ValueError:only one element tensors can be converted to Python scalars
element
A Vue.js 2.0 UI Toolkit for Web
项目地址:https://gitcode.com/gh_mirrors/eleme/element
免费下载资源
·
把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
GitHub 加速计划 / eleme / element
54.06 K
14.63 K
下载
A Vue.js 2.0 UI Toolkit for Web
最近提交(Master分支:3 个月前 )
c345bb45
7 个月前
a07f3a59
* Update transition.md
* Update table.md
* Update transition.md
* Update table.md
* Update transition.md
* Update table.md
* Update table.md
* Update transition.md
* Update popover.md 7 个月前
更多推荐
已为社区贡献2条内容
所有评论(0)