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

PyTorch性别分类器训练时矩阵形状不匹配报错求助

解决PyTorch GenderClassifier的形状不匹配报错

问题原因

报错RuntimeError: mat1 and mat2 shapes cannot be multiplied (64x7696 and 492544x2)的核心是全连接层的输入维度与卷积后展平的特征维度不匹配,主要由两个可能原因导致:

  • 输入图像的通道维度顺序错误(PyTorch要求通道在前,即[batch_size, channels, height, width],但你的输入可能是通道在后的[batch_size, height, width, channels])
  • 手动计算的全连接层输入维度与实际卷积后的特征维度不符

解决步骤

1. 修正输入维度顺序

先检查训练代码中输入X的形状,如果输出是类似(64, 110, 80, 3)(通道在最后),需要转置为PyTorch要求的格式:

for epoch in range(30):
    for batch in dataset: 
        X,y = batch 
        # 将通道维度转置到第二位,匹配PyTorch输入格式
        X = X.permute(0, 3, 1, 2)
        X, y = X.to('cuda'), y 
        yhat = clf(X) 
        loss = loss_fn(yhat, y) 

        opt.zero_grad()
        loss.backward() 
        opt.step() 

    print(f"Epoch:{epoch} loss is {loss.item()}")

2. 修正全连接层输入维度

如果输入维度已经正确,重新计算卷积后的特征总维度:
输入为(3,110,80),经过三次3x3无padding卷积后,尺寸变化为:

  • 第一次卷积:110-2=108,80-2=78 → 输出(32,108,78)
  • 第二次卷积:108-2=106,78-2=76 → 输出(64,106,76)
  • 第三次卷积:106-2=104,76-2=74 → 输出(64,104,74)

此时Flatten后的总特征数为64*104*74=492544,对应全连接层的in_features需保持一致,修正后的模型代码:

class GenderClassifier(nn.Module):
    def __init__(self):
        super().__init__()
        self.model = nn.Sequential(
            nn.Conv2d(3,32,(3,3)),
            nn.ReLU(),
            nn.Conv2d(32,64,(3,3)),
            nn.ReLU(),
            nn.Conv2d(64,64,(3,3)),
            nn.ReLU(),
            nn.Flatten(),
            nn.Linear(64*104*74,2),
            nn.Sigmoid()
        )
        
    def forward(self,x):
        return self.model(x)

3. 更稳妥的方案:使用自适应池化层

为避免手动计算维度的误差,推荐在卷积层后加入自适应池化层,固定特征图尺寸,这样全连接层的输入维度无需手动计算:

class GenderClassifier(nn.Module):
    def __init__(self):
        super().__init__()
        self.model = nn.Sequential(
            nn.Conv2d(3,32,(3,3)),
            nn.ReLU(),
            nn.Conv2d(32,64,(3,3)),
            nn.ReLU(),
            nn.Conv2d(64,64,(3,3)),
            nn.ReLU(),
            nn.AdaptiveAvgPool2d((8,8)), # 固定输出为8x8特征图
            nn.Flatten(),
            nn.Linear(64*8*8,2), # 64通道*8*8尺寸
            nn.Sigmoid()
        )
        
    def forward(self,x):
        return self.model(x)

验证方法

用随机输入测试模型的输出形状,确认是否匹配:

import torch
clf = GenderClassifier()
dummy_input = torch.randn(1,3,110,80) # 模拟单张输入
output = clf(dummy_input)
print(output.shape) # 应输出torch.Size([1,2])

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.12 17:05:38