首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >将tf.dataset作为字典的键传递

将tf.dataset作为字典的键传递
EN

Stack Overflow用户
提问于 2021-06-18 03:20:41
回答 1查看 135关注 0票数 3

我有一个与将tf.dictionary的元素作为字典的键传递相关的问题。我已经将其简化为以下最小示例:

代码语言:javascript
复制
def example(x,d):
   w=tf.vectorized_map(lambda y: d[y],tf.cast(x, tf.string))
   return w


dataset = tf.data.Dataset.from_tensor_slices([['a','d','s'],['b','e','a'],['c','f','d']])
d={'a':1,'b':2,'c':3,'d':4,'e':6,'f':5,'s':1}
dataset.map(lambda x: example(x,d))

我得到了错误:

代码语言:javascript
复制
TypeError: Failed to convert object of type <class 'tensorflow.python.util.object_identity.Reference'> to Tensor. Contents: <Reference wrapping <tf.Tensor 'args_0:0' shape=(3,) dtype=string>>. Consider casting elements to a supported type.

我试图解决这个问题,删除tf.cast(x, tf.string)并通过tf.map_fn更改tf.vectorized_map。在这两种情况下,我都得到相同的错误。

如何运行代码?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2021-06-18 03:42:44

您可以使用tf.lookup.StaticHashTable来实现这一点。

代码语言:javascript
复制
import tensorflow as tf
keys_tensor = tf.constant(['a', 'b', 'c', 'd', 'e', 'f', 's'])
vals_tensor = tf.constant([1, 2, 3, 4, 6, 5, 1])
table = tf.lookup.StaticHashTable(
    tf.lookup.KeyValueTensorInitializer(keys_tensor, vals_tensor),
    default_value=-1)

dataset = tf.data.Dataset.from_tensor_slices([['a','d','s'],['b','e','a'],['c','f','d']])
ds=dataset.map(lambda x:table[x])

for x in ds:
  print(x)
'''
tf.Tensor([1 4 1], shape=(3,), dtype=int32)
tf.Tensor([2 6 1], shape=(3,), dtype=int32)
tf.Tensor([3 5 4], shape=(3,), dtype=int32)
'''
票数 4
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/68025398

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档