pytorch卷积minist代码
时间: 2023-12-19 19:57:35 浏览: 86
计算卷积的matlab代码-KIUnetpPytorch:KIUnetpPytorch
可以直接用PyTorch提供的MNIST数据集进行训练,下面是一个简单的卷积神经网络模型代码:
```
import torch
from torch import nn
from torchvision import datasets, transforms
# 定义模型
class Net(nn.Module):
def __init__(self):
super().__init__()
self.conv1 = nn.Conv2d(1, 16, 3, padding=1)
self.conv2 = nn.Conv2d(16, 32, 3, padding=1)
self.conv3 = nn.Conv2d(32, 64, 3, padding=1)
self.pool = nn.MaxPool2d(2, 2)
self.fc1 = nn.Linear(64 * 7 * 7, 256)
self.fc2 = nn.Linear(256, 10)
self.dropout = nn.Dropout(p=0.5)
def forward(self, x):
x = self.pool(nn.functional.relu(self.conv1(x)))
x = self.pool(nn.functional.relu(self.conv2(x)))
x = self.pool(nn.functional.relu(self.conv3(x)))
x = x.view(-1, 64 * 7 * 7)
x = nn.functional.relu(self.fc1(x))
x = self.dropout(x)
x = self.fc2(x)
return nn.functional.log_softmax(x, dim=1)
# 加载数据
transform = transforms.Compose([
transforms.ToTensor(),
transforms.Normalize((0.5,), (0.5,))
])
train_set = datasets.MNIST('data', train=True, download=True, transform=transform)
train_loader = torch.utils.data.DataLoader(train_set, batch_size=64, shuffle=True)
test_set = datasets.MNIST('data', train=False, download=True, transform=transform)
test_loader = torch.utils.data.DataLoader(test_set, batch_size=64, shuffle=True)
# 训练模型
model = Net().to('cuda')
optimizer = torch.optim.Adam(model.parameters(), lr=0.001)
criterion = nn.NLLLoss()
for epoch in range(10):
running_loss = 0
for images, labels in train_loader:
optimizer.zero_grad()
images, labels = images.to('cuda'), labels.to('cuda')
output = model(images)
loss = criterion(output, labels)
loss.backward()
optimizer.step()
running_loss += loss.item()
print(f'Epoch {epoch+1} Loss: {running_loss/len(train_loader)}')
# 测试模型
model.eval()
correct = 0
with torch.no_grad():
for images, labels in test_loader:
images, labels = images.to('cuda'), labels.to('cuda')
output = model(images)
_, predicted = torch.max(output.data, 1)
correct += (predicted == labels).sum().item()
print(f'Test Accuracy: {correct/len(test_set)}')
```
在这个代码中,我们定义了一个名为“Net”的卷积神经网络模型,包含3个卷积层、3个最大池化层、2个全连接层和1个Dropout层,共计128万个参数。然后我们加载MNIST数据集,进行训练和测试。在训练过程中,我们使用Adam优化器和负对数似然损失函数,每个Epoch训练一遍。在测试过程中,我们关闭梯度计算,仅仅测试模型的预测精度。
阅读全文