tensorflow - 在 TF 2.0 中将 tf.Tensor 转换为 tf.data.Dataset.map(图形模式)中的 numpy 数组
问题描述
我正在使用TF 2.0。显然地图转换是在图形模式下完成的(我假设在 TF 2.0 中默认情况下一切都将在急切模式下)。
我有一个tf.Tensor
我想将其转换为numpy
数组以在增强函数中使用它。
创建后dataset
,我正在使用map
转换:
dataset = tf.data.Dataset.from_tensor_slices((images, labele))
dataset = dataset.map(random_gradient, num_parallel_calls=tf.data.experimental.AUTOTUNE)
功能random_gradient
是:
def random_gradient(x,
img_channel=0,
grad_range=[0.5, 1.5]):
# the shape of input x has to be cubic, i.e. d == h == w
intensity_grad = np.random.uniform(grad_range[0], grad_range[1], 1)[0]
d, h, w, _ = np.shape(x)
mask3d = np.zeros(shape=(d, h, w), dtype=np.float32)
mask2d = np.zeros(shape=(h, w), dtype=np.float32)
mask1d = np.linspace(1, intensity_grad, w, dtype=np.float32)
mask2d[:] = mask1d
mask3d[:] = mask2d
axis = np.random.randint(1, 3)
if axis == 1:
# gradient along the x axis
mask3d = np.swapaxes(mask3d, 0, 2)
elif axis == 2:
# gradient along the y axis
mask3d = np.swapaxes(mask3d, 1, 2)
x[:, :, :, img_channel] = x[:, :, :, img_channel]*mask3d
return x
如您所见,random_gradient()
适用于numpy
数组,但这里传递的参数x
是tf.Tensor
. 当我想转换x
为, withnumpy
内的数组时,它说:random_gradient()
x = x.numpy()
*** AttributeError: 'Tensor' object has no attribute 'numpy'
这是因为我们不在eager mode
.
如果有人能帮我解决这个问题,我将不胜感激。
解决方案
在 dataset.map() 中有一个使用 tf.py_function 的选项。这将确保您的张量是具有 .numpy() 属性的 Eager 张量。
推荐阅读
- python-3.x - 列表中的几个元素包含方括号,我想替换这些元素的括号
- ag-grid - 以编程方式设置集合类型过滤器时,浮动过滤器框不会更新
- r - R 条件变量
- javascript - 如何将 getFieldValues("Custom.RevisionCount", returnOriginalValue) 分配给 VSTS 自定义扩展 html 文件中的变量?
- javascript - 打字稿可选字段与可以未定义的字段
- php - 如何使我的回复显示为对评论的回复,而不是进入底部?
- laravel - Laravel:将 MySQL 行作为 html 表中的列
- python - 如何打印 <__main__.LinkedList object at 0x01BA8A90>?
- javascript - Promise.resolve() 和 just resolve() 之间的区别?
- c# - 如果启动窗口位于不同的项目/库中,如何在 App.xaml 中设置 StartupUri?