tf.lookup.StaticHashTable 以列表(任意大小)作为值
tf.lookup.StaticHashTable with lists (of arbitrary sizes) as values
我想为每个人的名字关联一个数字列表。
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
.
是否有另一种方法可以将张量的值关联到任意形状的列表?
感谢您的帮助:)
StaticHashTable
- 从 TF 2.3 开始 - 不能 return 多维值,更不用说参差不齐的值了。因此,尽管填充了值,但还是创建了一个散列 table,如下所示:
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 although it is in experimental mode. Neither dense nor static hash tables provide support for ragged keys or values。所以你最好的选择是填充你的值,并创建一个密集的哈希 table。在查找期间,您可以将它们抹去。整体代码如下所示:
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], []]>
我想为每个人的名字关联一个数字列表。
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
.
是否有另一种方法可以将张量的值关联到任意形状的列表?
感谢您的帮助:)
StaticHashTable
- 从 TF 2.3 开始 - 不能 return 多维值,更不用说参差不齐的值了。因此,尽管填充了值,但还是创建了一个散列 table,如下所示:
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 although it is in experimental mode. Neither dense nor static hash tables provide support for ragged keys or values。所以你最好的选择是填充你的值,并创建一个密集的哈希 table。在查找期间,您可以将它们抹去。整体代码如下所示:
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], []]>