0
点赞
收藏
分享

微信扫一扫

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

Aliven888 2022-03-11 阅读 66

文章首发及后续更新:https://mwhls.top/3680.html
新的更新内容请到mwhls.top查看。
无图/无目录/格式错误/更多相关请到上方的文章首发页面查看。

目录

1. Pytorch tensor 转为 numpy array

2. Pytorch tensor to numpy array

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

举报

相关推荐

0 条评论