【问题标题】:How to convert PyTorch Tensor to Numpy ndarray如何将 PyTorch 张量转换为 Numpy ndarray
【发布时间】:2020-06-27 02:52:40
【问题描述】:

我有这个功能可以旋转 MNIST 图像。该函数返回一个 pytorch 张量。我更熟悉 Tensorflow,我想将 pytorch 张量转换为我可以使用的 numpy ndarray。有没有可以让我这样做的功能?我尝试通过在tensor(img.rotate(rotation)).view(784) 之后添加 .numpy() 来稍微修改该函数并将其保存在一个空的 ndarray 中,但这不起作用。参数d 是保存在.pt 中的MNIST 数据(我认为是pytensor)。谢谢! (很想知道是否有可以旋转数据的张量流函数。)

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

【问题讨论】:

  • 什么不起作用?根据torch 文档,Tensor 对象有一个.numpy 方法。 save it to an empty ndarray 是什么意思?我不会要求可运行的代码(因为我没有torch),但您应该显示足够的代码和结果(甚至是错误),以便我们清楚地了解您的尝试。

标签: python numpy tensorflow computer-vision pytorch


【解决方案1】:

首先不转换为tensor 怎么样:

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

【讨论】:

  • 得到AttributeError: 'Image' object has no attribute 'flatten'
  • @AmartyaBarua 您可能还想将 numpy 数组转换为 float32
猜你喜欢
  • 2021-02-24
  • 2019-06-13
  • 1970-01-01
  • 2020-11-15
  • 2020-02-09
  • 2022-10-17
  • 2021-04-28
  • 2019-04-27
  • 2019-10-23
相关资源
最近更新 更多