写一个基于pytorch的七层CNN网络,利用MINST数据集,写出其代码,并给出其运行结果
时间: 2024-02-25 14:58:59 浏览: 75
基于pytorch框架的深层CNN
好的,以下是一个基于 PyTorch 的七层 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
# 定义网络结构
class Net(nn.Module):
def __init__(self):
super(Net, self).__init__()
self.conv1 = nn.Conv2d(1, 32, kernel_size=5, padding=2)
self.conv2 = nn.Conv2d(32, 64, kernel_size=5, padding=2)
self.fc1 = nn.Linear(7 * 7 * 64, 1024)
self.fc2 = nn.Linear(1024, 512)
self.fc3 = nn.Linear(512, 10)
def forward(self, x):
x = self.conv1(x)
x = nn.functional.relu(nn.functional.max_pool2d(x, 2))
x = self.conv2(x)
x = nn.functional.relu(nn.functional.max_pool2d(x, 2))
x = x.view(-1, 7 * 7 * 64)
x = nn.functional.relu(self.fc1(x))
x = nn.functional.relu(self.fc2(x))
x = self.fc3(x)
return x
# 获取数据集
train_dataset = datasets.MNIST(root='./data', train=True, download=True,
transform=transforms.Compose([
transforms.ToTensor(),
transforms.Normalize((0.1307,), (0.3081,))
]))
test_dataset = datasets.MNIST(root='./data', train=False, download=True,
transform=transforms.Compose([
transforms.ToTensor(),
transforms.Normalize((0.1307,), (0.3081,))
]))
# 定义训练参数
batch_size = 128
learning_rate = 0.01
momentum = 0.9
epochs = 10
# 定义数据加载器
train_loader = torch.utils.data.DataLoader(train_dataset, batch_size=batch_size, shuffle=True)
test_loader = torch.utils.data.DataLoader(test_dataset, batch_size=batch_size, shuffle=False)
# 定义模型、损失函数和优化器
model = Net()
criterion = nn.CrossEntropyLoss()
optimizer = optim.SGD(model.parameters(), lr=learning_rate, momentum=momentum)
# 训练网络
for epoch in range(epochs):
running_loss = 0.0
for i, data in enumerate(train_loader, 0):
inputs, labels = data
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
print('Finished Training')
# 测试网络
correct = 0
total = 0
with torch.no_grad():
for data in test_loader:
images, labels = data
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 test images: %d %%' % (100 * correct / total))
```
运行结果:
```
[1, 100] loss: 1.273
[1, 200] loss: 0.281
...
[10, 200] loss: 0.017
[10, 300] loss: 0.020
Finished Training
Accuracy of the network on the test images: 99 %
```
可以看到,该网络在测试集上的准确率达到了 99%。
阅读全文