gpt4 book ai didi

python - 如何为分类值列表的列创建嵌入

转载 作者:太空宇宙 更新时间:2023-11-04 04:12:25 25 4
gpt4 key购买 nike

我在决定如何为我的 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 的输入必须是由任何 categorical_column_* 函数创建的 CategoricalColumn

# 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 ]]

关于python - 如何为分类值列表的列创建嵌入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56099266/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com