tf.lookup.StaticHashTable,以列表(任意大小)作为值

Viv*_*ian 5 python lookup dictionary hashtable tensorflow

我想将每个人的名字与一个数字列表相关联。

keys = ["Fritz", "Franz", "Fred"]
values = [[1, 2, 3], [4, 5], [6, 7, 8, 9]]
Run Code Online (Sandbox Code Playgroud)

如果我运行以下命令:

import tensorflow as tf
table = tf.lookup.StaticHashTable(tf.lookup.KeyValueTensorInitializer(keys, values), default_value=0)
Run Code Online (Sandbox Code Playgroud)

,我得到 aValueError: Can't convert non-rectangular Python sequence to Tensor. 因为列表大小不同,因此无法转换为 a tf.Tensor

是否有另一种方法将张量的值与任意形状的列表相关联?

感谢您的帮助 :)

小智 7

StaticHashTable- 从 TF 2.3 开始 - 无法返回多维值,更不用说参差不齐的值了。因此,尽管填充了值,还是创建了一个像这样的哈希表:

keys = ["Fritz", "Franz", "Fred"]
values = [[1, 2, 3, -1], [4, 5, -1, -1], [6, 7, 8, 9]]
table_init = tf.lookup.KeyValueTensorInitializer(keys, values)
table = tf.lookup.StaticHashTable(table_init, -1)
Run Code Online (Sandbox Code Playgroud)

会抛出以下错误:

InvalidArgumentError: Expected shape [3] for value, got [3,4] [Op:LookupTableImportV2]
Run Code Online (Sandbox Code Playgroud)

为了避免这种情况,您可以使用密集哈希表,尽管它处于实验模式。密集哈希表和静态哈希表都不提供对参差不齐的键或值的支持。因此,最好的选择是填充您的值,并创建一个密集的哈希表。在查找过程中,您可以将它们拉回来。整体代码如下所示:

keys = ["Fritz", "Franz", "Fred"]
values = [[1, 2, 3, -1], [4, 5, -1, -1], [6, 7, 8, 9]]
table = tf.lookup.experimental.DenseHashTable(key_dtype=tf.string, value_dtype=tf.int64, empty_key="<EMPTY_SENTINEL>", deleted_key="<DELETE_SENTINEL>", default_value=[-1, -1, -1, -1])
table.insert(keys, values)
Run Code Online (Sandbox Code Playgroud)

在查找过程中:

InvalidArgumentError: Expected shape [3] for value, got [3,4] [Op:LookupTableImportV2]
Run Code Online (Sandbox Code Playgroud)