【问题标题】:Convert PyTorch tensor to python list将 PyTorch 张量转换为 python 列表
【发布时间】:2019-05-23 00:33:30
【问题描述】:

如何将 PyTorch Tensor 转换为 python 列表?

我当前的用例是将大小为 [1, 2048, 1, 1] 的张量转换为 2048 个元素的列表。

我的张量有浮点值。是否有一个解决方案也可以考虑 int 和可能的其他数据类型?

【问题讨论】:

    标签: python pytorch


    【解决方案1】:

    使用Tensor.tolist() 例如:

    >>> import torch
    >>> a = torch.randn(2, 2)
    >>> a.tolist()
    [[0.012766935862600803, 0.5415473580360413],
     [-0.08909505605697632, 0.7729271650314331]]
    >>> a[0,0].tolist()
    0.012766935862600803
    

    要删除大小为1 的所有尺寸,请使用a.squeeze().tolist()

    或者,如果除了一个维度之外的所有维度都是1(或者您希望获得张量的每个元素的列表),您可以使用a.flatten().tolist()

    【讨论】:

      【解决方案2】:

      要列出的张量:

      a_list  = embeddings.tolist()
      

      张量列表:

      a_tensor = torch.Tensor(a_list).cuda()
      

      【讨论】:

        【解决方案3】:

        #@pyorch 张量到列表或字符串

        in[]
        #bbox predictions
        boxes = predictions[:, :4]
        print(boxes)
        
        out[]
        
        tensor(54.97658) tensor(393.99637) tensor(225.55316) tensor(879.53503)
        tensor(670.91669) tensor(400.35202) tensor(810.) tensor(878.34045)
        tensor(219.87546) tensor(408.02075) tensor(346.14133) tensor(860.66687)
        tensor(13.24882) tensor(217.30855) tensor(800.23413) tensor(737.75751)
        tensor(0.12453) tensor(552.29401) tensor(76.41209) tensor(885.35455)
        tensor(656.11823) tensor(625.61261) tensor(689.63586) tensor(713.37250)
        

        之后

        in[]
        
        boxes = boxes.tolist()
        print(boxes)
            
        out []
            
        54.97657775878906 393.9963684082031 225.55316162109375 879.5350341796875
        670.9166870117188 400.3520202636719 810.0 878.3404541015625
        219.87545776367188 408.020751953125 346.1413269042969 860.6668701171875
        13.24881649017334 217.3085479736328 800.234130859375 737.7575073242188
        0.12453281879425049 552.2940063476562 76.4120864868164 885.3545532226562
        656.1182250976562 625.6126098632812 689.6358642578125 713.3724975585938
        

        【讨论】:

          猜你喜欢
          • 2022-01-10
          • 2019-07-29
          • 2019-08-07
          • 2022-10-17
          • 2020-08-05
          • 2022-01-01
          • 2020-04-07
          • 2020-06-13
          相关资源
          最近更新 更多