Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pytorch tensor to numpy array

I have a pytorch Tensor of size torch.Size([4, 3, 966, 1296])

I want to convert it to numpy array using the following code:

imgs = imgs.numpy()[:, ::-1, :, :]

Can anyone please explain what this code is doing ?

like image 394
DukeLover Avatar asked Apr 11 '18 06:04

DukeLover


People also ask

How do you pass a tensor to a numpy call?

Convert a Tensor to a NumPy Array With the Tensor. eval() Function in Python. We can also use the Tensor. eval() function to convert a Tensor to a NumPy array in Python.

Is PyTorch CPU faster than numpy?

In this benchmark I implemented the same algorithm in numpy/cupy, pytorch and native cpp/cuda. The benchmark is attached below. In all tests numpy was significantly faster than pytorch.

How do you flatten a tensor?

A tensor can be flattened into a one-dimensional tensor by reshaping it using the method torch. flatten(). This method supports both real and complex-valued input tensors. It takes a torch tensor as its input and returns a torch tensor flattened into one dimension.


2 Answers

I believe you also have to use .detach(). I had to convert my Tensor to a numpy array on Colab which uses CUDA and GPU. I did it like the following:

# this is just my embedding matrix which is a Torch tensor object embedding = learn.model.u_weight  embedding_list = list(range(0, 64382))  input = torch.cuda.LongTensor(embedding_list) tensor_array = embedding(input) # the output of the line below is a numpy array tensor_array.cpu().detach().numpy() 
like image 122
azizbro Avatar answered Sep 23 '22 23:09

azizbro


This worked for me:

np_arr = torch_tensor.cpu().detach().numpy() 
like image 42
Scott Avatar answered Sep 23 '22 23:09

Scott