Pytorch tensor to numpy array Pytorch tensor to numpy array python python

Pytorch tensor to numpy array


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 objectembedding = learn.model.u_weightembedding_list = list(range(0, 64382))input = torch.cuda.LongTensor(embedding_list)tensor_array = embedding(input)# the output of the line below is a numpy arraytensor_array.cpu().detach().numpy()


There are 4 dimensions of the tensor you want to convert.

[:, ::-1, :, :] 

: means that the first dimension should be copied as it is and converted, same goes for the third and fourth dimension.

::-1 means that for the second axes it reverses the the axes


This worked for me:

np_arr = torch_tensor.cpu().detach().numpy()