如果要混淆矩阵、召回率、准确度这些呢,代码是什么
时间: 2023-12-24 12:05:45 浏览: 58
给定混淆矩阵可以找到二类或多类指标,例如精度、召回率、F1 分数附matlab代码.zip
5星 · 资源好评率100%
当然可以!以下是添加混淆矩阵、召回率、准确度的代码:
1. 导入必要的库和模块
```python
import torch
import torchvision
from torchvision import datasets, models, transforms
import numpy as np
import matplotlib.pyplot as plt
from sklearn.metrics import confusion_matrix
import itertools
```
2. 加载数据集
```python
data_dir = 'path/to/dataset'
train_dir = data_dir + '/train'
valid_dir = data_dir + '/valid'
# 定义数据预处理方式
data_transforms = {
'train': transforms.Compose([
transforms.RandomResizedCrop(224),
transforms.RandomHorizontalFlip(),
transforms.ToTensor(),
transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225])
]),
'valid': transforms.Compose([
transforms.Resize(256),
transforms.CenterCrop(224),
transforms.ToTensor(),
transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225])
]),
}
# 加载数据集
image_datasets = {
'train': datasets.ImageFolder(train_dir, data_transforms['train']),
'valid': datasets.ImageFolder(valid_dir, data_transforms['valid'])
}
# 定义数据加载器
dataloaders = {
'train': torch.utils.data.DataLoader(image_datasets['train'], batch_size=32, shuffle=True),
'valid': torch.utils.data.DataLoader(image_datasets['valid'], batch_size=32, shuffle=True)
}
```
3. 加载预训练模型
```python
# 使用预训练的 ResNet-18 模型
model = models.resnet18(pretrained=True)
# 将模型的最后一层替换成全连接层
num_ftrs = model.fc.in_features
model.fc = torch.nn.Linear(num_ftrs, 2) # 2 表示分类数量
# 将模型转移到 GPU 上
device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
model = model.to(device)
```
4. 定义损失函数和优化器
```python
criterion = torch.nn.CrossEntropyLoss()
# 只更新最后一层的参数
optimizer = torch.optim.SGD(model.fc.parameters(), lr=0.001, momentum=0.9)
```
5. 训练模型
```python
# 训练模型
num_epochs = 10
for epoch in range(num_epochs):
for phase in ['train', 'valid']:
if phase == 'train':
model.train() # 训练模式
else:
model.eval() # 验证模式
running_loss = 0.0
running_corrects = 0
y_true = []
y_pred = []
for inputs, labels in dataloaders[phase]:
inputs = inputs.to(device)
labels = labels.to(device)
# 将梯度清零
optimizer.zero_grad()
# 前向传播
with torch.set_grad_enabled(phase == 'train'):
outputs = model(inputs)
_, preds = torch.max(outputs, 1)
loss = criterion(outputs, labels)
# 反向传播和优化
if phase == 'train':
loss.backward()
optimizer.step()
# 统计损失和正确预测数
running_loss += loss.item() * inputs.size(0)
running_corrects += torch.sum(preds == labels.data)
y_true += labels.cpu().numpy().tolist()
y_pred += preds.cpu().numpy().tolist()
epoch_loss = running_loss / len(image_datasets[phase])
epoch_acc = running_corrects.double() / len(image_datasets[phase])
epoch_recall = recall_score(y_true, y_pred, average='macro')
epoch_precision = precision_score(y_true, y_pred, average='macro')
epoch_f1 = f1_score(y_true, y_pred, average='macro')
epoch_cm = confusion_matrix(y_true, y_pred)
print('{} Loss: {:.4f} Acc: {:.4f} Recall: {:.4f} Precision: {:.4f} F1: {:.4f}'.format(phase, epoch_loss, epoch_acc, epoch_recall, epoch_precision, epoch_f1))
print('Confusion Matrix:')
print(epoch_cm)
```
以上就是添加混淆矩阵、召回率、准确度的代码,希望能对你有所帮助!
阅读全文