标签:tensor Python t2 torch list t1 scalars element ValueError
把list转换成pytorch的tensor对象时,出现以下错误
ValueError:only one element tensors can be converted to Python scalars
具体如下,torch.as_tensor()
和torch.tensor()
都转不了。
>>> t1 = torch.tensor([0., 1.])
>>> t2 = torch.tensor([2., 3.])
>>> tensor_list = [t1, t2]
>>> torch.as_tensor(tensor_list)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: only one element tensors can be converted to Python scalars
>>> torch.tensor(tensor_list)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: only one element tensors can be converted to Python scalars
准确地说,torch.tensor()
不能把包含tensor的list转成tensor,纯list就可以转tensor,不信看下面代码,我也不知道是为什么。
>>> t1 = [0., 1.]
>>> t2 = [2., 3.]
>>> tensor_list = [t1, t2]
>>> torch.tensor(tensor_list)
tensor([[0., 1.],
[2., 3.]])
解决办法
torch.stack()
>>> t1 = torch.tensor([0., 1.])
>>> t2 = torch.tensor([2., 3.])
>>> tensor_list = [t1, t2]
>>> torch.stack(tensor_list)
tensor([[0., 1.],
[2., 3.]])
同类错误
如果list里面的tensor是int类型的,用torch.as_tensor()
和torch.tensor()
转tensor会报以下错误,同样用torch.stack()
可以解决。
TypeError: only integer tensors of a single element can be converted to an index
标签:tensor,Python,t2,torch,list,t1,scalars,element,ValueError 来源: https://blog.csdn.net/lhp171302512/article/details/121477448
本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享; 2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关; 3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关; 4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除; 5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。