pytorch手写数字识别
时间: 2023-09-14 08:08:44 浏览: 132
手写数字识别(pytorch版)
PyTorch是一种基于Python的深度学习框架,可以用于训练神经网络并实现各种机器学习任务,包括手写数字识别。下面是一个简单的PyTorch手写数字识别的示例:
首先,我们需要导入需要的库和模块:
```python
import torch
import torch.nn as nn
import torch.optim as optim
from torch.autograd import Variable
from torchvision import datasets, transforms
```
然后,我们定义一个类来构建我们的神经网络模型。在这个例子中,我们使用一个简单的卷积神经网络(CNN)模型:
```python
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 = nn.functional.relu(nn.functional.max_pool2d(self.conv1(x), 2))
x = nn.functional.relu(nn.functional.max_pool2d(self.conv2(x), 2))
x = x.view(-1, 320)
x = nn.functional.relu(self.fc1(x))
x = self.fc2(x)
return nn.functional.log_softmax(x, dim=1)
```
接下来,我们设置一些超参数并加载MNIST数据集:
```python
batch_size = 64
learning_rate = 0.01
momentum = 0.5
train_dataset = datasets.MNIST(root='./data/', train=True, transform=transforms.ToTensor(), download=True)
test_dataset = datasets.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)
```
然后,我们实例化我们的模型和优化器:
```python
model = Net()
optimizer = optim.SGD(model.parameters(), lr=learning_rate, momentum=momentum)
```
接下来,我们定义训练和测试函数:
```python
def train(epoch):
model.train()
for batch_idx, (data, target) in enumerate(train_loader):
data, target = Variable(data), Variable(target)
optimizer.zero_grad()
output = model(data)
loss = nn.functional.nll_loss(output, target)
loss.backward()
optimizer.step()
if batch_idx % 10 == 0:
print('Train Epoch: {} [{}/{} ({:.0f}%)]\tLoss: {:.6f}'.format(
epoch, batch_idx * len(data), len(train_loader.dataset),
100. * batch_idx / len(train_loader), loss.data[0]))
def test():
model.eval()
test_loss = 0
correct = 0
for data, target in test_loader:
data, target = Variable(data, volatile=True), Variable(target)
output = model(data)
test_loss += nn.functional.nll_loss(output, target, size_average=False).data[0]
pred = output.data.max(1, keepdim=True)[1]
correct += pred.eq(target.data.view_as(pred)).cpu().sum()
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)))
```
最后,我们开始训练和测试我们的模型:
```python
for epoch in range(1, 10):
train(epoch)
test()
```
这个示例代码训练了一个简单的CNN模型来对MNIST数据集中的手写数字进行分类。在训练了10个epoch之后,模型的测试准确率约为98%左右。你也可以尝试调整超参数和网络结构来改进模型的性能。
阅读全文