簡體   English   中英

如何從matplotlib中的循環繪制超參數?

[英]How to plot hyper-parameters from loop in matplotlib?

我的內核帶有以下代碼,其中我想在測試集上運行不同的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):

  • 5、108070.017
  • 25,54273.79
  • 50,55912.80

現在,我想使用matplotlib在圖表中繪制這三個數據點的每一個。 給定下面的代碼片段,我該怎么做? 我不確定在循環中的哪個位置添加要顯示的代碼。 請幫忙。

除其他外,有四種方法可以做到這一點:

在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   

如果我正確地解釋了您的意思,則需要一個條形圖,其中水平軸上的每個刻度是估計量,垂直軸代表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()

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM