首页 > 解决方案 > 在 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数组,但这里传递的参数xtf.Tensor. 当我想转换x为, withnumpy内的数组时,它说:random_gradient()x = x.numpy()

*** AttributeError: 'Tensor' object has no attribute 'numpy'

这是因为我们不在eager mode.

如果有人能帮我解决这个问题,我将不胜感激。

标签: tensorflowtensorflow2.0

解决方案


在 dataset.map() 中有一个使用 tf.py_function 的选项。这将确保您的张量是具有 .numpy() 属性的 Eager 张量。


推荐阅读