写一个用resnet18分析jaffe数据集的代码,给出损失图,准确率图和混淆矩阵
时间: 2024-05-13 13:20:12 浏览: 151
使用pytorch写的Resnet代码,详细注释,可以生成训练集和测试集的损失和准确率的折线图
好的,我会尽力回答你的问题,以下是代码示例:
```
import torch
import torch.nn as nn
import torch.optim as optim
import torchvision
import torchvision.transforms as transforms
import matplotlib.pyplot as plt
import numpy as np
from sklearn.metrics import confusion_matrix
device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
# 数据预处理
transform = transforms.Compose([transforms.Resize((224,224)),
transforms.ToTensor(),
transforms.Normalize((0.5,0.5,0.5), (0.5,0.5,0.5))])
train_dataset = torchvision.datasets.ImageFolder(root='jaffe/train', transform=transform)
train_loader = torch.utils.data.DataLoader(train_dataset, batch_size=5, shuffle=True, num_workers=2)
test_dataset = torchvision.datasets.ImageFolder(root='jaffe/test', transform=transform)
test_loader = torch.utils.data.DataLoader(test_dataset, batch_size=5, shuffle=False, num_workers=2)
classes = train_dataset.classes
# 定义模型
class ResNet18(nn.Module):
def __init__(self, num_classes=7):
super(ResNet18, self).__init__()
self.resnet18 = torchvision.models.resnet18(pretrained=True)
self.linear = nn.Linear(1000, num_classes)
def forward(self, x):
x = self.resnet18(x)
x = self.linear(x)
return x
model = ResNet18()
model.to(device)
criterion = nn.CrossEntropyLoss()
optimizer = optim.SGD(model.parameters(), lr=0.001, momentum=0.9)
# 训练模型
for epoch in range(10):
running_loss = 0.0
for i,data in enumerate(train_loader,0):
inputs,labels = data
inputs,labels = inputs.to(device), labels.to(device)
optimizer.zero_grad()
outputs = model(inputs)
loss = criterion(outputs, labels)
loss.backward()
optimizer.step()
running_loss += loss.item()
if i % 10 == 9:
print('[%d,%5d] loss: %.3f' % (epoch+1,i+1,running_loss/10))
running_loss = 0.0
print('Finished Training')
# 测试模型
correct = 0
total = 0
predictions = []
true_labels = []
with torch.no_grad():
for data in test_loader:
images, labels = data
images, labels = images.to(device), labels.to(device)
outputs = model(images)
_, predicted = torch.max(outputs.data, 1)
predictions += predicted.tolist()
true_labels += labels.tolist()
total += labels.size(0)
correct += (predicted == labels).sum().item()
print('Accuracy of the network on the test images: %d %%' % (100 * correct / total))
# 混淆矩阵
confusion_mat = confusion_matrix(true_labels, predictions)
print(confusion_mat)
# 准确率图
plt.plot([0,1,2,3,4,5,6], confusion_mat.diagonal()/confusion_mat.sum(1))
plt.xlabel('Classes')
plt.ylabel('Accuracy')
plt.show()
# 损失图
plt.plot(loss_list)
plt.xlabel('Iteration')
plt.ylabel('Loss')
plt.show()
```
请注意,上述示例仅作参考,需要根据具体情况进行修改。同时,混淆矩阵、准确率图和损失图的绘制需要额外的代码实现,不在此处展示。
阅读全文