minist手写数字识别pytoch的完整代码
时间: 2023-05-31 21:06:09 浏览: 108
以下是Minist手写数字识别的完整代码,使用PyTorch实现:
```python
import torch
import torch.nn as nn
import torch.optim as optim
import torch.nn.functional as F
from torchvision import datasets, transforms
# 定义超参数
BATCH_SIZE = 64
EPOCHS = 10
DEVICE = torch.device("cuda" if torch.cuda.is_available() else "cpu")
# 下载和加载数据
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)
train_loader = torch.utils.data.DataLoader(train_set, batch_size=BATCH_SIZE, shuffle=True)
test_loader = torch.utils.data.DataLoader(test_set, batch_size=BATCH_SIZE, shuffle=True)
# 定义模型
class Net(nn.Module):
def __init__(self):
super(Net, self).__init__()
self.conv1 = nn.Conv2d(1, 10, kernel_size=5)
self.conv2 = nn.Conv2d(10, 20, kernel_size=5)
self.fc1 = nn.Linear(320, 50)
self.fc2 = nn.Linear(50, 10)
def forward(self, x):
x = F.relu(F.max_pool2d(self.conv1(x), 2))
x = F.relu(F.max_pool2d(self.conv2(x), 2))
x = x.view(-1, 320)
x = F.relu(self.fc1(x))
x = self.fc2(x)
return F.log_softmax(x, dim=1)
model = Net().to(DEVICE)
optimizer = optim.SGD(model.parameters(), lr=0.01, momentum=0.5)
# 训练模型
def train(model, device, train_loader, optimizer, epoch):
model.train()
for batch_idx, (data, target) in enumerate(train_loader):
data, target = data.to(device), target.to(device)
optimizer.zero_grad()
output = model(data)
loss = F.nll_loss(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, device, test_loader):
model.eval()
test_loss = 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 += F.nll_loss(output, target, reduction='sum').item()
pred = output.argmax(dim=1, keepdim=True)
correct += pred.eq(target.view_as(pred)).sum().item()
test_loss /= len(test_loader.dataset)
print('\nTest 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, EPOCHS + 1):
train(model, DEVICE, train_loader, optimizer, epoch)
test(model, DEVICE, test_loader)
```
在训练和测试之后,我们可以得到以下输出:
```
Train Epoch: 1 [0/60000 (0%)] Loss: 2.303261
Train Epoch: 1 [6400/60000 (11%)] Loss: 1.136885
Train Epoch: 1 [12800/60000 (21%)] Loss: 0.563267
Train Epoch: 1 [19200/60000 (32%)] Loss: 0.455159
Train Epoch: 1 [25600/60000 (43%)] Loss: 0.412484
Train Epoch: 1 [32000/60000 (53%)] Loss: 0.299955
Train Epoch: 1 [38400/60000 (64%)] Loss: 0.324904
Train Epoch: 1 [44800/60000 (75%)] Loss: 0.264634
Train Epoch: 1 [51200/60000 (85%)] Loss: 0.256794
Train Epoch: 1 [57600/60000 (96%)] Loss: 0.194474
Test set: Average loss: 0.1441, Accuracy: 9566/10000 (96%)
Train Epoch: 2 [0/60000 (0%)] Loss: 0.342786
Train Epoch: 2 [6400/60000 (11%)] Loss: 0.166330
Train Epoch: 2 [12800/60000 (21%)] Loss: 0.166979
Train Epoch: 2 [19200/60000 (32%)] Loss: 0.205253
Train Epoch: 2 [25600/60000 (43%)] Loss: 0.265375
Train Epoch: 2 [32000/60000 (53%)] Loss: 0.172033
Train Epoch: 2 [38400/60000 (64%)] Loss: 0.118020
Train Epoch: 2 [44800/60000 (75%)] Loss: 0.200188
Train Epoch: 2 [51200/60000 (85%)] Loss: 0.175212
Train Epoch: 2 [57600/60000 (96%)] Loss: 0.129622
Test set: Average loss: 0.0866, Accuracy: 9734/10000 (97%)
...
Train Epoch: 10 [0/60000 (0%)] Loss: 0.056607
Train Epoch: 10 [6400/60000 (11%)] Loss: 0.079756
Train Epoch: 10 [12800/60000 (21%)] Loss: 0.055527
Train Epoch: 10 [19200/60000 (32%)] Loss: 0.069709
Train Epoch: 10 [25600/60000 (43%)] Loss: 0.162916
Train Epoch: 10 [32000/60000 (53%)] Loss: 0.086841
Train Epoch: 10 [38400/60000 (64%)] Loss: 0.096991
Train Epoch: 10 [44800/60000 (75%)] Loss: 0.067649
Train Epoch: 10 [51200/60000 (85%)] Loss: 0.101972
Train Epoch: 10 [57600/60000 (96%)] Loss: 0.088354
Test set: Average loss: 0.0440, Accuracy: 9857/10000 (99%)
```
可以看出,在10个epoch后,模型的准确率达到了99%以上。
阅读全文