tf.feature_column详解_tf.feature_column.embedding_column-程序员宅基地

 

 

tensorflow2.0 环境下的tfrecord读写及tf.io.parse_example和tf.io.parse_single_example的区别中已经讲到了从tfrecord 中读取数据需要提供一个dict,里面包含了特征名称和特征的类型,如果我们特征很少,只需要手写这个dict就可以。但是当特征非常多的时候,就需要更方便的工具来生成这个dict。这个工具的就是tf.feature_column,同时tf.feature_column也是一个特征工程的工具,可以用来自动one-hot处理,还有hash分桶等处理。

tf.feature_column中的函数主要包括以下的的函数,下面会分别进行讲解

数值类型tf.feature_column.numeric_column

tf.feature_column.numeric_column(
    key, shape=(1,), default_value=None, dtype=tf.dtypes.float32, normalizer_fn=None
)

tf.feature_column.numeric_column用于抽取数值类型的特征,即dense特征,在tensorflow2.0 环境下的tfrecord读写及tf.io.parse_example和tf.io.parse_single_example的区别 中,7日内的消费和7日内打开淘宝的天数都用该函数定义:

pay = tf.feature_column.numeric_column('pay',shape=(1,), default_value=None, dtype=tf.dtypes.float32, normalizer_fn=None)
use_day = tf.feature_column.numeric_column("use_day",shape=(1,), default_value=None, dtype=tf.dtypes.int64, normalizer_fn=None)

应该注意的是key必须和tfrecord 中的key对应。shape必须与tfrecord中的shape对应,如果我们还有一个特征,是用户连续几天的消费金额[99.9, 249, 33] ,那么shape就要被定义成(3, )

类别特征系列

解析类别特征的方法最常用的有

方法 生成的子类
categorical_column_with_identity CategoricalColumn
categorical_column_with_vocabulary_list CategoricalColumn,存有vocabulary_list
categorical_column_with_vocabulary_file CategoricalColumn,存有vocabulary_file
categorical_column_with_hash_bucket HashedCategoricalColumn

 

 

categorical_column_with_vocabulary_list

根据sparse特征列表定义特征

city = tf.feature_column.categorical_column_with_vocabulary_list("city",["shanghai","beijing","guangzhou","tianjin","shenzhen"])

这种方法的缺点是只能用于数量较少的种类,比如性别,省份等。种类非常多的catogery,例如店铺id,就非常不适合这种方法了。

categorical_column_with_identity

这个方法用于已经编码的sparse特征,例如,店铺id虽然数量非常大,但是已经把每个店铺id都从0开始编码,那么就可以用

poi = tf.feature_column.categorical_column_with_identity("poi", num_buckets=10, default_value=0)

其中,num_bucket是最大编号

tf.feature_column.categorical_column_with_vocabulary_file

前面已经说了,当sparse特征的种类数量非常巨大的时候,就不能用用categorical_column_with_vocabulary_list了,用categorical_column_with_identity 又需要事先对sparse特征编码,这时候可以用tf.feature_column.categorical_column_with_vocabulary_file命令,读取sparse特征的所有可能取值。当然这种方法的效率也是比较低的,在要求低延迟的线上是不太划算的。

tf.feature_column.categorical_column_with_vocabulary_file(
    key, vocabulary_file, vocabulary_size=None, dtype=tf.dtypes.string,
    default_value=None, num_oov_buckets=0
)

categorical_column_with_hash_bucket

如果sparse特征非常庞大,例如上面的poi可以写成

poi = tf.feature_column.categorical_column_with_hash_bucket("poi", hash_bucket_size=10, dtype=tf.dtypes.int64)

但是应该注意的是,hash_bucket_size的大小应该留有充分的冗余量,否则非常容易出现hash冲突,在这个例子中,一共有3个店铺,把hash_bucket_size设定为10,仍然得到了hash冲突的结果,这样poi的信息就被丢失了一些信息

 

tf.feature_column.indicator column 

