使用pytorch nn的比较复杂的网络完成手写数字识别,python代码
时间: 2024-02-20 12:57:32 浏览: 59
好的,以下是一个使用PyTorch的深度神经网络完成手写数字识别的Python代码示例:
```python
import torch
import torch.nn as nn
import torchvision.datasets as dsets
import torchvision.transforms as transforms
from torch.autograd import Variable
# 超参数设置
input_size = 784 # 输入的大小为28x28
hidden_size = 500 # 隐藏层神经元个数
num_classes = 10 # 输出层类别个数
num_epochs = 5 # 训练轮数
batch_size = 100 # 每次训练的图片数量
learning_rate = 0.001 # 学习率
# MNIST数据集
train_dataset = dsets.MNIST(root='./data',
train=True,
transform=transforms.ToTensor(),
download=True)
test_dataset = dsets.MNIST(root='./data',
train=False,
transform=transforms.ToTensor())
# 数据加载器
train_loader = torch.utils.data.DataLoader(dataset=train_dataset,
batch_size=batch_size,
shuffle=True)
test_loader = torch.utils.data.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
net = Net(input_size, hidden_size, num_classes)
# 定义损失函数和优化器
criterion = nn.CrossEntropyLoss()
optimizer = torch.optim.Adam(net.parameters(), lr=learning_rate)
# 训练模型
for epoch in range(num_epochs):
for i, (images, labels) in enumerate(train_loader):
images = Variable(images.view(-1, 28*28))
labels = Variable(labels)
optimizer.zero_grad()
outputs = net(images)
loss = criterion(outputs, labels)
loss.backward()
optimizer.step()
if (i+1) % 100 == 0:
print ('Epoch [%d/%d], Step [%d/%d], Loss: %.4f'
%(epoch+1, num_epochs, i+1, len(train_dataset)//batch_size, loss.data))
# 测试模型
correct = 0
total = 0
for images, labels in test_loader:
images = Variable(images.view(-1, 28*28))
outputs = net(images)
_, predicted = torch.max(outputs.data, 1)
total += labels.size(0)
correct += (predicted == labels).sum()
print('Accuracy of the network on the 10000 test images: %d %%' % (100 * correct / total))
```
这个代码使用PyTorch的`nn`模块定义了一个具有一个隐藏层的前馈神经网络。该网络使用MNIST数据集进行训练和测试,其中训练轮数为5,每次训练使用100个图片。在训练过程中,网络使用交叉熵损失函数和Adam优化器进行反向传播和参数更新。在测试过程中,网络计算准确率并输出结果。
阅读全文