pytorch用Resnet进行人脸识别的代码并绘制训练集和测试集的损失和精度曲线图
时间: 2024-03-15 22:47:48 浏览: 106
以下是使用 PyTorch 和 ResNet 进行人脸识别的代码,并绘制训练集和测试集的损失和精度曲线图:
```python
import torch
import torch.nn as nn
import torchvision.models as models
import matplotlib.pyplot as plt
# 加载数据集和定义转换
train_dataset = torchvision.datasets.CIFAR10(root='./data', train=True,
transform=torchvision.transforms.ToTensor(),
download=True)
test_dataset = torchvision.datasets.CIFAR10(root='./data', train=False,
transform=torchvision.transforms.ToTensor())
# 定义数据加载器
batch_size = 100
train_loader = torch.utils.data.DataLoader(dataset=train_dataset,
batch_size=batch_size,
shuffle=True)
test_loader = torch.utils.data.DataLoader(dataset=test_dataset,
batch_size=batch_size,
shuffle=False)
# 加载 ResNet 模型
resnet = models.resnet18(pretrained=True)
# 冻结 ResNet 的所有层
for param in resnet.parameters():
param.requires_grad = False
# 将最后一层的输出特征数修改为人脸的类别数
num_classes = 10
resnet.fc = nn.Linear(resnet.fc.in_features, num_classes)
# 定义损失函数和优化器
criterion = nn.CrossEntropyLoss()
optimizer = torch.optim.Adam(resnet.fc.parameters())
# 训练模型
num_epochs = 10
total_step = len(train_loader)
train_loss = []
test_loss = []
train_acc = []
test_acc = []
for epoch in range(num_epochs):
epoch_train_loss = 0
epoch_test_loss = 0
epoch_train_acc = 0
epoch_test_acc = 0
resnet.train()
for i, (images, labels) in enumerate(train_loader):
images = images.to(device)
labels = labels.to(device)
outputs = resnet(images)
loss = criterion(outputs, labels)
epoch_train_loss += loss.item()
optimizer.zero_grad()
loss.backward()
optimizer.step()
_, predicted = torch.max(outputs.data, 1)
epoch_train_acc += (predicted == labels).sum().item()
resnet.eval()
with torch.no_grad():
for images, labels in test_loader:
images = images.to(device)
labels = labels.to(device)
outputs = resnet(images)
loss = criterion(outputs, labels)
epoch_test_loss += loss.item()
_, predicted = torch.max(outputs.data, 1)
epoch_test_acc += (predicted == labels).sum().item()
train_loss.append(epoch_train_loss/len(train_loader))
test_loss.append(epoch_test_loss/len(test_loader))
train_acc.append(epoch_train_acc/len(train_dataset))
test_acc.append(epoch_test_acc/len(test_dataset))
print ('Epoch [{}/{}], Train Loss: {:.4f}, Test Loss: {:.4f}, Train Acc: {:.2f} %, Test Acc: {:.2f} %'
.format(epoch+1, num_epochs, train_loss[-1], test_loss[-1], train_acc[-1]*100, test_acc[-1]*100))
# 绘制损失和精度曲线图
plt.subplot(2, 1, 1)
plt.plot(train_loss, label='Train Loss')
plt.plot(test_loss, label='Test Loss')
plt.legend()
plt.title('Loss')
plt.subplot(2, 1, 2)
plt.plot(train_acc, label='Train Acc')
plt.plot(test_acc, label='Test Acc')
plt.legend()
plt.title('Accuracy')
plt.show()
```
在这个代码中,我们使用了一个预先训练好的 ResNet-18 模型,将其最后一层的输出特征数修改为我们需要分类的类别数,并且只训练了最后一层的参数。在训练期间,我们使用交叉熵损失函数和 Adam 优化器来更新模型的参数,并记录每个 epoch 的训练集和测试集的损失和精度。在测试期间,我们使用测试集来评估模型的准确性。最后,我们使用 matplotlib 库绘制训练集和测试集的损失和精度曲线图。
阅读全文