基于MNIST 手写数字识别模型代码要有key(s) in state_dict: "fc3.weight", "fc3.bias"
时间: 2023-07-19 08:33:35 浏览: 95
好的,这是一个基于MNIST手写数字识别的LeNet模型代码示例,你可以参考一下:
```python
import torch
import torch.nn as nn
import torch.nn.functional as F
class LeNet(nn.Module):
def __init__(self):
super(LeNet, self).__init__()
self.conv1 = nn.Conv2d(1, 6, kernel_size=5)
self.pool1 = nn.MaxPool2d(kernel_size=2)
self.conv2 = nn.Conv2d(6, 16, kernel_size=5)
self.pool2 = nn.MaxPool2d(kernel_size=2)
self.fc1 = nn.Linear(16 * 4 * 4, 120)
self.fc2 = nn.Linear(120, 84)
self.fc3 = nn.Linear(84, 10)
def forward(self, x):
x = F.relu(self.conv1(x))
x = self.pool1(x)
x = F.relu(self.conv2(x))
x = self.pool2(x)
x = x.view(-1, 16 * 4 * 4)
x = F.relu(self.fc1(x))
x = F.relu(self.fc2(x))
x = self.fc3(x)
return x
model = LeNet()
# 加载预训练模型权重
pretrained_dict = torch.load('lenet_mnist.pth')
model_dict = model.state_dict()
# 去掉不匹配的键
pretrained_dict = {k: v for k, v in pretrained_dict.items() if k in model_dict}
# 更新模型权重
model_dict.update(pretrained_dict)
model.load_state_dict(model_dict)
```
当你加载预训练模型权重时,如果出现了"fc3.weight"和"fc3.bias"这两个键缺失的问题,可以将这两个键从模型权重中去掉,然后再更新模型权重。
阅读全文