tf.feature_column.indicator column  是一个onehot工具,用于把sparse特征进行onehot 变换,用于把categorical_column_with_*工具生成的特征变成onehot 编码

tf.feature_column.indicator column 的入参非只有一个,就是categorical_column_with_*的结果。

poi = tf.feature_column.categorical_column_with_hash_bucket("poi", hash_bucket_size=15, dtype=tf.dtypes.int64)
poi_idc = tf.feature_column.indicator_column(poi)

这里还有一个有趣的细节,在tensorflow2.0 环境下的tfrecord读写及tf.io.parse_example和tf.io.parse_single_example的区别中我们已经提到了tf.io.parse_example和tf.io.parse_single_example的区别。在这里他们还有另一个区别

poi = tf.feature_column.categorical_column_with_hash_bucket("poi", hash_bucket_size=15, dtype=tf.dtypes.int64)   #创建poi特征
poi_idc = tf.feature_column.indicator_column(poi)  #onehot处理
feature_column = [poi_idc] 
feature = tf.feature_column.make_parse_example_spec(feature_column)  #生成poi的featuredict
path = "./tfrecord"
data = tf.data.TFRecordDataset(path)  #读取tfrecord
#分别用tf.io.parse_example 和 tf.io.parse_single_example 解析数据
data2 = data.map(lambda x : tf.io.parse_example(tf.reshape(x,[1]), features = feature))
data3 = data.map(lambda x : tf.io.parse_single_example(x, features = feature))

tf.io.parse_example得到的poi是一个形状为[1 3]的张量,而tf.io.parse_single_example得到的是一个形状为[3]的张量,这个区别就直接决定了

for batch in data2:
    tensor = tf.compat.v1.feature_column.input_layer(batch,feature_column)  #可以执行
for batch2 in data3:
    tensor2 = tf.compat.v1.feature_column.input_layer(batch2,feature_column)  #报错
 

如果看不懂也没关系,只需要记住tf.io.parse_example的结果,在用tf.compat.v1.feature_column.input_layer生成输入时,可以把所有的特征一起生成

而记住tf.io.parse_single_example的结果,只能对sparse特征逐个生成,然后合并成起来。

tf.feature_column.embedding_column

用于生成embedding后的张量

tf.feature_column.embedding_column(
    categorical_column, dimension, combiner='mean', initializer=None,
    ckpt_to_load_from=None, tensor_name_in_ckpt=None, max_norm=None, trainable=True,
    use_safe_embedding_lookup=True
)

他的几个入参意义分别是

categorical_column: categorical_column_with_* 工具的结果

dimension:embedding后的维度

combiner:对于多种类的sparse特征怎么组合,Currently 'mean', 'sqrtn' and 'sum' are supported

其他配置全部用默认就好了,绝大部分情况都不会有什么影响

应该注意的是,与indicator的一样,用tf.io.parse_single_example会生成一个embedding后的举证,而tf.io.parse_example会得到一个向量。例如

poi = tf.feature_column.categorical_column_with_hash_bucket("poi", hash_bucket_size=15, dtype=tf.dtypes.int64)
poi_ebd = tf.feature_column.embedding_column(poi,dimension = 3,combiner = "mean")
feature_column = [poi_ebd]
feature = tf.feature_column.make_parse_example_spec(feature_column)
path = "./tfrecord"
data = tf.data.TFRecordDataset(path)
data2 = data.map(lambda x : tf.io.parse_example(tf.reshape(x,[1]), features = feature))
data3 = data.map(lambda x : tf.io.parse_single_example(x, features = feature))
for batch in data2:
    tensor = tf.compat.v1.feature_column.input_layer(batch,feature_column)
for batch2 in data3:
    tensor2 = tf.compat.v1.feature_column.input_layer(batch2,feature_column)
print(tensor)
print(tensor2)

result:
tf.Tensor([[0.00952441 0.01638425 0.29906932]], shape=(1, 3), dtype=float32)
tf.Tensor(
[[-0.59089464 -0.52776134  0.3303768 ]
 [ 0.74979115  0.11539479  0.3902657 ]
 [ 0.08098221  0.21678661 -0.11189163]], shape=(3, 3), dtype=float32)

