有一些深度学习模型是并不像yolo系列那样最终输出相应的参数图,有很多训练形成了一个训练log文件,于是需要读取log文件中的内容并绘制成曲线图。
如下实例,有一个log文件的部分截图,需要将其读取出来并绘制曲线图
废话不多说,直接上代码
import os
import re
import pandas as pd
import matplotlib.pyplot as plt
import matplotlib.ticker as ticker
txt_dir = 'D:/TEST/train.log' # 文件路径
# 读取文件内容
with open(txt_dir, "r") as f:data = f.read()# print(data)
# 利用正则匹配出相应的数据并提取
epoch_num = re.findall("Epoch (.*) Train", data)
# print(epoch_num)
Loss_MSE_MAE = re.findall("Train, (.*), Cost", data) # 由于找不到合适的正则条件,于是先取出来一整行数据后续重新正则匹配
# print(Loss_MSE_MAE)
Loss = []
MSE = []
MAE = []
for info in Loss_MSE_MAE:# print(info)Loss_num = re.findall("Loss: (.*), MSE", info)MSE_num = re.findall("MSE: (.*) MAE", info)MAE_num = re.findall("MAE: (.*)", info)# print(Loss_num, '/n', MSE_num,'/n', MAE_num)Loss.append(Loss_num[0])MSE.append(MSE_num[0])MAE.append(MAE_num[0])
# print(Loss, MSE, MAE)
# 将列表中数字的引号去掉生成参数列表
Loss = str(Loss).replace("'","")
Loss = Loss.replace("[", "").replace("]", "").split(", ")
Loss = [float(d) for d in Loss]MSE = str(MSE).replace("'","")
MSE = MSE.replace("[", "").replace("]", "").split(", ")
MSE = [float(d) for d in MSE]MAE = str(MAE).replace("'","")
MAE = MAE.replace("[", "").replace("]", "").split(", ")
MAE = [float(d) for d in MAE]
# print(Loss, MSE, MAE)# 开始画图,前面我们得到了epoch,这将作为横坐标,得到了Loss, MSE, MAE等参数,将用于画图
# 下面是同时生成三张图的方法,可以参考
fig, axs = plt.subplots(nrows=1, ncols=3, figsize=(30, 6), dpi=300)
y_data = [Loss[2:], MSE[2:], MAE[2:]]
colors = ['red', 'green', 'blue']
line_style = ['-', '-', '-']
y_labels = ['Loss', 'MSE', 'MAE']
for i in range(3):# axs[i].plot(epoch_num[2:300], y_data[i], c = colors[i], label = y_labels[i], linestyle = line_style[i]) # 横坐标加了epoch太长axs[i].plot(y_data[i], c = colors[i], label = y_labels[i], linestyle = line_style[i]) # 所以不要了epoch,横坐标自动调整# axs[i].scatter(epoch_num[2:], y_data[i], c = colors[i]) # 每个epoch节点对应的数据axs[i].legend(loc='best') # legend图例,用于说明每条曲线的文字显示axs[i].set_yticks(range(0, 150, 5)) # set_yticks用于设置y刻度列表# axs[i].grid(True, linestyle='--', alpha=0.5) # grid用于设置网格线外观axs[i].set_xlabel("epoch_num", fontdict={'size': 8}) # set_xlabel用于设置x轴标题 axs[i].set_ylabel(y_labels[i], fontdict={'size': 8}, rotation=90) # set_ylabel用于设置y轴标题,rotation表示旋转90度axs[i].set_title("train_metric_{}".format(y_labels[i]), fontdict={'size': 8})
fig.autofmt_xdate() # 改变x轴坐标的显示方法可以斜着表示,不用平着挤一堆
plt.savefig('D:/TEST/train_metric_map.png', bbox_inches='tight', pad_inches=0.0, dpi=300)
# plt.show()
最终得到图像如下