如何基于PyTorch构建适配28×28 RGB图像的CNN?
适配RGB图像的CNN修改方案
需要修改代码来适配RGB图像,具体修改点如下:
1. 调整第一个卷积层的输入通道数
原代码中conv1的in_channels=1对应灰度图的单通道,而RGB图像有3个颜色通道,必须将其改为in_channels=3:
self.conv1 = nn.Conv2d(in_channels=3, out_channels=32, kernel_size=3, stride=1, padding=1)
2. 确认后续层的维度兼容性
由于输入图像尺寸仍为28×28,通道数变化不会影响后续卷积、池化操作的输出尺寸:
- 经过
conv1和conv2后,特征图尺寸保持28×28,通道数变为64 - 经过
pool1后尺寸压缩为14×14,通道数维持64 - 经过
conv3后通道数变为128,尺寸仍为14×14 - 经过
pool2后尺寸压缩为7×7,通道数128 - 全连接层
fc1的输入特征数128*7*7完全匹配,无需修改
3. 可选优化:调整输出层激活函数(推荐)
原代码中fc2使用ReLU激活,而多分类任务更适合搭配Softmax(或直接使用CrossEntropyLoss,该损失函数已内置Softmax逻辑)。如果采用Softmax,可修改前向传播的最后一步:
x = F.softmax(self.fc2(x), dim=1)
若使用CrossEntropyLoss训练,直接返回self.fc2(x)即可,无需额外激活。
修改后的完整代码
import torch.nn as nn import torch.nn.functional as F class Net(nn.Module): def __init__(self): super(Net, self).__init__() # 3x28x28 to 32x28x28 self.conv1 = nn.Conv2d(in_channels=3, out_channels=32, kernel_size=3, stride=1, padding=1) # 32x28x28 to 64x28x28 self.conv2 = nn.Conv2d(in_channels=32, out_channels=64, kernel_size=3, stride=1, padding=1) # 64x28x28 to 64x14x14 self.pool1 = nn.MaxPool2d(kernel_size=2, stride=2) # 64x14x14 to 128x14x14 self.conv3 = nn.Conv2d(in_channels=64, out_channels=128, kernel_size=3, stride=1, padding=1) # 128x14x14 to 128x7x7 self.pool2 = nn.MaxPool2d(kernel_size=2, stride=2) # 128x7x7 to 128 self.fc1 = nn.Linear(in_features=128*7*7, out_features=128) # 128 to 27 (no. of classes) self.fc2 = nn.Linear(in_features=128, out_features=27) def forward(self, x): x = F.relu(self.conv1(x)) x = F.relu(self.conv2(x)) x = self.pool1(x) x = F.relu(self.conv3(x)) x = self.pool2(x) x = x.view(-1, 128*7*7) x = F.relu(self.fc1(x)) # 若使用CrossEntropyLoss,替换为return self.fc2(x) x = F.softmax(self.fc2(x), dim=1) return x
内容的提问来源于stack exchange,提问作者chai
相关产品推荐
相关产品推荐