tf.feature_column.make_parse_example_spec

tf.io.parse_example和tf.io.parse_single_example需要一个dict,定义特征名称和特征类型(fixedlenfeature还是varlenfeature)

tf.feature_column.make_parse_example_spec用于生成这个dict,他的入参必须是个可迭代对象,一般都是一个list,list的元素是上面讲过的所有函数的result。

这里应该非常注意的是,tf.feature_column.indicator column 和tf.feature_column.embedding_column 并不影响tf.feature_column.make_parse_example_spec,也就是说,一个特征是否经过了tf.feature_column.indicator column 和tf.feature_column.embedding_column 后tf.feature_column.make_parse_example_spec的结果是一样的,tf.io.parse_example和tf.io.parse_single_example的结果也是一样的。

例子:

poi = tf.feature_column.categorical_column_with_hash_bucket("poi", hash_bucket_size=15, dtype=tf.dtypes.int64)  #定义poi特征
poi_ebd = tf.feature_column.embedding_column(poi,dimension = 3,combiner = "mean") #poi做embedding
poi_idc = tf.feature_column.indicator_column(poi)  #poi做indicator


feature_column = [poi]
feature_column2 = [poi_ebd]
feature_column3 = [poi_idc]

feature = tf.feature_column.make_parse_example_spec(feature_column)
feature2 = tf.feature_column.make_parse_example_spec(feature_column2)
feature3 = tf.feature_column.make_parse_example_spec(feature_column3)

print(feature)
print(feature2)
print(feature3)

===============================================================

result:
{'poi': VarLenFeature(dtype=tf.int64)}
{'poi': VarLenFeature(dtype=tf.int64)}
{'poi': VarLenFeature(dtype=tf.int64)}

===============================================================

path = "./tfrecord"
data = tf.data.TFRecordDataset(path)
data2 = data.map(lambda x : tf.io.parse_example(tf.reshape(x,[1]), features = feature))
data3 = data.map(lambda x : tf.io.parse_example(tf.reshape(x,[1]), features = feature2))
data4 = data.map(lambda x : tf.io.parse_example(tf.reshape(x,[1]), features = feature3))

for batch in data2:
    tensor = tf.compat.v1.feature_column.input_layer(batch,feature_column)
    print(tf.sparse.to_dense(batch["poi"]))
for batch2 in data3:
    tensor2 = tf.compat.v1.feature_column.input_layer(batch2,feature_column)
    print(tf.sparse.to_dense(batch2["poi"]))
for batch3 in data4:
    tensor3 = tf.compat.v1.feature_column.input_layer(batch3,feature_column)
    print(tf.sparse.to_dense(batch2["poi"]))



result:
tf.Tensor([[1 3 2]], shape=(1, 3), dtype=int64)
tf.Tensor([[1 3 2]], shape=(1, 3), dtype=int64)
tf.Tensor([[1 3 2]], shape=(1, 3), dtype=int64)

特征工程

可以看到tf.feature_column.make_parse_example_spec和tf.io.parse_example和tf.io.parse_single_example 仅仅是从tfrecord 中读取数据,并不会对数据做任何的特征工程的处理。

那么特征工程在哪个环节进行呢?

poi = tf.feature_column.categorical_column_with_hash_bucket("poi", hash_bucket_size=15, dtype=tf.dtypes.int64)  #定义poi特征
poi_ebd = tf.feature_column.embedding_column(poi,dimension = 3,combiner = "mean") #poi做embedding



feature_column2 = [poi_ebd]

feature2 = tf.feature_column.make_parse_example_spec(feature_column2)



print(feature2)


===============================================================

result:
{'poi': VarLenFeature(dtype=tf.int64)}


===============================================================

path = "./tfrecord"
data = tf.data.TFRecordDataset(path)

