如何解决MNIST 1D CNN训练中Conv1d输入维度不匹配的RuntimeError
使用Conv1D训练MNIST时的输入维度不匹配问题修复
我因研究需求必须使用nn.Conv1d构建1D CNN训练MNIST,但运行时触发了输入维度错误。我明确需要将输入从[96,1,28,28]转换为[96,1,784]的形状以适配Conv1D的要求,但不清楚应该在代码的哪个阶段(数据加载/模型forward)实现,之前尝试过ChatGPT给出的方案但无效,也没找到合适的解决方法。
现有代码
模型定义
import torch.nn as nn class net_mnist(nn.Module): def __init__(self, input_size, output_size): super(net_mnist, self).__init__() self.conv1 = nn.Conv1d(1, 1, kernel_size=1, stride=1, padding=1) self.pool = nn.MaxPool1d(kernel_size=1, stride=2) self.fc1 = nn.Linear(input_size, 4096, bias=True) self.fc2 = nn.Linear(4096, 4096, bias=True) self.fc3 = nn.Linear(4096, 4096, bias=True) self.fc4 = nn.Linear(4096, 4096, bias=True) self.fc5 = nn.Linear(4096, output_size, bias=True) self.relu = nn.ReLU() def forward(self, x): x = self.conv1(x) x = self.relu(x) x = self.pool(x) x = self.conv2(x) # 注意:conv2未在__init__中定义,会触发AttributeError x = self.relu(x) x = self.pool(x) x = x.view(x.size(0), -1) x = self.fc1(x) x = self.relu(x) x = self.fc2(x) return x return x.squeeze() # 这段代码永远不会执行
数据集加载代码
from torchvision.transforms import Compose, ToTensor from torchvision.datasets import MNIST from torch.utils.data import DataLoader transforms = Compose([ ToTensor(), # Normalize( # mean=[0.1307], # std=[0.3081], # ) ]) trainset = MNIST(root='./mnist_data', train=True, download=True, transform=transforms) testset = MNIST(root='./mnist_data', train=False, download=True, transform=transforms) trainloader = DataLoader(trainset, batch_size=96, shuffle=True) testloader = DataLoader(testset, batch_size=96, shuffle=True)
训练执行代码
net = net_mnist(28*28, 10) net.to(device) criterion = nn.CrossEntropyLoss().to(device) writer = SummaryWriter() net = train_mnist(net, trainloader, testloader, criterion, lrate=0.03, max_epochs=6)
错误信息
RuntimeError Traceback (most recent call last) <ipython-input-21-6bc9f6dcde7f> in <cell line: 5>() 3 criterion = nn.CrossEntropyLoss().to(device) 4 writer = SummaryWriter() ----> 5 net = train_mnist(net,trainloader,testloader,criterion,lrate=0.03,max_epochs=6) 5 frames /usr/local/lib/python3.10/dist-packages/torch/nn/modules/conv.py in _conv_forward(self, input, weight, bias) 307 weight, bias, self.stride, 308 _single(0), self.dilation, self.groups) ---> 309 return F.conv1d(input, weight, bias, self.stride, 310 self.padding, self.dilation, self.groups) 311 RuntimeError: Expected 2D (unbatched) or 3D (batched) input to conv1d, but got input of size: [96, 1, 28, 28]
核心需求
- 将MNIST输入从
[batch_size, 1, 28, 28]转换为[batch_size, 1, 784],适配nn.Conv1d的输入要求(3D张量:[batch_size, in_channels, sequence_length]) - 修复模型中未定义
conv2的问题 - 确保模型forward流程正确(当前末尾的
return x.squeeze()永远不会执行)
内容的提问来源于stack exchange,提问作者jerry gill
相关产品推荐
相关产品推荐

