具有列表(任意大小)作为值的tf.lookup.StaticHashTable

2024-05-12 17:38:47 发布

您现在位置:Python中文网/ 问答频道 /正文

我想给每个人的名字关联一个数字列表

keys = ["Fritz", "Franz", "Fred"]
values = [[1, 2, 3], [4, 5], [6, 7, 8, 9]]

如果我运行以下命令:

import tensorflow as tf
table = tf.lookup.StaticHashTable(tf.lookup.KeyValueTensorInitializer(keys, values), default_value=0)

,我得到一个ValueError: Can't convert non-rectangular Python sequence to Tensor. 由于列表的大小不同,因此无法转换为tf.Tensor

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

谢谢你的帮助:)


Tags: import命令列表tftensorflowas数字keys
1条回答
网友
1楼 · 发布于 2024-05-12 17:38:47

StaticHashTable-从TF2.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)

将抛出以下错误:

InvalidArgumentError: Expected shape [3] for value, got [3,4] [Op:LookupTableImportV2]

为了避免这种情况,您可以使用Dense hash tables,尽管它处于实验模式。密集散列表和静态散列表都不支持不规则键or values。因此,最好的办法是填充值,并创建一个密集的哈希表。在查找过程中,您可以将它们拉回。总体代码如下所示:

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)

在查找过程中:

>>> tf.RaggedTensor.from_tensor(table.lookup(['Franz', 'Emil']), padding=-1)
<tf.RaggedTensor [[4, 5], []]>

相关问题 更多 >