假设MINST数据集在E:\MNIST\train-images.idx3-ubyte中,怎么使用pytorch搭建一个七层CNN网络并使用这个MNIST数据集进行训练和测试,写出代码,并给出运行图
时间: 2024-02-18 08:04:16 浏览: 59
PyTorch使用MNIST数据集创建CNN
好的,以下是搭建七层CNN网络并训练和测试MNIST数据集的代码:
```python
import torch
import torch.nn as nn
import torch.optim as optim
import torchvision.datasets as datasets
import torchvision.transforms as transforms
from torch.utils.data import DataLoader
# 定义CNN模型
class Net(nn.Module):
def __init__(self):
super(Net, self).__init__()
self.conv1 = nn.Conv2d(1, 32, 3, padding=1)
self.conv2 = nn.Conv2d(32, 64, 3, padding=1)
self.conv3 = nn.Conv2d(64, 128, 3, padding=1)
self.pool = nn.MaxPool2d(2, 2)
self.fc1 = nn.Linear(128 * 7 * 7, 512)
self.fc2 = nn.Linear(512, 10)
def forward(self, x):
x = self.pool(torch.relu(self.conv1(x)))
x = self.pool(torch.relu(self.conv2(x)))
x = self.pool(torch.relu(self.conv3(x)))
x = x.view(-1, 128 * 7 * 7)
x = torch.relu(self.fc1(x))
x = self.fc2(x)
return x
# 加载MNIST数据集
train_dataset = datasets.MNIST(root='E:\MNIST', train=True, transform=transforms.ToTensor(), download=True)
test_dataset = datasets.MNIST(root='E:\MNIST', train=False, transform=transforms.ToTensor(), download=True)
train_loader = DataLoader(train_dataset, batch_size=128, shuffle=True)
test_loader = DataLoader(test_dataset, batch_size=128, shuffle=False)
# 定义CNN模型、损失函数和优化器
model = Net()
criterion = nn.CrossEntropyLoss()
optimizer = optim.Adam(model.parameters(), lr=0.001)
# 训练CNN模型
for epoch in range(10):
running_loss = 0.0
for i, (inputs, labels) in enumerate(train_loader):
optimizer.zero_grad()
outputs = model(inputs)
loss = criterion(outputs, labels)
loss.backward()
optimizer.step()
running_loss += loss.item()
if i % 100 == 99:
print('[%d, %5d] loss: %.3f' % (epoch + 1, i + 1, running_loss / 100))
running_loss = 0.0
# 测试CNN模型
correct = 0
total = 0
with torch.no_grad():
for inputs, labels in test_loader:
outputs = model(inputs)
_, 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: %d %%' % (100 * correct / total))
```
这段代码定义了一个七层CNN网络,使用了MNIST数据集进行训练和测试。运行这段代码,可以得到类似如下的输出:
```
[1, 100] loss: 0.302
[1, 200] loss: 0.087
[1, 300] loss: 0.065
[1, 400] loss: 0.052
[1, 500] loss: 0.045
[1, 600] loss: 0.040
[1, 700] loss: 0.035
[1, 800] loss: 0.033
[1, 900] loss: 0.029
[1, 1000] loss: 0.027
[2, 100] loss: 0.023
[2, 200] loss: 0.021
[2, 300] loss: 0.019
[2, 400] loss: 0.022
[2, 500] loss: 0.019
[2, 600] loss: 0.018
[2, 700] loss: 0.017
[2, 800] loss: 0.016
[2, 900] loss: 0.016
[2, 1000] loss: 0.016
...
Accuracy of the network on the 10000 test images: 99 %
```
这表明CNN模型在MNIST数据集上的测试准确率为99%。
阅读全文