译(五十)-Pytorch转换Tensor至numpy数组

stackoverflow热门问题目录

如有翻译问题欢迎评论指出,谢谢。

Pytorch tensor 转为 numpy array

  • DukeLover asked:

    • 对于一个大小为 torch.Size([4, 3, 966, 1296])pytorch Tensor
    • 我想用下面的代码把它转成 numpy 数组:
    • imgs = imgs.numpy()[:, ::-1, :, :]
    • 可以解释一下这句代码吗?
  • Answers:

    • azizbro - vote: 86

    • 我觉得你还得加上 detach()。我在利用CUDA和GPU进行计算的Colab上用下面的代码来实现张量和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 below is a numpy array
      tensor_array.cpu().detach().numpy()
    • Scott - vote: 29

    • 试试这个:

    • np_arr = torch_tensor.cpu().detach().numpy()
    • Maaz Bin Musa - vote: 24

    • 因为这个张量里有四个维度。

    • [:, ::-1, :, :] 
    • : 表示第一、第三、第四维度在转换时保持不变。

    • ::-1 表示第二维度需要翻转。


Pytorch tensor to numpy array

  • DukeLover asked:

    • I have a pytorch Tensor of size torch.Size([4, 3, 966, 1296])
      对于一个大小为 torch.Size([4, 3, 966, 1296])pytorch Tensor
    • I want to convert it to numpy array using the following code:
      我想用下面的代码把它转成 numpy 数组:
    • imgs = imgs.numpy()[:, ::-1, :, :]
    • Can anyone please explain what this code is doing ?
      可以解释一下这句代码吗?
  • Answers:

    • azizbro - vote: 86

    • 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上用下面的代码来实现张量和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 below is a numpy array
      tensor_array.cpu().detach().numpy()
    • Scott - vote: 29

    • This worked for me:
      试试这个:

    • np_arr = torch_tensor.cpu().detach().numpy()
    • Maaz Bin Musa - vote: 24

    • 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
      ::-1 表示第二维度需要翻转。

版权声明:
作者:MWHLS
链接:https://mwhls.top/3680.html
来源:无镣之涯
文章版权归作者所有,未经允许请勿转载。

THE END
分享
二维码
打赏
< <上一篇
下一篇>>