How to transform Variable into numpy?

When I used pytorch, I met a problem that I can not transform Variable into numpy. When I try to use torch.Tensor or transform it into torch.FloatTensor, but it’s fail. So how can I to solve this problem?

6 Likes

Hi, having the same issue here
https://github.com/pytorch/examples/pull/47/files#diff-1357f5fd365db925427f5f0692df5b52R251

2 Likes

Variable's can’t be transformed to numpy, because they’re wrappers around tensors that save the operation history, and numpy doesn’t have such objects. You can retrieve a tensor held by the Variable, using the .data attribute. Then, this should work: var.data.numpy().

49 Likes

Thanks a lot.:grinning:

Hi, when I want to convert the data in a Variable x with type torch.cuda.FloatTensor into a numpy array. Use x.data.numpy() and this error pops up RuntimeError: numpy conversion for FloatTensor is not supported. Is there anything that I am missing? Thanks.

2 Likes

Ah, after more searching I found out that I gotta do cpu() first. :sweat_smile:

10 Likes

Yes, it’s working: (Variable(x).data).cpu().numpy()

10 Likes

You can refer this link, in case converting torch tensor to numpy still poses a problem!

1 Like

Is there a function which handles both CUDA and CPU at once?

what will type if cuda tenso is fp16 than after converting it will numpy(fp32) or numpy(fp16)?