minist手写数字识别pytoch完整代码
时间: 2023-05-31 19:06:22 浏览: 123
以下是使用PyTorch进行手写数字识别的完整代码:
```python
import torch
import torch.nn as nn
import torchvision.transforms as transforms
from torchvision.datasets import MNIST
from torch.utils.data import DataLoader
# 设置设备为GPU或CPU
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
# 超参数
input_size = 784
hidden_size = 500
num_classes = 10
num_epochs = 5
batch_size = 100
learning_rate = 0.001
# 加载MNIST数据集
train_dataset = MNIST(root='data/', train=True, transform=transforms.ToTensor(), download=True)
test_dataset = MNIST(root='data/', train=False, transform=transforms.ToTensor())
# 创建数据加载器
train_loader = DataLoader(dataset=train_dataset, batch_size=batch_size, shuffle=True)
test_loader = DataLoader(dataset=test_dataset, batch_size=batch_size, shuffle=False)
# 定义神经网络模型
class Net(nn.Module):
def __init__(self, input_size, hidden_size, num_classes):
super(Net, self).__init__()
self.fc1 = nn.Linear(input_size, hidden_size)
self.relu = nn.ReLU()
self.fc2 = nn.Linear(hidden_size, num_classes)
def forward(self, x):
out = self.fc1(x)
out = self.relu(out)
out = self.fc2(out)
return out
# 实例化模型并移动到设备上
model = Net(input_size, hidden_size, num_classes).to(device)
# 定义损失函数和优化器
criterion = nn.CrossEntropyLoss()
optimizer = torch.optim.Adam(model.parameters(), lr=learning_rate)
# 训练模型
total_step = len(train_loader)
for epoch in range(num_epochs):
for i, (images, labels) in enumerate(train_loader):
# 将输入移动到设备上
images = images.reshape(-1, 28*28).to(device)
labels = labels.to(device)
# 前向传播
outputs = model(images)
loss = criterion(outputs, labels)
# 反向传播和优化
optimizer.zero_grad()
loss.backward()
optimizer.step()
# 每100个batch打印一次训练信息
if (i+1) % 100 == 0:
print('Epoch [{}/{}], Step [{}/{}], Loss: {:.4f}'.format(epoch+1, num_epochs, i+1, total_step, loss.item()))
# 测试模型
with torch.no_grad():
correct = 0
total = 0
for images, labels in test_loader:
# 将输入移动到设备上
images = images.reshape(-1, 28*28).to(device)
labels = labels.to(device)
# 前向传播
outputs = model(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: {} %'.format(100 * correct / total))
```
该代码首先使用PyTorch加载MNIST数据集,并创建了训练和测试数据加载器。然后,定义了一个包含两个全连接层的神经网络模型,并将其移动到设备上。接着,定义了损失函数和优化器,并使用训练数据对模型进行训练。最后,使用测试数据评估了模型的准确度。
阅读全文