实现手写数字的识别,使用MNIST数据集内容完成手写数字识别 步骤: 1.准备数据 2.构建模型 3.损失函数 4.模型训练 5.模型的保存和加载 6.模型的评估:损失和准确率 train_batch_size = 64 test_batch_size = 1000 train和test分别训练10次
时间: 2024-03-03 09:51:16 浏览: 95
好的,针对您的问题,我可以为您提供以下代码实现手写数字的识别,使用MNIST数据集完成手写数字识别:
1. 准备数据
```
import torch
import torchvision
import torchvision.transforms as transforms
transform = transforms.Compose([
transforms.ToTensor(),
transforms.Normalize((0.1307,), (0.3081,))])
train_dataset = torchvision.datasets.MNIST(root='./data', train=True,
download=True, transform=transform)
test_dataset = torchvision.datasets.MNIST(root='./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=1000,
shuffle=False)
```
2. 构建模型
```
import torch.nn as nn
import torch.nn.functional as F
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
net = Net()
```
3. 损失函数
```
import torch.optim as optim
criterion = nn.CrossEntropyLoss()
optimizer = optim.SGD(net.parameters(), lr=0.01, momentum=0.5)
```
4. 模型训练
```
for epoch in range(10):
running_loss = 0.0
for i, data in enumerate(train_loader, 0):
inputs, labels = data
optimizer.zero_grad()
outputs = net(inputs)
loss = criterion(outputs, labels)
loss.backward()
optimizer.step()
running_loss += loss.item()
if i % 100 == 99:
print('[%d, %5d] loss: %.3f' %
(epoch + 1, i + 1, running_loss / 100))
running_loss = 0.0
print('Finished Training')
```
5. 模型的保存和加载
```
PATH = './mnist_net.pth'
torch.save(net.state_dict(), PATH)
# 加载模型
net = Net()
net.load_state_dict(torch.load(PATH))
```
6. 模型的评估:损失和准确率
```
correct = 0
total = 0
with torch.no_grad():
for data in test_loader:
images, labels = data
outputs = net(images)
_, predicted = torch.max(outputs.data, 1)
total += labels.size(0)
correct += (predicted == labels).sum().item()
print('Accuracy of the network on the 10000 test images: %d %%' % (
100 * correct / total))
```
以上代码可以实现手写数字的识别,使用MNIST数据集完成手写数字识别,其中train和test分别训练10次,并且包含了准备数据、构建模型、损失函数、模型训练、模型保存和加载、模型评估的完整流程。
阅读全文