首页 > 解决方案 > 在字典 Tensorflow 中查找数组内的列表

问题描述

我有一个张量,我想在其中查找并为每个单词输出一个 int。

我怎样才能滚动这个并为每个单词输出一个值?

table =tf.lookup.StaticHashTable(tf.lookup.TextFileInitializer(vocab_filename, tf.string, 0, tf.int64, 1, delimiter="!"),7) 
out=table.lookup(data[0])
print(out)

<tf.Tensor: shape=(231637,), dtype=string, numpy=
array([b"['honey', 'apple', 'tree', 'butter', 'olive oil', 'salt']",

标签: pythontensorflowdictionary

解决方案


您可以使用StaticVocabularyTable来实现相同的目的。下面是一个例子。

vocab = ["<1H OCEAN", "INLAND", "NEAR OCEAN", "NEAR BAY", "ISLAND"]
indices = tf.range(len(vocab), dtype=tf.int64)
table_init = tf.lookup.KeyValueTensorInitializer(vocab, indices)
num_oov_buckets = 20
table = tf.lookup.StaticVocabularyTable(table_init, num_oov_buckets) 

结果:

out = table.lookup(tf.constant(["NEAR OCEAN"]))
print(out)
tf.Tensor([2], shape=(1,), dtype=int64)

如果要从文本文件中创建Vocabulary List和创建Index values,可以按照以下示例进行操作。

num_oov_buckets = 3
input_tensor = tf.constant(["emerson", "lake", "palmer", "king", "crimnson"])
table = tf.lookup.StaticVocabularyTable(
    tf.lookup.TextFileInitializer(
        filename,
        key_dtype=tf.string, key_index=tf.lookup.TextFileIndex.WHOLE_LINE,
        value_dtype=tf.int64, value_index=tf.lookup.TextFileIndex.LINE_NUMBER,
        delimiter="\t"),
    num_oov_buckets)
out = table.lookup(input_tensor) 

您可以按照文档获取详细说明。


推荐阅读