【问题标题】:how to detach list of pytorch tensors to array如何将pytorch张量列表分离到数组
【发布时间】:2021-02-22 13:17:33
【问题描述】:

有一个 PyTorch 的张量列表,我想将其转换为数组,但出现错误:

'list' 对象没有属性'cpu'

如何将其转换为数组?

import torch
result = []
for i in range(3):
    x = torch.randn((3, 4, 5))
    result.append(x)
a = result.cpu().detach().numpy()

【问题讨论】:

    标签: python list numpy pytorch tensor


    【解决方案1】:

    您可以将它们堆叠并转换为 NumPy 数组:

    import torch
    result = [torch.randn((3, 4, 5)) for i in range(3)]
    a = torch.stack(result).cpu().detach().numpy()
    

    在这种情况下,a 将具有以下形状:[3, 3, 4, 5]

    如果您想将它们连接到 [3*3, 4, 5] 数组中,那么:

    a = torch.cat(result).cpu().detach().numpy()
    

    【讨论】:

      猜你喜欢
      • 2019-07-22
      • 2021-08-15
      • 2021-06-18
      • 2019-07-29
      • 2018-09-20
      • 2020-08-05
      • 2020-03-16
      • 2021-05-24
      相关资源
      最近更新 更多