我的内核带有以下代码,我想在其测试集上运行不同的n_estimators:
import matplotlib
import matplotlib.pyplot as plt
import numpy as np
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,my_mae):
现在,我想使用matplotlib在图表中绘制这三个数据点中的每一个。给定下面的代码片段,我该怎么做?我不确定在循环中的哪个位置添加要显示的代码。请帮忙。
答案 0 :(得分:1)
其中有四种方法可以实现:
在for循环内绘制单个点
import matplotlib
import matplotlib.pyplot as plt
import numpy as np
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)
plt.scatter(n_estimators, my_mae) # Way 1
# plt.plot(n_estimators, my_mae, 'o') # Way 2
在for循环外绘制所有点
my_maes = []
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)
my_maes.append(my_mae)
plt.plot(n_estimators, my_mae, 'o') # Way 3
# plt.scatter(n_estimators, my_mae) # Way 4
答案 1 :(得分:0)
如果我正确地解释了您的意思,则需要一个条形图,其中水平轴上的每个刻度是估计量,垂直轴代表MAE。只需使用matplotlib.pyplot.bar
。您还需要修改x轴标签,以便它们是自定义的,因为按原样使用估计器的数量会使每个条形的外观不一致。因此,x轴应该是线性的,例如1到6,其中6是您在问题中提供了示例代码段的估算器总数,然后用这些值作图并将x轴标签更改为实际数字估计数。您需要matplotlib.pyplot.xticks
才能更改x轴标签。
因此:
import matplotlib
import matplotlib.pyplot as plt
import numpy as np
values = [5, 25, 50, 100, 250, 500] # New - save for plotting for later
dummy = list(range(len(values))) # Dummy x-axis values for the bar chart
maes = [] # Save the MAEs for each iteration
for n_estimators in values:
my_mae = get_mae(n_estimators, train_X, test_X, train_y, test_y)
maes.append(my_mae) # Save MAE for later
plt.bar(dummy, maes) # Plot the bar chart with each bar having the same distance between each other
plt.xticks(dummy, values) # Now change the x-axis labels
# Add x-label, y-label and title to the graph
plt.xlabel("Number of estimators")
plt.ylabel("MAE")
plt.title("MAE vs. Number of Estimators")
plt.show()