用pytorch实现MNIST分类
时间: 2023-11-11 16:07:58 浏览: 91
好的,接下来我将向您展示如何使用PyTorch实现MNIST分类。
首先,我们需要安装PyTorch库。可以通过以下命令在终端中安装:
```
pip install torch torchvision
```
接下来,我们将导入必要的库和模块:
```python
import torch
import torch.nn as nn
import torch.optim as optim
import torchvision.transforms as transforms
from torch.utils.data import DataLoader
from torchvision.datasets import MNIST
```
然后,我们将定义超参数:
```python
batch_size = 128
learning_rate = 0.001
num_epochs = 10
```
接下来,我们将下载MNIST数据集:
```python
train_dataset = MNIST(root='data', train=True, transform=transforms.ToTensor(), download=True)
test_dataset = MNIST(root='data', train=False, transform=transforms.ToTensor(), download=True)
```
然后,我们将使用DataLoader加载训练和测试数据集:
```python
train_loader = DataLoader(dataset=train_dataset, batch_size=batch_size, shuffle=True)
test_loader = DataLoader(dataset=test_dataset, batch_size=batch_size, shuffle=False)
```
接下来,我们将定义一个简单的卷积神经网络模型:
```python
class Net(nn.Module):
def __init__(self):
super(Net, self).__init__()
self.conv1 = nn.Conv2d(in_channels=1, out_channels=32, kernel_size=5, stride=1)
self.maxpool1 = nn.MaxPool2d(kernel_size=2, stride=2)
self.conv2 = nn.Conv2d(in_channels=32, out_channels=64, kernel_size=5, stride=1)
self.maxpool2 = nn.MaxPool2d(kernel_size=2, stride=2)
self.fc1 = nn.Linear(in_features=1024, out_features=256)
self.fc2 = nn.Linear(in_features=256, out_features=10)
def forward(self, x):
x = self.conv1(x)
x = nn.functional.relu(x)
x = self.maxpool1(x)
x = self.conv2(x)
x = nn.functional.relu(x)
x = self.maxpool2(x)
x = x.view(x.size(0), -1)
x = self.fc1(x)
x = nn.functional.relu(x)
x = self.fc2(x)
return x
```
在上面的代码中,我们定义了一个拥有两个卷积层和两个全连接层的模型。
接下来,我们将实例化模型并定义损失函数和优化器:
```python
model = Net()
criterion = nn.CrossEntropyLoss()
optimizer = optim.Adam(model.parameters(), lr=learning_rate)
```
最后,我们将开始训练模型并在测试数据集上进行评估:
```python
for epoch in range(num_epochs):
for i, (images, labels) in enumerate(train_loader):
optimizer.zero_grad()
outputs = model(images)
loss = criterion(outputs, labels)
loss.backward()
optimizer.step()
if (i+1) % 100 == 0:
print('Epoch [{}/{}], Step [{}/{}], Loss: {:.4f}'.format(epoch+1, num_epochs, i+1, len(train_loader), loss.item()))
correct = 0
total = 0
with torch.no_grad():
for images, labels in test_loader:
outputs = model(images)
_, predicted = torch.max(outputs.data, 1)
total += labels.size(0)
correct += (predicted == labels).sum().item()
print('Test Accuracy of the model on the 10000 test images: {} %'.format(100 * correct / total))
```
训练过程中,我们将输出每个epoch的损失,以及在测试数据集上的准确率。最后,我们将得到一个在测试数据集上的准确率。
完整的代码如下:
阅读全文