簡體   English   中英

如何將 PyTorch 張量轉換為 Numpy ndarray

[英]How to convert PyTorch Tensor to Numpy ndarray

我有這個功能可以旋轉 MNIST 圖像。 該函數返回一個 pytorch 張量。 我更熟悉 Tensorflow,我想將 pytorch 張量轉換為我可以使用的 numpy ndarray。 有什么功能可以讓我這樣做嗎? 我試圖通過在tensor(img.rotate(rotation)).view(784)之后添加 .numpy() 來稍微修改該函數並將其保存在一個空的 ndarray 中,但這不起作用。 參數d是保存在.pt MNIST 數據(我認為是 pytensor)。 謝謝! (很想知道是否有可以旋轉數據的 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