如何将以下 TensorFlow 代码转换为 PyTorch?

问题描述

我正在寻找 GAN 模型的损失函数,然后 this one 出来了:

gd_loss = tf.reduce_sum(tf.square(tf.abs(dx_real) - tf.abs(dx_fake))) + \
              tf.reduce_sum(tf.square(tf.abs(dy_real) - tf.abs(dy_fake))) + \
              tf.reduce_sum(tf.square(tf.abs(dz_real) - tf.abs(dz_fake)))

但我想将以下内容转换为 PyTorch,因为我使用的是 PyTorch 张量:

dx_real = t_target_image[:,1:,:,:] - t_target_image[:,:-1,:]

其中 t_target_image 是 TensorFlow 中的张量。

我该怎么做?

解决方法

PyTorch 擅长对常见矩阵运算坚持纯 python 语法,所以你可以这样做

gd_loss = ((dx_real.abs() - dx_fake.abs())**2).sum() + \
              ((dy_real.abs() - dy_fake.abs())**2).sum() + \
              ((dz_real.abs() - dz_fake.abs())**2).sum()

如果您的问题特别是关于将 tensorflow 张量转换为 pytorch 张量,您应该先转换为 numpy,然后使用 torch.as_tensor 转换为 pytorch。

,

解决办法是:

dx_real = real[:,:,1:,:] - real[:,:-1,:]
dy_real = real[:,:]
dz_real = real[:,1:] - real[:,:-1]
dx_fake = fake[:,:] - fake[:,:]
dy_fake = fake[:,:]
dz_fake = fake[:,1:] - fake[:,:-1]
gd_loss = torch.sum(torch.pow(torch.abs(dx_real) - torch.abs(dx_fake),2),dim=(2,3,4)) + \
          torch.sum(torch.pow(torch.abs(dy_real) - torch.abs(dy_fake),4)) + \
          torch.sum(torch.pow(torch.abs(dz_real) - torch.abs(dz_fake),4))
return torch.sum(gd_loss)`