加载ResNet18的.pth模型文件时参数形状不匹配错误的解决求助
加载ResNet18的.pth模型文件时参数形状不匹配错误的解决求助
各位好,我最近遇到了一个模型加载的棘手问题,想请教一下大家的解决方案:
我训练了一个ResNet18模型并保存成了.pth文件,但尝试加载的时候一直报参数形状不匹配的错误,错误信息如下,后面还有好几行类似的格式:
Error loading checkpoint: Error(s) in loading state_dict for ResNet: size mismatch for layer1.0.conv1.weight: copying a param with shape torch.Size([64, 64, 1, 1]) from checkpoint, the shape in current model is torch.Size([64, 64, 3, 3]). size mismatch for layer1.1.conv1.weight: copying a param with shape torch.Size([64, 256, 1, 1]) from checkpoint, the shape in current model is torch.Size([64, 64, 3, 3]). size mismatch for layer2.0.conv1.weight: copying a param with shape torch.Size([128, 256, 1, 1]) from checkpoint, the shape in current model is torch.Size([128, 64, 3, 3]). size mismatch for layer2.0.downsample.0.weight: copying a param with shape torch.Size([512, 256, 1, 1]) from checkpoint, the shape in current model is torch.Size([128, 64, 1, 1]). size mismatch for layer2.0.downsample.1.weight: copying a param with shape torch.Size([512]) from checkpoint, the shape in current model is torch.Size([128]).
这是我当初训练模型的代码:
teacher = models.resnet18(pretrained=True) num_features = teacher.fc.in_features teacher.fc = nn.Linear(num_features, 5) criterion = nn.CrossEntropyLoss() optimizer = optim.SGD(teacher.parameters(), lr=0.0001, momentum=0.9, weight_decay=0.0001) scheduler = optim.lr_scheduler.StepLR(optimizer, step_size=7, gamma=0.1) def train_and_evaluate(model, train_loader, val_loader, criterion, optimizer, num_epochs, lambda_l1, learning_rate): for epoch in range(num_epochs): model.train() for images, labels in train_loader: # Filter out class 2 samples during training mask = labels != 2 images, labels = images[mask], labels[mask] if len(labels) == 0: continue optimizer.zero_grad() outputs = model(images) loss = criterion(outputs, labels) total_loss = loss total_loss.backward() optimizer.step() # Evaluate on both training and validation sets, excluding class 2 train_loss, train_accuracy = evaluate_model(model, train_loader, criterion) val_loss, val_accuracy = evaluate_model(model, val_loader, criterion) print(f"Epoch {epoch+1} - Training Loss: {train_loss:.4f}, Training Accuracy: {train_accuracy:.4%}, Validation Loss: {val_loss:.4f}, Validation Accuracy: {val_accuracy:.4%}")
我知道训练时排除第二类的逻辑写得有点乱,但这个模型训练花了超级久,我真的很想把它救回来😭。
另外,我加载模型的代码是这样的:
checkpoint = torch.load("model968acc.pth", map_location="cpu") teacher.load_state_dict(checkpoint, strict=False)
如果这个模型真的没法抢救了,也想请大家推荐一些靠谱的模型保存方法,避免以后再遇到这种加载失败的问题!
备注:内容来源于stack exchange,提问作者Xayyna
相关产品推荐
相关产品推荐