data2 = data.map(lambda x : tf.io.parse_example(tf.reshape(x,[1]), features = feature2))


for batch in data2:
    tensor = tf.compat.v1.feature_column.input_layer(batch,feature_column2)
    print(tf.sparse.to_dense(batch["poi"]))




result:
tf.Tensor([[1 1 1]], shape=(1, 3), dtype=int64)

从上面的代码可以看到categorical_column_with_identity、categorical_column_with_vocabulary_list、categorical_column_with_vocabulary_file、categorical_column_with_hash_bucket 保存了数值化方式,

embedding_column, bucketized_column, indicator_column,保存了特征工程方式,

最后通过调用feature_column.input_layer,实现了特征工程的处理

 

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/kangshuangzhu/article/details/106851826

智能推荐

概率论总结_p(∪n i=1ai) ≤ pn i=1 p(ai)-程序员宅基地

文章浏览阅读823次,点赞2次,收藏13次。随机事件与概率基本概念随机试验试验可以在相同的条件下重复进行试验所有可能结果是明确可知道的,并且不止一个每一次试验会出现哪一个结果,事先并不确定事件随机事件A,B,C...A,B,C...A,B,C...必然事件Ω\OmegaΩ不可能事件∅\varnothing∅样本空间样本点:随机试验的每一个可能结果称为样本点,记为ω\omegaω样本空间:样本点的全体组成的集合称为样本空间,记为Ω\OmegaΩ基本事件:由一个样本点构成的事件称为基本事件随机事件AAA是由若干个基本_p(∪n i=1ai) ≤ pn i=1 p(ai)

Nuxt中使用Vuex(新版,简单入门)_nuxt vuex-程序员宅基地

文章浏览阅读8.5k次,点赞2次,收藏17次。1.前言因为我学的是后端开发,前端不是很厉害,如果有什么不对的地方请评论指出,谢谢!看这篇文章你需要对Vuex有一定的了解 官方链接做课设的时候使用到了Nuxt框架,需要做登录,也就结识了Vuex,其实以前就学过Vuex,但是一直不知道这个东西有什么优势,特点。这次我在实际使用中就用到了一个非常好用的特点,官方的解释如下:Vuex 的状态存储是响应式的。当 Vue 组件从 store ..._nuxt vuex

vue点击按钮改变按钮样式_vue点击按钮切换样式-程序员宅基地

文章浏览阅读3.7k次。【代码】vue点击按钮改变按钮样式。_vue点击按钮切换样式

图论学习-最短路模型-程序员宅基地

文章浏览阅读2k次,点赞20次,收藏44次。这里只是我对于最短路模型学习的一个记录,不正确的地方希望大家指出。文章目录最短路模型一、 什么是最短路?1.1 概念1.2 基本术语二、主要模型2.1 dijkstra2.1.1 步骤2.1.2 画图理解2.1.3 为什么dijkstra不能处理负权边?2.2 堆优化的dijkstra2.3 bellman_ford2.3.1 三角形不等式2.3.2 步骤2.3.3 代码实现2.4 spfa2.4.1 步骤2.4.2 代码实现2.4.3 主要问题2.5 floyd三、练习题目四、参考最短路模型一、 什_最短路模型

20210409因为内存条的兼容问题引起的编译aosp10莫名的异常_aosp 编译 segmentation fault-程序员宅基地

文章浏览阅读2.7k次。20210409因为内存条的兼容问题引起的编译aosp10莫名的异常内存使用2条32GB的内存条(3000MHz)https://item.jd.com/10025021240070.html酷兽(CUSO)ddr4 32g台式机内存 32g 3000MHz 酷兽夜枭系列【京选存储.稳定兼容】酷兽存储.实惠装机能手(内存终身保固.以换代修)京 东 价¥ 769.00 降价通知32g 3000MHz电脑使用的:dell的Inspiron-3880rootroot@rootroot-Ins_aosp 编译 segmentation fault

SSL_1072&&P2347【砝码称重】-程序员宅基地

