[英]how to detach list of pytorch tensors to array
There is a list of PyTorch's Tensors and I want to convert it to array but it raised with error:有一个 PyTorch 的张量列表,我想将它转换为数组,但它引发了错误:
'list' object has no attribute 'cpu'
'list' 对象没有属性 'cpu'
How can I convert it to array?如何将其转换为数组?
import torch
result = []
for i in range(3):
x = torch.randn((3, 4, 5))
result.append(x)
a = result.cpu().detach().numpy()
You can stack them and convert to NumPy array:您可以堆叠它们并转换为 NumPy 数组:
import torch
result = [torch.randn((3, 4, 5)) for i in range(3)]
a = torch.stack(result).cpu().detach().numpy()
In this case, a
will have the following shape: [3, 3, 4, 5]
.在这种情况下,
a
将具有以下形状: [3, 3, 4, 5]
。
If you want to concatenate them in a [3*3, 4, 5]
array, then:如果要将它们连接到
[3*3, 4, 5]
数组中,则:
a = torch.cat(result).cpu().detach().numpy()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.