绘制resnet34训练集准确度曲线和损失函数曲线pytorch代码
时间: 2023-05-11 07:05:36 浏览: 181
Pytorch练习–绘制Loss曲线
5星 · 资源好评率100%
以下是绘制resnet34训练集准确度曲线和损失函数曲线的PyTorch代码:
```python
import torch
import torch.nn as nn
import torch.optim as optim
import torchvision
import torchvision.transforms as transforms
import matplotlib.pyplot as plt
# Define the ResNet34 model
class ResNet34(nn.Module):
def __init__(self):
super(ResNet34, self).__init__()
self.conv1 = nn.Conv2d(3, 64, kernel_size=3, stride=1, padding=1, bias=False)
self.bn1 = nn.BatchNorm2d(64)
self.relu = nn.ReLU(inplace=True)
self.layer1 = nn.Sequential(
nn.Conv2d(64, 64, kernel_size=3, stride=1, padding=1, bias=False),
nn.BatchNorm2d(64),
nn.ReLU(inplace=True),
nn.Conv2d(64, 64, kernel_size=3, stride=1, padding=1, bias=False),
nn.BatchNorm2d(64),
)
self.layer2 = nn.Sequential(
nn.Conv2d(64, 128, kernel_size=3, stride=2, padding=1, bias=False),
nn.BatchNorm2d(128),
nn.ReLU(inplace=True),
nn.Conv2d(128, 128, kernel_size=3, stride=1, padding=1, bias=False),
nn.BatchNorm2d(128),
)
self.layer3 = nn.Sequential(
nn.Conv2d(128, 256, kernel_size=3, stride=2, padding=1, bias=False),
nn.BatchNorm2d(256),
nn.ReLU(inplace=True),
nn.Conv2d(256, 256, kernel_size=3, stride=1, padding=1, bias=False),
nn.BatchNorm2d(256),
)
self.layer4 = nn.Sequential(
nn.Conv2d(256, 512, kernel_size=3, stride=2, padding=1, bias=False),
nn.BatchNorm2d(512),
nn.ReLU(inplace=True),
nn.Conv2d(512, 512, kernel_size=3, stride=1, padding=1, bias=False),
nn.BatchNorm2d(512),
)
self.avgpool = nn.AdaptiveAvgPool2d((1, 1))
self.fc = nn.Linear(512, 10)
def forward(self, x):
x = self.conv1(x)
x = self.bn1(x)
x = self.relu(x)
x = self.layer1(x) + x
x = self.layer2(x) + x
x = self.layer3(x) + x
x = self.layer4(x) + x
x = self.avgpool(x)
x = x.view(x.size(0), -1)
x = self.fc(x)
return x
# Define the training function
def train(net, trainloader, criterion, optimizer, epoch):
net.train()
running_loss = 0.0
correct = 0
total = 0
for i, data in enumerate(trainloader, 0):
inputs, labels = data
inputs, labels = inputs.cuda(), labels.cuda()
optimizer.zero_grad()
outputs = net(inputs)
loss = criterion(outputs, labels)
loss.backward()
optimizer.step()
running_loss += loss.item()
_, predicted = outputs.max(1)
total += labels.size(0)
correct += predicted.eq(labels).sum().item()
print('Epoch %d, Loss: %.3f, Train Acc: %.3f%%' % (epoch, running_loss/(i+1), 100.*correct/total))
return running_loss/(i+1), 100.*correct/total
# Define the test function
def test(net, testloader, criterion, epoch):
net.eval()
running_loss = 0.0
correct = 0
total = 0
with torch.no_grad():
for i, data in enumerate(testloader, 0):
inputs, labels = data
inputs, labels = inputs.cuda(), labels.cuda()
outputs = net(inputs)
loss = criterion(outputs, labels)
running_loss += loss.item()
_, predicted = outputs.max(1)
total += labels.size(0)
correct += predicted.eq(labels).sum().item()
print('Epoch %d, Loss: %.3f, Test Acc: %.3f%%' % (epoch, running_loss/(i+1), 100.*correct/total))
return running_loss/(i+1), 100.*correct/total
# Load the CIFAR10 dataset
transform_train = transforms.Compose([
transforms.RandomCrop(32, padding=4),
transforms.RandomHorizontalFlip(),
transforms.ToTensor(),
transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5))
])
transform_test = transforms.Compose([
transforms.ToTensor(),
transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5))
])
trainset = torchvision.datasets.CIFAR10(root='./data', train=True, download=True, transform=transform_train)
trainloader = torch.utils.data.DataLoader(trainset, batch_size=128, shuffle=True, num_workers=2)
testset = torchvision.datasets.CIFAR10(root='./data', train=False, download=True, transform=transform_test)
testloader = torch.utils.data.DataLoader(testset, batch_size=100, shuffle=False, num_workers=2)
# Initialize the ResNet34 model, loss function, and optimizer
net = ResNet34().cuda()
criterion = nn.CrossEntropyLoss()
optimizer = optim.SGD(net.parameters(), lr=0.1, momentum=0.9, weight_decay=5e-4)
# Train the model for 200 epochs
train_loss = []
train_acc = []
test_loss = []
test_acc = []
for epoch in range(1, 201):
train_loss_epoch, train_acc_epoch = train(net, trainloader, criterion, optimizer, epoch)
test_loss_epoch, test_acc_epoch = test(net, testloader, criterion, epoch)
train_loss.append(train_loss_epoch)
train_acc.append(train_acc_epoch)
test_loss.append(test_loss_epoch)
test_acc.append(test_acc_epoch)
# Plot the training and test curves
plt.figure()
plt.plot(range(1, 201), train_loss, label='Train Loss')
plt.plot(range(1, 201), test_loss, label='Test Loss')
plt.xlabel('Epoch')
plt.ylabel('Loss')
plt.legend()
plt.show()
plt.figure()
plt.plot(range(1, 201), train_acc, label='Train Acc')
plt.plot(range(1, 201), test_acc, label='Test Acc')
plt.xlabel('Epoch')
plt.ylabel('Accuracy')
plt.legend()
plt.show()
```
希望这个代码对你有所帮助!
阅读全文