文章预览:
1.可视化train,test的loss acc
1.1 案例:交通指示牌识别案例-history数组
代码地址:E:\项目例程\猫狗分类\迁移学习\猫狗_resnet18_2 \猫狗分类_迁移学习可视化
- 导入库
from collections import defaultdict
- 训练函数中构建一个默认value为list的字典
history = defaultdict(list) # 构建一个默认value为list的字典
- 训练函数中保存train_loss,train_acc,test_loss,test_acc结果
history['train_acc'].append(train_accuracy)
history['train_loss'].append(train_loss)
history['val_acc'].append(val_accuracy)
history['val_loss'].append(val_loss)
- 训练函数返回
return model, history
- 训练模型调用时
# 调用训练函数训练
model_conv, history = train_model(
model_conv,
criterion,
optimizer_conv,
exp_lr_scheduler,
num_epochs=30
)
- 绘制函数 两张图,每个图两个曲线,写法固定
注意:若运行不出图,则加plt.show()
# 绘制 loss, acc 写法固定:两张表
def plot_training_history(history):
fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(18, 6))
ax1.plot(history['train_loss'], label='train loss')
ax1.plot(history['val_loss'], label='val loss')
ax1.set_ylim([-0.05, 1.05])
ax1.legend()
ax1.set_ylabel('Loss')
ax1.set_xlabel('Epoch')
ax2.plot(history['train_acc'], label='train acc')
ax2.plot(history['val_acc'], label='val acc'