简体   繁体   English

如何将 PyTorch 张量转换为 Numpy ndarray

[英]How to convert PyTorch Tensor to Numpy ndarray

I have this function that rotates the MNIST images.我有这个功能可以旋转 MNIST 图像。 The function returns a pytorch Tensor.该函数返回一个 pytorch 张量。 I am more familiar with Tensorflow and I want to convert the pytorch tensor to a numpy ndarray that I can use.我更熟悉 Tensorflow,我想将 pytorch 张量转换为我可以使用的 numpy ndarray。 Is there a function that will allow me to do that?有什么功能可以让我这样做吗? I tried to modify the function a little bit by adding .numpy() after tensor(img.rotate(rotation)).view(784) and save it in an empty ndarray, but that didn't work.我试图通过在tensor(img.rotate(rotation)).view(784)之后添加 .numpy() 来稍微修改该函数并将其保存在一个空的 ndarray 中,但这不起作用。 Parameter d is MNIST data saved in .pt (pytensor, I think).参数d是保存在.pt MNIST 数据(我认为是 pytensor)。 Thanks!谢谢! (Would love to know if there is a tensorflow function that can rotate the data.) (很想知道是否有可以旋转数据的 tensorflow 函数。)

t = 1
min_rot = 1.0 * t / 20 * (180 - 0) + \
        0
max_rot = 1.0 * (t + 1) / 20 * \
    (180 - 0) + 0
rot = random.random() * (max_rot - min_rot) + min_rot
rotate_dataset(x_tr, rot)
def rotate_dataset(d, rotation):
    result = torch.FloatTensor(d.size(0), 784)
    tensor = transforms.ToTensor()

    for i in range(d.size(0)):
        img = Image.fromarray(d[i].numpy(), mode='L')
        result[i] = tensor(img.rotate(rotation)).view(784)
    return result

首先不转换为tensor怎么样:

result[i] = np.array(img.rotate(rotation)).flatten()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM