有一个PyTorch张量列表,我想将其转换为数组,但它引发了错误:
"列表"对象没有属性"cpu">
如何将其转换为数组?
import torch
result = []
for i in range(3):
x = torch.randn((3, 4, 5))
result.append(x)
a = result.cpu().detach().numpy()
您可以将它们堆叠并转换为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()