You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用PyTorch预训练SqueezeNet迁移学习时出现矩阵形状不匹配错误

解决PyTorch迁移学习中SqueezeNet1_0的形状不匹配错误

错误mat1 and mat2 shapes cannot be multiplied (212992x13 and 1280x3)的核心原因是SqueezeNet1_0的特征输出结构与EfficientNet_B0完全不同,你直接复用了EfficientNet的分类器结构,导致输入特征维度不匹配:

  • EfficientNet_B0的features模块最终输出的是1280维的全局平均池化向量,因此可以直接接Linear(in_features=1280)
  • SqueezeNet1_0的features模块输出的是512通道的特征图(而非一维向量),且它的原生分类器是用卷积层+自适应池化实现分类,不是全连接层

方案1:沿用SqueezeNet原生分类器结构(推荐)

保持SqueezeNet用卷积做分类的设计,仅修改最后一层卷积的输出通道数为你的类别数:

torch.manual_seed(42)
output_shape = len(class_names)
# 替换为适配SqueezeNet的分类器
model.classifier = torch.nn.Sequential(
    torch.nn.Dropout(p=0.5),  # SqueezeNet预训练默认dropout概率为0.5,可按需调整
    torch.nn.Conv2d(512, output_shape, kernel_size=(1, 1)),
    torch.nn.ReLU(inplace=True),
    torch.nn.AdaptiveAvgPool2d((1, 1))
).to(device)

SqueezeNet的原生forward方法会自动将自适应池化后的结果展平为一维向量,无需额外修改训练逻辑。

方案2:改用全连接层分类

如果偏好使用全连接层,需要先对特征图做全局平均池化,将其转为512维向量后再接全连接层:

torch.manual_seed(42)
output_shape = len(class_names)
model.classifier = torch.nn.Sequential(
    torch.nn.AdaptiveAvgPool2d((1, 1)),  # 将512通道的特征图转为(512,1,1)
    torch.nn.Flatten(),  # 展平为512维向量
    torch.nn.Dropout(p=0.2),
    torch.nn.Linear(in_features=512,  # 输入维度对应SqueezeNet特征通道数
                    out_features=output_shape,
                    bias=True)
).to(device)

内容的提问来源于stack exchange,提问作者Chiraag

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.26 18:35:25