第4关:使用pytorch搭建卷积神经网络识别手写数字 命令
时间: 2024-01-30 11:03:05 浏览: 96
使用pytorch搭建卷积神经网络识别手写数字的命令如下:
```python
import torch
import torch.nn as nn
import torch.optim as optim
from torchvision import datasets, transforms
# 定义数据预处理
transform = transforms.Compose([
transforms.ToTensor(),
transforms.Normalize((0.1307,), (0.3081,))
])
# 加载数据集
train_set = datasets.MNIST('./data', train=True, download=True, transform=transform)
test_set = datasets.MNIST('./data', train=False, download=True, transform=transform)
# 定义模型
class Net(nn.Module):
def __init__(self):
super(Net, self).__init__()
self.conv1 = nn.Conv2d(1, 32, kernel_size=3)
self.conv2 = nn.Conv2d(32, 64, kernel_size=3)
self.fc1 = nn.Linear(64 * 5 * 5, 128)
self.fc2 = nn.Linear(128, 10)
def forward(self, x):
x = nn.functional.relu(self.conv1(x))
x = nn.functional.relu(self.conv2(x))
x = nn.functional.max_pool2d(x, 2)
x = x.view(-1, 64 * 5 * 5)
x = nn.functional.relu(self.fc1(x))
x = self.fc2(x)
return nn.functional.log_softmax(x, dim=1)
# 训练模型
model = Net()
optimizer = optim.SGD(model.parameters(), lr=0.01, momentum=0.5)
loss_fn = nn.NLLLoss()
def train(epoch):
model.train()
for batch_idx, (data, target) in enumerate(train_set):
optimizer.zero_grad()
output = model(data.unsqueeze(0))
loss = loss_fn(output, torch.tensor([target]))
loss.backward()
optimizer.step()
if batch_idx % 1000 == 0:
print('Train Epoch: {} [{}/{} ({:.0f}%)]\tLoss: {:.6f}'.format(
epoch, batch_idx * len(data), len(train_set.dataset),
100. * batch_idx / len(train_set), loss.item()))
for epoch in range(1, 11):
train(epoch)
# 测试模型
model.eval()
test_loss = 0
correct = 0
with torch.no_grad():
for data, target in test_set:
output = model(data.unsqueeze(0))
test_loss += loss_fn(output, torch.tensor([target]), reduction='sum').item()
pred = output.argmax(dim=1, keepdim=True)
correct += pred.eq(torch.tensor([target]).view_as(pred)).sum().item()
test_loss /= len(test_set.dataset)
print('\nTest set: Average loss: {:.4f}, Accuracy: {}/{} ({:.0f}%)\n'.format(
test_loss, correct, len(test_set.dataset),
100. * correct / len(test_set.dataset)))
```
阅读全文