RuntimeError: shape ‘[4]‘ is invalid for input of size 6

tech2022-12-14  132

1.报错

运行pytorch代码,得到报错:RuntimeError: shape '[4]' is invalid for input of size 6,笔者的报错信息是出现在view()方法附近。

2.原因

以简单的一段代码为例,看看报错原因。

import torch as t a = t.randint(1,5,(3,1,2,1)) # 3*2 = 6,这就是后面为什么说input of size 6的原因 print(a) a = a.view(4) # view:想将a变成一维的向量(即行向量) print(a) --------------------------------------------------------------------------- RuntimeError Traceback (most recent call last) <ipython-input-5-6e1293746853> in <module> 4 a = t.randint(1,5,(3,1,2)) # 5 print(a) ----> 6 a = a.view(4) 7 print(a) RuntimeError: shape '[4]' is invalid for input of size 6

即tensor变化的数目不对,导致上述错误,在相应代码处进行修改就OK了。

上述代码也可以在我的github之pytorch专题中的文件tensor维度问题.ipynb查看。

最新回复(0)