Use matplotlib to draw good-looking line charts

Use matplotlib to draw good-looking line charts


Problem Description

When training a neural network, a large amount of data is generated, including but not only train_loss, test_accuracy. These data are generally saved in .csv files, but it is really troublesome to draw the curve manually every time, and the graph for weekly reporting does not need to be so refined, as long as you can see the trend. It is really convenient to automatically draw pictures and save them to the specified folder when the model is trained.

Solution

1. Save the training data of each epoch to a list.
2. Drawing.

import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt

x1 = range(0, T, 1)
y1 = final_train_loss#final_train_loss是一个list
y2 = final_test_loss
y3 = final_train_accuracy
y4 = final_test_accuracy

#########huitu#########
plt.figure()
plt.plot(x1, y1, '.-',label='train_loss')
plt.plot(x1, y2, '--',label='test_loss')
plt.title('loss & communication round')
plt.ylabel('loss')
plt.xlabel('T')
plt.xticks(rotation=45)
plt.legend()
plt.grid(True)
plt.savefig('./SimulationData/FL_Dynamic/Weight/%s_Dynamic_fed_weight%s_%s_%sUEs_%s_T%s_epoch%s_iid%s_%s_%s_LOSS.png'\
            %(Time,weight,have_classifier, args.num_users, args.dataset,T,args.set_local_ep,args.iid, args.degree_noniid,timeslot))
  

plt.figure()
# plt.style.use('ggplot') #给图片换不同的风格
plt.plot(x1, y3, '.-',label='train_acc')
plt.plot(x1, y4,'--',label='test_acc')
plt.title('accuracy & communication round')#设置图片标题
plt.ylabel('accuracy')#纵坐标
plt.xlabel('T') #横坐标
plt.xticks(rotation=45)#坐标轴旋转45度
plt.legend()#显示图例
plt.grid(True)
#将图片保存指定文件夹下并命名为指定名字
plt.savefig('./SimulationData/FL_Dynamic/Weight/%s_Dynamic_fed_weight%s_%s_%sUEs_%s_T%s_epoch%s_iid%s_%s_%s_ACCURACY.png'\
            %(Time,weight,have_classifier, args.num_users, args.dataset,T,args.set_local_ep,args.iid, args.degree_noniid,timeslot))
# plt.show()

insert image description here
insert image description here
Well, it turns out that the model is overfitting, but this picture seems to be ok, quite beautiful~
Reference link: https://zhuanlan.zhihu.com/p/24675460

Guess you like

Origin blog.csdn.net/qq_38703529/article/details/121914006