用pytorch实现minist手写体识别任务
时间: 2023-11-13 14:05:20 浏览: 95
好的,关于手写数字识别的任务,您可以使用 PyTorch 框架搭建卷积神经网络模型进行训练。以下是具体实现的步骤:
1. 导入必须的库
```
import torch
import torch.nn as nn
import torch.optim as optim
import torch.nn.functional as F
from torchvision import datasets, transforms
```
2. 加载数据集
```
transform = transforms.Compose([
transforms.ToTensor(),
transforms.Normalize((0.1307,), (0.3081,))
])
train_dataset = datasets.MNIST('data', train=True, download=True, transform=transform)
test_dataset = datasets.MNIST('data', train=False, download=True, 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=True)
```
3. 定义模型
```
class Net(nn.Module):
def __init__(self):
super(Net, self).__init__()
self.conv1 = nn.Conv2d(1, 32, 3, 1)
self.conv2 = nn.Conv2d(32, 64, 3, 1)
self.dropout1 = nn.Dropout2d(0.25)
self.dropout2 = nn.Dropout2d(0.5)
self.fc1 = nn.Linear(9216, 128)
self.fc2 = nn.Linear(128, 10)
def forward(self, x):
x = self.conv1(x)
x = F.relu(x)
x = self.conv2(x)
x = F.relu(x)
x = F.max_pool2d(x, 2)
x = self.dropout1(x)
x = torch.flatten(x, 1)
x = self.fc1(x)
x = F.relu(x)
x = self.dropout2(x)
x = self.fc2(x)
output = F.log_softmax(x, dim=1)
return output
```
4. 定义优化器和损失函数
```
model = Net()
optimizer = optim.Adam(model.parameters(), lr=0.001)
criterion = nn.NLLLoss()
```
5. 训练模型
```
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
model.to(device)
epochs = 10
for epoch in range(epochs):
train_loss = 0.0
for data, target in train_loader:
data, target = data.to(device), target.to(device)
optimizer.zero_grad()
output = model(data)
loss = criterion(output, target)
loss.backward()
optimizer.step()
train_loss += loss.item() * data.size(0)
train_loss = train_loss/len(train_loader.dataset)
print('Epoch: {} \t Training Loss: {:.6f}'.format(epoch+1, train_loss))
```
6. 测试模型
```
test_loss = 0.0
correct = 0
with torch.no_grad():
for data, target in test_loader:
data, target = data.to(device), target.to(device)
output = model(data)
test_loss += criterion(output, target).item() * data.size(0)
_, pred = torch.max(output, 1)
correct += torch.sum(pred == target.data)
test_loss = test_loss/len(test_loader.dataset)
accuracy = 100. * correct/len(test_loader.dataset)
print('Test Loss: {:.6f} \t Test Accuracy: {:.2f}%'.format(test_loss, accuracy))
```
通过以上步骤,您就可以完成 PyTorch 实现手写数字识别任务的代码啦!
阅读全文