我有以下代码:
import torch
list_of_tensors = [ torch.randn(3), torch.randn(3), torch.randn(3)]
tensor_of_tensors = torch.tensor(list_of_tensors)
我遇到了以下错误:
ValueError:只有一个元素的张量可以转换为Python标量。
如何将PyTorch中的张量列表转换为张量张量?
我有以下代码:
import torch
list_of_tensors = [ torch.randn(3), torch.randn(3), torch.randn(3)]
tensor_of_tensors = torch.tensor(list_of_tensors)
这里有一个解决方案:
tensor_of_tensors = torch.stack((list_of_tensors))
print(tensor_of_tensors) #shape (3,3)
你也可以将torch张量转换为NumPy数组,然后再将它们转换回张量
list_of_tensors = [torch.randn(3).numpy(),torch.randn(3).numpy(),torch.randn(3).numpy()]
tensor_of_tensors = torch.tensor(list_of_tensors)
torch.stack()
,之前也在Stackoverflow上回答过这个问题,尽管我无法更改我的重复投票。例如可以看这里here。如果需要更多细节,请随时回复。 - dennlinger