将张量列表转换为 PyTorch 的张量张量

9

我有以下代码:

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中的张量列表转换为张量张量?

这个回答解决了您的问题吗?将张量列表转换为PyTorch张量 - dennlinger
谢谢您的评论,我看到了这篇文章,但它并没有回答我的问题。我不想要一个大张量,我想要一个张量的张量。 - Kenny Smith
2
在您看来,“张量的张量”和张量中的附加维度有什么区别? - dennlinger
1
使用 tensor.cat,我将获得一个大小为 9 的张量。 我想要获得一个大小为 (3,3) 的张量。 - Kenny Smith
4
抱歉,我不小心链接了错误的答案,对此我深表歉意。你要找的函数是torch.stack(),之前也在Stackoverflow上回答过这个问题,尽管我无法更改我的重复投票。例如可以看这里here。如果需要更多细节,请随时回复。 - dennlinger
2个回答

12

这里有一个解决方案:

tensor_of_tensors = torch.stack((list_of_tensors))
print(tensor_of_tensors) #shape (3,3)

0

你也可以将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)

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接