1

有一个 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()
4

1 回答 1

2

您可以将它们堆叠并转换为 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()
于 2020-11-10T15:21:03.667 回答