PyTorch性别分类CNN模型报错:输入与目标batch_size不匹配
问题解决:PyTorch性别分类输入与目标batch_size不匹配错误
错误根源
从报错日志和代码运行输出可以明确:
- 输入batch_size是24(
torch.Size([24, 3, 224, 224])),经过卷积后最终特征图尺寸为[24, 256, 112, 112] - 你在
forward函数中错误地将展平后的特征数指定为256*56*56,导致output.view(-1, 256*56*56)把原本24个样本的特征强行拆分成96个(24*(112/56)²=96),输出batch_size变成96,而标签的batch_size仍为24,两者不匹配触发错误。
修复方案
1. 修正全连接层输入特征数
在CNN类的__init__方法中,修改全连接层的in_features参数:
# 原错误代码 # self.fc=nn.Linear(in_features=256*56*56,out_features=2) # 修正后 self.fc=nn.Linear(in_features=256*112*112,out_features=2)
2. 修正forward中的展平操作
同步修改forward函数中的view操作:
# 原错误代码 # output=output.view(-1, 256*56*56) # 修正后 output=output.view(-1, 256*112*112)
更通用的写法(推荐)
为避免手动计算特征图尺寸出错,可采用自动展平的方式,同时适配后续网络结构修改:
# forward函数中替换原view行 output = output.view(output.size(0), -1) # 此时需要先运行一次网络,打印output.shape获取展平后的特征数,再替换__init__中的全连接层in_features # 比如测试输出为torch.Size([24, 3211264]),则in_features=3211264(即256*112*112)
验证建议
修改后可输入测试张量验证输出是否符合预期:
test_input = torch.randn(1, 3, 224, 224) model = CNN() output = model(test_input) print(output.shape) # 预期输出:torch.Size([1, 2])
内容的提问来源于stack exchange,提问作者DarioLong
相关产品推荐
相关产品推荐

