RuntimeError mat1 and mat2 shapes cannot be multiplied

简介: RuntimeError mat1 and mat2 shapes cannot be multiplied

详细显示如下

x = self.fc(x)

File “D:\Python36\lib\site-packages\torch\nn\modules\module.py”, line 1102, in _call_impl

return forward_call(*input, **kwargs)

File “D:\Python36\lib\site-packages\torch\nn\modules\linear.py”, line 103, in forward

return F.linear(input, self.weight, self.bias)

File “D:\Python36\lib\site-packages\torch\nn\functional.py”, line 1848, in linear

return torch._C._nn.linear(input, weight, bias)

RuntimeError: mat1 and mat2 shapes cannot be multiplied (8x704 and 2304x4)

根据提示,全连接层两个需要相乘的矩阵维度不匹配,代码中batchSize为8,最后的类别数量为4。

原因,样本总数不是批次的倍数,有余数,因此,最后一个批次的样本会产生该问题。

解决方案1,dataloader中需要设置参数drop_last=True。即丢弃最后一个不足batchSize的样本。

trainLoader = DataLoader(dataset=trainSet, batch_size=batchSize, shuffle=True, drop_last=True)

解决方案2,reshape时使用样本的数量

......
for seq, y_train in trainLoader:
  sampleSize = seq.shape[0]
  optimizer.zero_grad()
    y_pred = model(seq.reshape(sampleSize, 1, -1)) # Dataloader中drop_last=False
    # y_pred = model(seq.reshape(batchSize, 1, -1))
......
相关文章
|
7月前
|
存储 编译器 计算机视觉
cv::Mat
cv::Mat
51 3
|
计算机视觉
|
计算机视觉 Python
cv2 resize 与reshape的区别
cv2 resize 与reshape的区别
|
计算机视觉
图像拼接遇到module ‘cv2.cv2‘ has no attribute ‘xfeatures2d‘
图像拼接遇到module ‘cv2.cv2‘ has no attribute ‘xfeatures2d‘
135 0
|
SQL Java Android开发
Mat使用详解
Mat使用详解
|
计算机视觉
【opencv】cv2.error: OpenCV(4.5.5) :-1: error: (-5:Bad argument) in function ‘imshow‘
【opencv】cv2.error: OpenCV(4.5.5) :-1: error: (-5:Bad argument) in function ‘imshow‘
817 0
【opencv】cv2.error: OpenCV(4.5.5) :-1: error: (-5:Bad argument) in function ‘imshow‘
|
计算机视觉
'cv2' has no attribute '_registerMatType 问题解决
'cv2' has no attribute '_registerMatType 问题解决
4337 0
成功解决ValueError: Dimension 1 in both shapes must be equal, but are 1034 and 1024. Shapes are [100,103
成功解决ValueError: Dimension 1 in both shapes must be equal, but are 1034 and 1024. Shapes are [100,103
成功解决AttributeError: module 'cv2.cv2' has no attribute 'CV_CAP_PROP_FPS'和 'CV_CAP_PROP_FRAME_WIDTH'
成功解决AttributeError: module 'cv2.cv2' has no attribute 'CV_CAP_PROP_FPS'和 'CV_CAP_PROP_FRAME_WIDTH'