Python Pytorch 张量到 numpy 数组

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/49768306/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 19:14:24  来源:igfitidea点击:

Pytorch tensor to numpy array

pythonnumpypytorch

提问by DukeLover

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

我有一个pytorch大小的张量torch.Size([4, 3, 966, 1296])

I want to convert it to numpyarray using the following code:

我想numpy使用以下代码将其转换为数组:

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

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

Can anyone please explain what this code is doing ?

谁能解释一下这段代码在做什么?

采纳答案by Maaz Bin Musa

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

您要转换的张量有 4 个维度。

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

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

:意味着第一个维度应该按原样复制和转换,第三个和第四个维度也是如此。

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

::-1意味着对于第二个轴,它反转轴

回答by Azizbro

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:

我相信你也必须使用.detach(). 我不得不在使用 CUDA 和 GPU 的 Colab 上将我的 Tensor 转换为一个 numpy 数组。我是这样做的:

# 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 bwlow is a numpy array
tensor_array.cpu().detach().numpy()

回答by Muhammad Bilal

You can use this syntax if some grads are attached with your variables.

如果您的变量附加了一些 grads,您可以使用此语法。

y=torch.Tensor.cpu(x).detach().numpy()[:,:,:,-1]

y=torch.Tensor.cpu(x).detach().numpy()[:,:,:,-1]