Tensorflow 在tf 2.0的tf.data.Dataset.map(图形模式)中将tf.Tensor转换为numpy数组
我正在使用TF2.0。显然,map转换是在graph模式下完成的(我假设在tf2.0中,一切都默认在急切模式下进行) 我有一个Tensorflow 在tf 2.0的tf.data.Dataset.map(图形模式)中将tf.Tensor转换为numpy数组,tensorflow,tensorflow2.0,Tensorflow,Tensorflow2.0,我正在使用TF2.0。显然,map转换是在graph模式下完成的(我假设在tf2.0中,一切都默认在急切模式下进行) 我有一个tf.Tensor,我想把它转换成一个numpy数组,在增广函数中使用它 创建数据集后,我正在使用映射转换: dataset = tf.data.Dataset.from_tensor_slices((images, labele)) dataset = dataset.map(random_gradient, num_parallel_calls=tf.data.exp
tf.Tensor
,我想把它转换成一个numpy
数组,在增广函数中使用它
创建数据集
后,我正在使用映射
转换:
dataset = tf.data.Dataset.from_tensor_slices((images, labele))
dataset = dataset.map(random_gradient, num_parallel_calls=tf.data.experimental.AUTOTUNE)
函数随机梯度为:
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
转换为random\u gradient()
中的numpy
数组,使用x=x.numpy()
,它会说:
***AttributeError:“Tensor”对象没有属性“numpy”
这是因为我们不是在急切模式下
如果有人能帮我解决这个问题,我将不胜感激。我将mask3d
转换为tf.Tensor
,并最终扩展最后一个维度以再次获得4D图像。这暂时解决了我的问题,因为输入x
只有一个通道
但是,问题仍然悬而未决
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)
# 3D mask3d
mask3d = tf.convert_to_tensor(mask3d)
# 3D x
x = x[:, :, :, img_channel]*mask3d
# 4D x
x = tf.expand_dims(x, 3)
return x
在dataset.map()中有一个使用tf.py_函数的选项。这将确保您的张量是具有.numpy()属性的渴望张量