要素列嵌入查找

Kri*_*naa 4 tensorflow tensorflow-datasets

我一直在使用tensorflow中的数据集和feature_columns(https://developers.googleblog.com/2017/11/introducing-tensorflow-feature-columns.html).我发现它们具有分类功能以及从分类功能创建嵌入功能的方法.但是在处理nlp任务时,我们如何创建单个嵌入查找?

例如:考虑文本分类任务.每个数据点都有很多文本列,但它们不是单独的类别.我们如何为所有这些列创建和使用单个嵌入查找?

下面是我目前如何使用嵌入功能的示例.我正在为每列构建一个分类功能,并使用它来创建嵌入.问题是对于不同的列,相同单词的嵌入可能不同.

def create_embedding_features(key, vocab_list=None, embedding_size=20):
    cat_feature = \
        tf.feature_column.categorical_column_with_vocabulary_list(
            key=key,
            vocabulary_list = vocab_list
            )
    embedding_feature = tf.feature_column.embedding_column(
            categorical_column = cat_feature,
            dimension = embedding_size
        )
    return embedding_feature

le_features_embd = [create_embedding_features(f, vocab_list=vocab_list)
                     for f in feature_keys]
Run Code Online (Sandbox Code Playgroud)

gre*_*ess 5

我觉得你有一些误解.对于文本分类任务,如果输入是一段文本(句子),则应将整个句子视为单个要素列.因此,每个数据点只有一个文本列,而不是很多列.此列中的值通常是所有标记的组合嵌入.这就是我们将var-length稀疏特征(未知数量的文本标记)转换为一个密集特征(例如,固定的256维浮点矢量)的方式.

让我们从一开始吧_CategoricalColumn.

cat_column_with_vocab = tf.feature_column.categorical_column_with_vocabulary_list(
    key='my-text',
    vocabulary_list=vocab_list)
Run Code Online (Sandbox Code Playgroud)

请注意,如果您的词汇量很大,您应该使用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)
Run Code Online (Sandbox Code Playgroud)

假设您有另一个密集功能price:

price_column = tf.feature_column.numeric_column('price')
Run Code Online (Sandbox Code Playgroud)

创建要素列

columns = [embed_column, price_column]
Run Code Online (Sandbox Code Playgroud)

建立模型:

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)
Run Code Online (Sandbox Code Playgroud)

顺便说一句,为了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"
    }}
  }
}
Run Code Online (Sandbox Code Playgroud)

也就是说,我假设您有两种要素类型,一种是产品价格,另一种是产品的文字说明.你的词汇表将是一个超集

["this", "product", "is", "for sale", "within", "us"].
Run Code Online (Sandbox Code Playgroud)