pytorch卷积神经网络代码
时间: 2023-06-30 08:14:08 浏览: 81
pytorch卷积神经网络代码教学
好的,以下是一个简单的 PyTorch 卷积神经网络的示例代码:
```python
import torch
import torch.nn as nn
# 定义卷积神经网络模型
class CNN(nn.Module):
def __init__(self):
super(CNN, self).__init__()
self.conv1 = nn.Conv2d(3, 32, kernel_size=3, stride=1, padding=1)
self.conv2 = nn.Conv2d(32, 64, kernel_size=3, stride=1, padding=1)
self.pool = nn.MaxPool2d(kernel_size=2, stride=2)
self.fc1 = nn.Linear(64 * 8 * 8, 1024)
self.fc2 = nn.Linear(1024, 10)
def forward(self, x):
x = self.conv1(x)
x = nn.functional.relu(x)
x = self.pool(x)
x = self.conv2(x)
x = nn.functional.relu(x)
x = self.pool(x)
x = x.view(x.size(0), -1)
x = self.fc1(x)
x = nn.functional.relu(x)
x = self.fc2(x)
return x
# 定义训练函数
def train(model, train_loader, optimizer, criterion, device):
model.train()
train_loss = 0
correct = 0
total = 0
for batch_idx, (inputs, targets) in enumerate(train_loader):
inputs, targets = inputs.to(device), targets.to(device)
optimizer.zero_grad()
outputs = model(inputs)
loss = criterion(outputs, targets)
loss.backward()
optimizer.step()
train_loss += loss.item()
_, predicted = outputs.max(1)
total += targets.size(0)
correct += predicted.eq(targets).sum().item()
return train_loss/(batch_idx+1), 100.*correct/total
# 定义测试函数
def test(model, test_loader, criterion, device):
model.eval()
test_loss = 0
correct = 0
total = 0
with torch.no_grad():
for batch_idx, (inputs, targets) in enumerate(test_loader):
inputs, targets = inputs.to(device), targets.to(device)
outputs = model(inputs)
loss = criterion(outputs, targets)
test_loss += loss.item()
_, predicted = outputs.max(1)
total += targets.size(0)
correct += predicted.eq(targets).sum().item()
return test_loss/(batch_idx+1), 100.*correct/total
# 加载数据集
train_loader = torch.utils.data.DataLoader(trainset, batch_size=128, shuffle=True, num_workers=2)
test_loader = torch.utils.data.DataLoader(testset, batch_size=128, shuffle=False, num_workers=2)
# 定义超参数
device = 'cuda' if torch.cuda.is_available() else 'cpu'
lr = 0.001
momentum = 0.9
epochs = 10
# 初始化模型、优化器、损失函数
model = CNN().to(device)
optimizer = torch.optim.SGD(model.parameters(), lr=lr, momentum=momentum)
criterion = nn.CrossEntropyLoss()
# 开始训练和测试
for epoch in range(1, epochs+1):
train_loss, train_acc = train(model, train_loader, optimizer, criterion, device)
test_loss, test_acc = test(model, test_loader, criterion, device)
print('Epoch: {:03d}, Train Loss: {:.3f}, Train Acc: {:.3f}%, Test Loss: {:.3f}, Test Acc: {:.3f}%'.format(epoch, train_loss, train_acc, test_loss, test_acc))
```
以上代码中定义了一个简单的卷积神经网络模型,用于对 CIFAR10 数据集进行分类任务。同时定义了训练和测试函数,以及超参数和优化器、损失函数等。
阅读全文