How to convert Pytorch autograd.Variable to Numpy?
Two possible case
Using GPU: If you try to convert a cuda float-tensor directly to numpy like shown below,it will throw an error.
x.data.numpy()
RuntimeError: numpy conversion for FloatTensor is not supported
So, you cant covert a cuda float-tensor directly to numpy, instead you have to convert it into a cpu float-tensor first, and try converting into numpy, like shown below.
x.data.cpu().numpy()
Using CPU: Converting a CPU tensor is straight forward.
x.data.numpy()
I have found the way. Actually, I can first extract the Tensor
data from the autograd.Variable
by using a.data
. Then the rest part is really simple. I just use a.data.numpy()
to get the equivalent numpy
array. Here's the steps:
a = a.data # a is now torch.Tensora = a.numpy() # a is now numpy array