文章浏览阅读72次。砝码称重题目设有1g、2g、3g、5g、10g、20g的砝码各若干枚(其总重<=1000),要求:输入方式:a1 a2 a3 a4 a5 a6(表示1g砝码有a1个,2g砝码有a2个,…,20g砝码有a6个)输出方式:N(N表示用这些砝码能称出的不同重量的个数,但不包括一个砝码也不用的情况)Sample Input1 1 0 0 0 0(注:下划线表示空格)Sample Output3//表示可以称出1g,2g,3g三种不同的重量。解析啊就这?!堂堂1996年分区联赛提高组第

随便推点

BZOJ 2301 [HAOI2011]Problem b(莫比乌斯反演)_[bzoj2301][haoi2011]-程序员宅基地

文章浏览阅读139次。题目链接:https://www.lydsy.com/JudgeOnline/problem.php?id=2301咱也不知道莫比乌斯函数,莫比乌斯反演怎么来的,直接用就得了...①莫比乌斯函数:else表示质因子分解后有质因子出现一次以上莫比乌斯函数跟着欧拉筛跑一遍就可以求出来②莫比乌斯反演的两种写法:其中f(i)是题目询问的东西,你发现直接求求..._[bzoj2301][haoi2011]

SpringBoot多文件压缩包下载(多附件zip格式)_springboot下载多个文件-程序员宅基地

文章浏览阅读7.4k次。文章目录前言 : 此 Demo 为 Windows 环境下演示,部署到服务器的话路径需改成服务器的路径。一、自定义工具类DownLoadZipUtil二、Dao层分析与sqlmapper层代码(DAO)三、Service层代码三、Controller层代码注意 : 文件的打包下载这里用到了临时路径,下面只需要关注方法ZipTempDownLoad即可,下面的代码实际需根据自己的逻辑需求去写。四、前端部分代码,此Demo前端用的vue五、效果展示前言 : 此 Demo 为 Windows 环境下演示,部_springboot下载多个文件

meta SEO(给搜索引擎看的meta标签 name keywords)_搜索 <meta name="keywords" content="氢能源、燃料、电池技术、清洁能源-程序员宅基地

文章浏览阅读1.8k次。<!-- 你挂载到域名上才有用 --> <meta name="keywords" content="游戏,音乐,体育">_搜索

CVPR2019 主动学习方面论文_cvpr 2019 active learning-程序员宅基地

文章浏览阅读498次。1 Learning Loss for Active Learning 论文下载直接预测样本的LossCVPR2019 论文接受列表_cvpr 2019 active learning

通信原理chapter2总结(内含多径效应和多普勒效应MATLAB仿真)_多普勒效应和多径效应 建模-程序员宅基地

文章浏览阅读4.8k次,点赞12次,收藏67次。第二章总结1.信道:通信系统中信道是指发送设备到接收设备之间信号传输的通道,是通信系统中的一个重要组成部分。2.分类:1)按照传输媒介:无线信道和有线信道;2)根据信道研究对象不同:调制信道,编码信道3)按照信道的冲激响应是否随时间变化:恒参信道,随参信道4)按照信道输入和输出符号是否离散:离散信道,连续信道3. 简介1)有线信道:利用人造的传导电或光信号的媒质来传输信号,如明线,..._多普勒效应和多径效应 建模

富士通01018z平板电脑评测_微软Surface Pro 7详细评测:仍旧是最好的二合一平板电脑...-程序员宅基地

文章浏览阅读1k次。今年10月初,当人们还沉浸在国庆放假的喜悦中的时候,大洋彼岸的微软在纽约召开新品发布会,一口气发布了6款Surface设备,除了惊艳的双屏电脑Surface Neo以及传说中的“Surface Phone”以不一样的形态和消费者见面之外,升级版的微软Surface Pro 7也是本次发布会的最大看点之一,微软Surface Pro 7跟着英特尔的节奏升级到了10代酷睿处理器,另外的一个看点则是增加..._farq01018z

推荐文章

热门文章

相关标签