如何在Matplotlib中绘制循环生成的超参数实验结果
解决MAE与n_estimators的绘图问题
嘿,我来帮你搞定这个Matplotlib绘图的问题~其实最合理的做法是先把所有循环产生的数据收集起来,等循环结束后统一绘图,这样既高效又方便调整图表样式。下面给你两种方案,对应不同的需求:
方案一:完整循环收集数据后绘图(推荐)
如果后续你要跑完整的[5,25,50,100,250,500]所有n_estimators测试,用这个方案最合适。我们先初始化两个空列表,在循环里把每次的n_estimators和对应的MAE存进去,最后一次性绘图:
import matplotlib import matplotlib.pyplot as plt import numpy as np # 初始化空列表存储数据 n_estimators_list = [] mae_list = [] for n_estimators in [5, 25, 50, 100, 250, 500]: my_mae = get_mae(n_estimators, train_X, test_X, train_y, test_y) print(n_estimators, my_mae) # 将每次的结果添加到列表中 n_estimators_list.append(n_estimators) mae_list.append(my_mae) # 循环结束后绘制图表 plt.figure(figsize=(10, 6)) # 设置图表大小 # 用折线+散点的组合,既看趋势又看单个数据点 plt.plot(n_estimators_list, mae_list, marker='o', linestyle='--', color='blue', linewidth=2, markersize=8) plt.xlabel('Number of Estimators (n_estimators)', fontsize=12) plt.ylabel('Mean Absolute Error (MAE)', fontsize=12) plt.title('MAE vs. Number of Estimators', fontsize=14, fontweight='bold') plt.grid(True, alpha=0.3) # 添加网格,让数据更易读 plt.show()
为什么不推荐在循环里每次画一个点?因为那样会重复调用绘图函数,代码冗余,而且后续要调整标题、坐标轴样式时,得修改循环里的每一行代码,非常麻烦。先收集数据再统一绘图,能一次性控制整个图表的外观。
方案二:针对已有的3个数据点绘图
如果你现在只需要用已经得到的3组数据(5→108070.017;25→54273.79;50→55912.80)来绘图,可以直接定义数据列表,跳过循环:
import matplotlib.pyplot as plt # 直接定义已有的数据 n_estimators = [5, 25, 50] mae_values = [108070.017, 54273.79, 55912.80] plt.figure(figsize=(8, 5)) plt.scatter(n_estimators, mae_values, color='red', s=120, label='MAE Data') # 散点图 plt.plot(n_estimators, mae_values, color='red', linestyle='-', alpha=0.7) # 折线连接 plt.xlabel('n_estimators', fontsize=11) plt.ylabel('Mean Absolute Error (MAE)', fontsize=11) plt.title('MAE for Selected n_estimators', fontsize=13) plt.legend() plt.grid(axis='y') plt.show()
这样就能快速生成你需要的图表啦~
内容的提问来源于stack exchange,提问作者ee8291
相关产品推荐
相关产品推荐

