生成pytorch卷积神经网络minist数据集代码
时间: 2023-11-14 09:06:16 浏览: 160
当然可以!以下是一个简单的 PyTorch 卷积神经网络处理 MNIST 数据集的代码:
```
import torch
from torch import nn, optim
from torchvision import datasets, transforms
# Define a transform to normalize the data
transform = transforms.Compose([transforms.ToTensor(),
transforms.Normalize((0.5,), (0.5,)),
])
# Download and load the training data
trainset = datasets.MNIST('~/.pytorch/MNIST_data/', download=True, train=True, transform=transform)
trainloader = torch.utils.data.DataLoader(trainset, batch_size=64, shuffle=True)
# Define the model
model = nn.Sequential(nn.Conv2d(1, 32, 3, padding=1),
nn.ReLU(),
nn.MaxPool2d(2, 2),
nn.Conv2d(32, 64, 3, padding=1),
nn.ReLU(),
nn.MaxPool2d(2, 2),
nn.Flatten(),
nn.Linear(7*7*64, 512),
nn.ReLU(),
nn.Linear(512, 10),
nn.LogSoftmax(dim=1))
# Define the loss function and optimizer
criterion = nn.NLLLoss()
optimizer = optim.Adam(model.parameters(), lr=0.003)
# Train the model
epochs = 5
for e in range(epochs):
running_loss = 0
for images, labels in trainloader:
# Clear the gradients
optimizer.zero_grad()
# Forward pass
output = model(images)
loss = criterion(output, labels)
# Backward pass and optimization
loss.backward()
optimizer.step()
running_loss += loss.item()
else:
print(f"Training loss: {running_loss/len(trainloader)}")
```
希望这段代码可以帮到你!
阅读全文