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 ?
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.
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.
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.
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()
This worked for me:
np_arr = torch_tensor.cpu().detach().numpy()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With