PyTorch训练VGG16模型后无法绘制训练集与验证集损失及准确率曲线
问题排查与解决方法
核心问题点
- 原训练函数未对每轮的损失、准确率数值做持久化存储,仅做了控制台打印,训练完成后无历史数据可用于绘图
- 绘图代码逻辑完全错误:
- 未初始化
loss_values就直接调用append方法 - Pytorch模型对象不是字典,无法通过
model['train','validation']读取损失数据 - 未区分损失、准确率两类指标的绘图逻辑
- 定义的
ss_values变量无任何实际作用
- 未初始化
修复步骤
1. 调整训练函数,新增历史数据记录逻辑
修改train_model函数,初始化存储指标的列表,每轮计算完指标后存入列表,最终随模型一同返回:
import time import copy import torch import torch.nn as nn import torch.optim as optim from torch.optim import lr_scheduler import matplotlib.pyplot as plt def train_model(model, criterion, optimizer, scheduler, num_epochs, device, dataloaders, dataset_sizes): since = time.time() best_model_wts = copy.deepcopy(model.state_dict()) best_acc = 0.0 # 初始化存储历史指标的列表 train_loss_history = [] val_loss_history = [] train_acc_history = [] val_acc_history = [] for epoch in range(num_epochs): print('Epoch {}/{} LR {:.6f}'.format(epoch, num_epochs - 1, scheduler.get_last_lr()[0])) print('-' * 10) for phase in ['train', 'validation']: if phase == 'train': model.train() else: model.eval() running_loss = 0.0 running_corrects = 0 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) if phase == 'train': scheduler.step() epoch_loss = running_loss / dataset_sizes[phase] epoch_acc = running_corrects.double() / dataset_sizes[phase] print('{} Loss: {:.4f} Acc: {:.4f}'.format(phase, epoch_loss, epoch_acc)) # 存入对应指标列表,acc转为普通数值避免后续绘图报错 if phase == 'train': train_loss_history.append(epoch_loss) train_acc_history.append(epoch_acc.cpu().item()) else: val_loss_history.append(epoch_loss) val_acc_history.append(epoch_acc.cpu().item()) if phase == 'validation' and epoch_acc > best_acc: best_acc = epoch_acc best_model_wts = copy.deepcopy(model.state_dict()) print() time_elapsed = time.time() - since print('Training complete in {:.0f}m {:.0f}s'.format(time_elapsed // 60, time_elapsed % 60)) print('Best val Acc: {:4f}'.format(best_acc)) model.load_state_dict(best_model_wts) # 返回历史指标 return model, (train_loss_history, val_loss_history, train_acc_history, val_acc_history)
2. 修正训练调用代码
修复原代码中损失函数和优化器定义的语法错误,同时接收返回的历史指标:
# 修复原代码语法错误:拆分两行 criterion = nn.CrossEntropyLoss() optimizer = optim.Adam(model.parameters(), lr=0.0001) exp_lr_scheduler = lr_scheduler.StepLR(optimizer, step_size=7, gamma=0.1) # 接收返回的模型和历史指标 model, history = train_model(model, criterion, optimizer, exp_lr_scheduler, num_epochs=5, device=device, dataloaders=dataloaders, dataset_sizes=dataset_sizes) model = model.to(device) train_loss, val_loss, train_acc, val_acc = history
3. 替换为正确的绘图代码
分别绘制损失曲线和准确率曲线:
# 绘制损失曲线 plt.figure(figsize=(12,5)) plt.subplot(1,2,1) plt.plot(train_loss, label='训练损失') plt.plot(val_loss, label='验证损失') plt.xlabel('轮次') plt.ylabel('损失值') plt.title('训练/验证损失变化') plt.legend(loc='upper right') # 绘制准确率曲线 plt.subplot(1,2,2) plt.plot(train_acc, label='训练准确率') plt.plot(val_acc, label='验证准确率') plt.xlabel('轮次') plt.ylabel('准确率') plt.title('训练/验证准确率变化') plt.legend(loc='lower right') plt.tight_layout() plt.show()
内容的提问来源于stack exchange,提问作者cliff
相关产品推荐
相关产品推荐

