如何将 Pytorch autograd.Variable 转换为 Numpy?

How to convert Pytorch autograd.Variable to Numpy?

标题说明了一切。我想将 PyTorch autograd.Variable 转换为等效的 numpy 数组。在他们的 official documentation 中,他们提倡使用 a.numpy() 来获得等效的 numpy 数组(对于 PyTorch tensor)。但这给了我以下错误:

Traceback (most recent call last): File "stdin", line 1, in module File "/home/bishwajit/anaconda3/lib/python3.6/site-packages/torch/autograd/variable.py", line 63, in getattr raise AttributeError(name) AttributeError: numpy

有什么办法可以避免这种情况吗?

我找到方法了。实际上,我可以先使用 a.dataautograd.Variable 中提取 Tensor 数据。那么剩下的部分就很简单了。我只是使用 a.data.numpy() 来获得等效的 numpy 数组。步骤如下:

a = a.data  # a is now torch.Tensor
a = a.numpy()  # a is now numpy array

两种可能的情况

  • 使用 GPU: 如果您尝试将 cuda 浮点张量直接转换为 numpy,如下所示,它会抛出错误。

    x.data.numpy()

    RuntimeError: numpy conversion for FloatTensor is not supported

    因此,您不能将 cuda 浮点张量直接转换为 numpy,相反,您必须先将其转换为 cpu 浮点张量,然后尝试转换为 numpy,如图所示下面.

    x.data.cpu().numpy()

  • 使用 CPU: 转换 CPU 张量非常简单。

    x.data.numpy()