基于lenet的手写数字识别PYTORCH
时间: 2024-10-23 16:18:46 浏览: 25
LeNet是一种经典的卷积神经网络(Convolutional Neural Network,CNN),它最初由Yann LeCun等人在1998年应用于手写数字识别任务,尤其是MNIST数据集上。在PyTorch中实现基于LeNet的手写数字识别可以分为以下几个步骤:
1. **导入库**:首先,你需要导入必要的PyTorch库,包括`torch`, `torch.nn`, 和 `torch.optim`。
```python
import torch
import torch.nn as nn
import torch.optim as optim
```
2. **构建模型**:定义一个继承自`nn.Module`的类,其中包含卷积层、池化层、全连接层等组件。
```python
class LeNet(nn.Module):
def __init__(self):
super(LeNet, self).__init__()
self.conv1 = nn.Conv2d(1, 6, kernel_size=5)
self.pool = nn.MaxPool2d(2, 2)
self.conv2 = nn.Conv2d(6, 16, kernel_size=5)
self.fc1 = nn.Linear(16 * 4 * 4, 120) # Flatten the output of conv2
self.fc2 = nn.Linear(120, 84)
self.fc3 = nn.Linear(84, 10) # Output layer for 10 classes
def forward(self, x):
x = F.relu(self.pool(F.relu(self.conv1(x))))
x = F.relu(self.pool(F.relu(self.conv2(x))))
x = x.view(-1, 16 * 4 * 4) # Reshape for fully connected layers
x = F.relu(self.fc1(x))
x = F.relu(self.fc2(x))
x = self.fc3(x)
return x
```
3. **加载数据**:使用PyTorch的数据集模块如`torchvision.datasets`获取MNIST数据,并进行预处理。
```python
from torchvision import datasets, transforms
transform = transforms.Compose([transforms.ToTensor(), transforms.Normalize((0.1307,), (0.3081,))])
train_dataset = datasets.MNIST(root='./data', train=True, transform=transform, download=True)
test_dataset = datasets.MNIST(root='./data', train=False, transform=transform)
train_loader = torch.utils.data.DataLoader(train_dataset, batch_size=64, shuffle=True)
test_loader = torch.utils.data.DataLoader(test_dataset, batch_size=64, shuffle=False)
```
4. **训练模型**:定义损失函数(如交叉熵)、优化器(如Adam)并开始训练过程。
```python
model = LeNet()
criterion = nn.CrossEntropyLoss()
optimizer = optim.Adam(model.parameters(), lr=0.001)
for epoch in range(num_epochs): # Train for a number of epochs
for images, labels in train_loader:
optimizer.zero_grad() # Clear gradients
outputs = model(images)
loss = criterion(outputs, labels)
loss.backward() # Backpropagation
optimizer.step() # Update weights
```
5. **评估模型**:测试模型在测试集上的性能。
```python
correct_count, all_count = 0, 0
with torch.no_grad():
for images, labels in test_loader:
outputs = model(images)
_, predicted = torch.max(outputs.data, 1)
all_count += labels.size(0)
correct_count += (predicted == labels).sum().item()
accuracy = 100 * correct_count / all_count
print(f"Test accuracy: {accuracy}%")
```
阅读全文