TypeError: only integer tensors of a single element can be converted to an indexValueError: only one

1.ValueError: only one element tensors can be converted to Python scalars

2.TypeError: only integer tensors of a single element can be converted to an index

这个两个报错很有意思,是一对亲兄弟,都发生在列表转化为tensor的过程中。

让我们好好分析一下,看完下面代码,你就会明白only one element tensors can be converted to Python scalars或者另外一个报错是什么意思了。

a=[]
b=torch.tensor([1])
a.append(b)
a.append(b)
print(a)


显然,a是一个列表,我们想将其转化为一个tensor。注意到,列表的元素就是一个个的单元素tensor,即错误中的one element tensors

torch.tensor(a)

成功!


分割线


上面似乎平平无奇,再看下面这一段代码,吓汝一跳。

a=[]
b=torch.tensor([1,2],dtype=torch.float32)
a.append(b)
a.append(b)
print(a)


同样,我们想要把这个列表转化为tensor。

torch.tensor(a)


是不是感觉很无语,上面都可以转化成功,这里却不可以。这下你明白了only one element tensorsonly的含义了吧。
不会吧,还没吓到你?那就再吓汝一跳!看招:

a=[]
b=torch.tensor([1,2],dtype=torch.int32)
a.append(b)
a.append(b)
print(a)


显然,上述是一个列表,我们还是想要将其转化为tensor。

torch.tensor(a)

又报错了,这下体验到only的作用了吧!

解决

这个问题的命根子就在与列表中的元素是一个一个的tensor,所以我们从这里入手。

a=[]
b=torch.tensor([1,2],dtype=torch.int32)
a.append(b)
a.append(b)
print(a)
a=[aa.tolist() for aa in a]#列表中元素由tensor变成列表。
print(torch.tensor(a))


可以看到把列表中元素由tensor变成列表,这是最致命的一击,把命根子斩断了!问题就解决了。

附录

上面是较为特殊的相互转换,一般地相互转换见list,numpy,tensor之间相互转换的方法


完结撒花


来源:音程

物联沃分享整理
物联沃-IOTWORD物联网 » TypeError: only integer tensors of a single element can be converted to an indexValueError: only one

发表评论