python - 将 tf.dataset 作为字典的键传递
问题描述
我有一个与将 tf.dictionary 的元素作为字典的键传递相关的问题。我已将其简化为以下最小示例:
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))
我得到错误:
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.vectorized_map
来解决它tf.map_fn
。在这两种情况下,我都会遇到相同的错误。
如何运行代码?
解决方案
您可以使用tf.lookup.StaticHashTable
来实现这一点。
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)
'''
推荐阅读
- ruby-on-rails - 我的 ruby on rails 应用程序关联错误
- c# - 字符串中的日期时间分别添加时间和日期
- charts - 我可以用谷歌图表库制作一个在两条线之间定义边界的面积图吗?
- firebase - Cordova + Firebase auth + ISO 无法打开页面,因为地址无效
- powershell - 如何使用 Invoke-Command 将 Bath 文件作为远程服务器运行?
- java - 如果我在并行流中使用 lambda 会发生死锁,但如果我使用匿名类则不会发生死锁?
- ios - UIScrollView 上的“CALayer 位置包含 NaN:[nan nan]”
- node.js - Express - 带有开始和结束帧的 res.download
- laravel - Laravel 路由未在控制器中调用函数
- r - setup_twitter_oauth 错误(consumer_key,consumer_secret,:找不到函数“setup_twitter_oauth”