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

PyTorch训练CNN时出现矩阵形状不兼容错误求助

解决CNN矩阵形状不匹配问题

错误核心原因

报错RuntimeError: mat1 and mat2 shapes cannot be multiplied (64x8192 and 12800x10)本质是全连接层输入维度与卷积层输出展平后的维度不匹配:

  • 64是训练用的batch size,8192是32x32图像经新CNN卷积、池化后,展平得到的特征向量长度
  • 你复用了8x8图像任务中设置的全连接层输入维度12800,和当前的8192不匹配,导致矩阵乘法无法执行

分步解决方法

1. 计算卷积层输出的特征维度

先明确新CNN的卷积、池化参数,用代码自动推导展平后的特征数(避免手动计算出错):

import torch
import torch.nn as nn

# 实例化你的新CNN模型
class NewCNN(nn.Module):
    def __init__(self):
        super().__init__()
        # 这里替换成你实际的卷积、池化层定义
        self.conv_blocks = nn.Sequential(
            nn.Conv2d(1, 64, kernel_size=3, padding=1),
            nn.ReLU(),
            nn.MaxPool2d(2, 2),
            # 更多卷积/池化层...
        )

model = NewCNN()
# 用单张32x32的测试输入推导特征维度
test_input = torch.randn(1, 1, 32, 32)  # 单通道灰度图示例
with torch.no_grad():
    conv_output = model.conv_blocks(test_input)
flattened_dim = conv_output.view(1, -1).size(1)
print(f"展平后的特征维度: {flattened_dim}")

2. 修改全连接层的输入维度

把ClassifierNeuralNet中全连接层的第一个输入参数,替换成上面计算出的flattened_dim(比如计算结果是8192,就把12800换成8192):

class ClassifierNeuralNet(nn.Module):
    def __init__(self, num_classes):
        super(ClassifierNeuralNet, self).__init__()
        # 替换为实际计算出的展平维度
        self.fc1 = nn.Linear(8192, 512)
        self.relu = nn.ReLU()
        self.fc2 = nn.Linear(512, num_classes)
    
    def forward(self, x):
        x = x.view(x.size(0), -1)
        x = self.relu(self.fc1(x))
        x = self.fc2(x)
        return x

3. 验证修改效果

重新运行训练代码,若仍有形状错误,重复步骤1检查卷积层的padding、stride、池化参数是否正确,确保卷积输出的尺寸计算无误。

优化建议:自动适配维度

避免硬编码维度,在模型初始化时自动计算展平后的特征数,后续修改图像尺寸或卷积架构时无需手动调整:

class AutoAdaptCNN(nn.Module):
    def __init__(self, num_classes=10):
        super().__init__()
        self.conv_blocks = nn.Sequential(
            nn.Conv2d(1, 64, kernel_size=3, padding=1),
            nn.ReLU(),
            nn.MaxPool2d(2, 2),
            # 你的其他卷积/池化层
        )
        
        # 自动计算展平维度
        with torch.no_grad():
            dummy_input = torch.randn(1, 1, 32, 32)
            conv_out = self.conv_blocks(dummy_input)
            self.flattened_dim = conv_out.view(1, -1).size(1)
        
        # 全连接层自动适配
        self.fc_blocks = nn.Sequential(
            nn.Linear(self.flattened_dim, 512),
            nn.ReLU(),
            nn.Linear(512, num_classes)
        )
    
    def forward(self, x):
        x = self.conv_blocks(x)
        x = x.view(x.size(0), -1)
        x = self.fc_blocks(x)
        return x

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.22 02:17:17