我认为你有一些误解。对于文本分类任务,如果您的输入是一段文本(一个句子),则应该将整个句子视为单个特征列。因此每个数据点只有一个文本列NOT很多专栏。此列中的值通常是所有标记的组合嵌入。这就是我们将 var-length 稀疏特征(未知数量的文本标记)转换为一个密集特征(例如,固定的 256 维浮点向量)的方式。
让我们从一个_CategoricalColumn
.
cat_column_with_vocab = tf.feature_column.categorical_column_with_vocabulary_list(
key='my-text',
vocabulary_list=vocab_list)
请注意,如果您的词汇量很大,则应该使用categorical_column_with_vocabulary_file
.
我们通过使用初始化器从检查点读取(如果我们有预先训练的嵌入)或随机化来创建嵌入列。
embedding_initializer = None
if has_pretrained_embedding:
embedding_initializer=tf.contrib.framework.load_embedding_initializer(
ckpt_path=xxxx)
else:
embedding_initializer=tf.random_uniform_initializer(-1.0, 1.0)
embed_column = embedding_column(
categorical_column=cat_column_with_vocab,
dimension=256, ## this is your pre-trained embedding dimension
initializer=embedding_initializer,
trainable=False)
假设你有另一个密集特征price
:
price_column = tf.feature_column.numeric_column('price')
创建您的特色栏
columns = [embed_column, price_column]
构建模型:
features = tf.parse_example(...,
features=make_parse_example_spec(columns))
dense_tensor = tf.feature_column.input_layer(features, columns)
for units in [128, 64, 32]:
dense_tensor = tf.layers.dense(dense_tensor, units, tf.nn.relu)
prediction = tf.layers.dense(dense_tensor, 1)
顺便说一下,对于tf.parse_example
要工作,这假设您的输入数据是tf.Example
像这样(文本protobuf):
features {
feature {
key: "price"
value { float_list {
value: 29.0
}}
}
feature {
key: "my-text"
value { bytes_list {
value: "this"
value: "product"
value: "is"
value: "for sale"
value: "within"
value: "us"
}}
}
}
也就是说,我假设你有两种特征类型,一种是产品价格,另一种是产品的文字描述。你的词汇表将是以下的超集
["this", "product", "is", "for sale", "within", "us"].