从TensorFlow文档中可以清楚地了解如何使用tf.feature_column.categorical_column_with_vocabulary_list
创建一个功能列,该功能列将一些字符串作为输入并输出一个热矢量。例如
vocabulary_feature_column =
tf.feature_column.categorical_column_with_vocabulary_list(
key="vocab_feature",
vocabulary_list=["kitchenware", "electronics", "sports"])
让我们说"kitchenware"
映射到[1,0,0]
,"electronics"
映射到[0,1,0]
。我的问题与将字符串列表作为一项功能有关。例如,如果要素值为["kitchenware","electronics"]
,那么所需的输出将为[1,1,0]
。输入列表长度不固定,但输出维度为。
用例是一个直接的词袋类型模型(显然有一个更大的词汇表!)。
实现此目的的正确方法是什么?
答案 0 :(得分:12)
以下是如何将数据馈送到指标列的示例:
features = {'letter': [['A','A'], ['C','D'], ['E','F'], ['G','A'], ['X','R']]}
letter_feature = tf.feature_column.categorical_column_with_vocabulary_list(
"letter", ["A", "B", "C"], dtype=tf.string)
indicator = tf.feature_column.indicator_column(letter_feature)
tensor = tf.feature_column.input_layer(features, [indicator])
with tf.Session() as session:
session.run(tf.global_variables_initializer())
session.run(tf.tables_initializer())
print(session.run([tensor]))
哪个输出:
[array([[2., 0., 0.],
[0., 0., 1.],
[0., 0., 0.],
[1., 0., 0.],
[0., 0., 0.]], dtype=float32)]
答案 1 :(得分:2)
你应该使用tf.feature_column.indicator_column 见https://www.tensorflow.org/versions/master/api_docs/python/tf/feature_column/indicator_column