python - 如何为作为分类值列表的列创建嵌入
问题描述
我在决定如何为我的 DNN 模型的分类特征创建嵌入时遇到了一些麻烦。该功能由一组非固定标签组成。
该功能如下:
column = [['Adventure','Animation','Comedy'],
['Adventure','Comedy'],
['Adventure','Children','Comedy']
我想这样做,tensorflow
所以我知道tf.feature_column模块应该可以工作,我只是不知道要使用哪个版本。
谢谢!
解决方案
首先,您需要将特征填写到相同的长度。
import itertools
import numpy as np
column = np.array(list(itertools.zip_longest(*column, fillvalue='UNK'))).T
print(column)
[['Adventure' 'Animation' 'Comedy']
['Adventure' 'Comedy' 'UNK']
['Adventure' 'Children' 'Comedy']]
然后,您可以使用tf.feature_column.embedding_column
为分类特征创建嵌入。的输入embedding_column
必须是CategoricalColumn
由任何categorical_column_*
函数创建的。
# if you have big vocabulary list in files, you can use tf.feature_column.categorical_column_with_vocabulary_file
cat_fc = tf.feature_column.categorical_column_with_vocabulary_list(
'cat_data', # identifying the input feature
['Adventure', 'Animation', 'Comedy', 'Children'], # vocabulary list
dtype=tf.string,
default_value=-1)
cat_column = tf.feature_column.embedding_column(
categorical_column =cat_fc,
dimension = 5,
combiner='mean')
categorical_column_with_vocabulary_list
将忽略,'UNK'
因为'UNK'
词汇表中没有。dimension
指定嵌入的维度,并combiner
指定如果单行中有多个条目,则如何减少,而 'mean' 中的默认值是embedding_column
.
结果:
tensor = tf.feature_column.input_layer({'cat_data':column}, [cat_column])
with tf.Session() as session:
session.run(tf.global_variables_initializer())
session.run(tf.tables_initializer())
print(session.run(tensor))
[[-0.694761 -0.0711766 0.05720187 0.01770079 -0.09884425]
[-0.8362482 0.11640486 -0.01767573 -0.00548441 -0.05738768]
[-0.71162754 -0.03012567 0.15568805 0.00752804 -0.1422816 ]]
推荐阅读
- c++ - 如何获取传递给函数的数组的长度?
- unix - 如何调试 Makefile?
- office-js - Word 加载项 - 如何读取自定义属性并返回值?
- python - 如果文件不存在,电子邮件警报 - Python
- sql-server - 如何在SQL中对相邻行进行分组并对数据求和
- arduino - arduino nodemcu 为板 esp32 编译错误
- javascript - 如何动态导入 SVG 并内联渲染
- java - 如何在 Java 上使用时间/日期值进行操作?
- mysql - 无法将 WSO2 API 管理器连接到 MariaDB
- azure - 如何在不使用客户端 ID 和密钥重定向的情况下从 azure 广告中获取登录用户的用户 ID_token