使用PyTorch构建卷积神经网络(CNN)来训练图像分类器,识别手写数字
时间: 2024-01-27 11:06:27 浏览: 80
好的,以下是使用PyTorch构建卷积神经网络(CNN)来训练图像分类器,识别手写数字的步骤:
1. 导入必要的库和数据集
```python
import torch
import torch.nn as nn
import torch.optim as optim
import torchvision
import torchvision.transforms as transforms
# 加载手写数字数据集
train_dataset = torchvision.datasets.MNIST(root='./data', train=True, transform=transforms.ToTensor(), download=True)
test_dataset = torchvision.datasets.MNIST(root='./data', train=False, transform=transforms.ToTensor(), download=True)
# 定义批次大小
batch_size = 128
# 加载数据
train_loader = torch.utils.data.DataLoader(train_dataset, batch_size=batch_size, shuffle=True)
test_loader = torch.utils.data.DataLoader(test_dataset, batch_size=batch_size, shuffle=False)
```
2. 定义CNN模型
```python
class CNN(nn.Module):
def __init__(self):
super(CNN, self).__init__()
self.conv1 = nn.Conv2d(1, 32, 5, padding=2)
self.conv2 = nn.Conv2d(32, 64, 5, padding=2)
self.pool = nn.MaxPool2d(2)
self.fc1 = nn.Linear(64*7*7, 1024)
self.fc2 = nn.Linear(1024, 10)
self.dropout = nn.Dropout(p=0.5)
self.relu = nn.ReLU()
def forward(self, x):
x = self.conv1(x)
x = self.relu(x)
x = self.pool(x)
x = self.conv2(x)
x = self.relu(x)
x = self.pool(x)
x = x.view(-1, 64*7*7)
x = self.fc1(x)
x = self.relu(x)
x = self.dropout(x)
x = self.fc2(x)
return x
# 实例化模型
model = CNN()
```
3. 定义损失函数和优化器
```python
criterion = nn.CrossEntropyLoss()
optimizer = optim.Adam(model.parameters(), lr=0.001)
```
4. 训练模型
```python
# 定义训练函数
def train(model, train_loader, criterion, optimizer, epoch):
model.train()
for batch_idx, (data, target) in enumerate(train_loader):
optimizer.zero_grad()
output = model(data)
loss = criterion(output, target)
loss.backward()
optimizer.step()
if batch_idx % 100 == 0:
print('Train Epoch: {} [{}/{} ({:.0f}%)]\tLoss: {:.6f}'.format(
epoch, batch_idx * len(data), len(train_loader.dataset),
100. * batch_idx / len(train_loader), loss.item()))
# 定义测试函数
def test(model, test_loader, criterion):
model.eval()
test_loss, correct = 0, 0
with torch.no_grad():
for data, target in test_loader:
output = model(data)
test_loss += criterion(output, target).item()
pred = output.argmax(dim=1, keepdim=True)
correct += pred.eq(target.view_as(pred)).sum().item()
test_loss /= len(test_loader.dataset)
print('Test set: Average loss: {:.4f}, Accuracy: {}/{} ({:.0f}%)\n'.format(
test_loss, correct, len(test_loader.dataset),
100. * correct / len(test_loader.dataset)))
# 训练模型
for epoch in range(1, 11):
train(model, train_loader, criterion, optimizer, epoch)
test(model, test_loader, criterion)
```
5. 测试模型
```python
# 加载测试数据
test_loader = torch.utils.data.DataLoader(test_dataset, batch_size=1, shuffle=True)
# 预测一张手写数字图片
model.eval()
with torch.no_grad():
for data, target in test_loader:
output = model(data)
print('Predicted Label:', output.argmax(dim=1).item())
break
```
希望这个例子能对您有所帮助!
阅读全文