如何解决PyTorch中RuntimeError:期望输入64通道却得到16通道问题
问题分析与解决
核心错误点
3D卷积层误用:
模型前两层都是Conv2d,输出张量形状为[batch_size, channels, height, width](比如打印的[64,64,8,8]),但第三层误用了Conv3d——Conv3d要求输入是5维张量[batch_size, channels, depth, height, width],维度不匹配直接触发RuntimeError。全连接层参数非法:
nn.Linear(1024, 0)和nn.Linear(0, 1024)中特征数设为0完全无效,PyTorch不允许线性层的输入/输出特征数为0,会导致后续计算崩溃。
修正后的模型代码
import torch import torch.nn as nn import torch.nn.functional as F class Net(nn.Module): def __init__(self): super(Net, self).__init__() self.conv1 = nn.Conv2d( in_channels=3, out_channels=32, kernel_size=5, stride=1, padding=2 ) self.conv2 = nn.Conv2d( in_channels=32, out_channels=64, kernel_size=5, stride=1, padding=2 ) # 将Conv3d改为Conv2d,与前序2D卷积逻辑统一 self.conv3 = nn.Conv2d( in_channels=64, out_channels=64, kernel_size=5, stride=1, padding=2 ) self.pool = nn.MaxPool2d(2,2) # 计算卷积+池化后的特征数:CIFAR-10输入32x32,三次池化后为4x4,64个通道,即64*4*4=1024 self.fc1 = nn.Linear(64 * 4 * 4, 512) # 替换无效的0值,使用合理中间特征数 self.fc2 = nn.Linear(512, 128) self.fc3 = nn.Linear(128, 10) def forward(self, x): x = self.pool(F.relu(self.conv1(x))) x = self.pool(F.relu(self.conv2(x))) x = self.pool(F.relu(self.conv3(x))) x = torch.flatten(x, 1) # 展平除batch外的所有维度 x = F.relu(self.fc1(x)) x = F.relu(self.fc2(x)) x = self.fc3(x) return x
额外说明
- 若确实需要使用3D卷积,需先给2D图像扩展深度维度(比如
x = x.unsqueeze(2)),但CIFAR-10是2D图像场景,完全不需要用3D卷积,2D卷积足够完成任务。 - 全连接层的输入特征数必须与卷积层输出的展平后维度一致,可通过在
torch.flatten前打印x.shape确认具体数值。
内容的提问来源于stack exchange,提问作者Takadox et compagnie
相关产品推荐
相关产品推荐

