pyorch 全连接神经网络 mnist识别
时间: 2023-12-08 21:04:30 浏览: 75
好的,下面是利用 PyTorch 实现全连接神经网络进行 MNIST 手写数字识别的代码:
```python
import torch
import torch.nn as nn
import torch.optim as optim
from torch.utils.data import DataLoader
from torchvision import datasets, transforms
# 定义超参数
batch_size = 128
learning_rate = 0.1
num_epochs = 10
# 加载数据集
train_dataset = datasets.MNIST(root='./data', train=True, transform=transforms.ToTensor(), download=True)
test_dataset = datasets.MNIST(root='./data', train=False, transform=transforms.ToTensor(), download=True)
train_loader = DataLoader(train_dataset, batch_size=batch_size, shuffle=True)
test_loader = DataLoader(test_dataset, batch_size=batch_size, shuffle=False)
# 定义模型
class Net(nn.Module):
def __init__(self):
super(Net, self).__init__()
self.fc1 = nn.Linear(28 * 28, 512)
self.fc2 = nn.Linear(512, 10)
def forward(self, x):
x = x.view(-1, 28 * 28)
x = self.fc1(x)
x = nn.functional.relu(x)
x = self.fc2(x)
return x
model = Net()
# 定义损失函数和优化器
criterion = nn.CrossEntropyLoss()
optimizer = optim.SGD(model.parameters(), lr=learning_rate)
# 训练模型
for epoch in range(num_epochs):
for i, (images, labels) in enumerate(train_loader):
# 前向传播
outputs = model(images)
loss = criterion(outputs, labels)
# 反向传播和优化
optimizer.zero_grad()
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_loader), loss.item()))
# 测试模型
model.eval()
with torch.no_grad():
correct = 0
total = 0
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: %.2f %%' % (100 * correct / total))
```
其中,定义的 `Net` 类是一个继承自 `nn.Module` 的神经网络模型类,包含两个全连接层 `fc1` 和 `fc2`。在 `forward` 方法中,将输入的图片展开成一个向量,然后进行前向传播。
在训练过程中,首先将模型的参数传递给优化器,然后进行前向传播、计算损失、反向传播和优化参数。最后,在测试阶段,将模型的参数设置为不可训练状态,然后对测试数据进行预测,并计算准确率。
阅读全文