RuntimeError: mat1 and mat2 shapes cannot be multiplied (1024x1 and 1024x3)

本文探讨了在使用PyTorch搭建神经网络时遇到的RuntimeError,重点在于如何修复'1024x1与1024x3矩阵无法相乘'的问题,通过提供两种解决方案——调整输入维度和全连接层前的预处理技巧,帮助读者避免此类常见错误。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

RuntimeError: mat1 and mat2 shapes cannot be multiplied (1024x1 and 1024x3)

前言:在学习pytorch 搭建神经网络的时候,测试网络发现出现RuntimeError: mat1 and mat2 shapes cannot be multiplied (1024x1 and 1024x3)的错误,记录下。

一、报错如下

Traceback (most recent call last):
  File "mobilenet_v1.py", line 145, in <module>
    out = model(input)
  File "J:\WorkSoft\envs\yolov5_test\lib\site-packages\torch\nn\modules\module.py", line 1051, in _call_impl
    return forward_call(*input, **kwargs)
  File "mobilenet_v1.py", line 138, in forward
    x = self.fc(x)
  File "J:\WorkSoft\envs\yolov5_test\lib\site-packages\torch\nn\modules\module.py", line 1051, in _call_impl
    return forward_call(*input, **kwargs)
  File "J:\WorkSoft\envs\yolov5_test\lib\site-packages\torch\nn\modules\linear.py", line 96, in forward
    return F.linear(input, self.weight, self.bias)
  File "J:\WorkSoft\envs\yolov5_test\lib\site-packages\torch\nn\functional.py", line 1847, in linear
    return torch._C._nn.linear(input, weight, bias)
RuntimeError: mat1 and mat2 shapes cannot be multiplied (1024x1 and 1024x3)

二、定位报错为全连接层

 File "mobilenet_v1.py", line 138, in forward
    x = self.fc(x)

三、原因分析

卷积层的输入为四维[batch_size,channels,H,W] ,而全连接接受维度为2的输入,通常为[batch_size, size]。

四、解决办法

在全连接层前面加入维度变换

//方法一:
x.view(-1,7* 7* 1024) 

//方法二:
x = torch.flatten(x,1) //拉成二维向量[batch_size, size]
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值