gpt4 book ai didi

python - 如何从 GridSearchCV 绘制网格分数?

转载 作者:IT老高 更新时间:2023-10-28 20:57:45 26 4
gpt4 key购买 nike

我正在寻找一种在 sklearn 中从 GridSearchCV 绘制 grid_scores_ 的方法。在这个例子中,我试图网格搜索 SVR 算法的最佳 gamma 和 C 参数。我的代码如下所示:

    C_range = 10.0 ** np.arange(-4, 4)
gamma_range = 10.0 ** np.arange(-4, 4)
param_grid = dict(gamma=gamma_range.tolist(), C=C_range.tolist())
grid = GridSearchCV(SVR(kernel='rbf', gamma=0.1),param_grid, cv=5)
grid.fit(X_train,y_train)
print(grid.grid_scores_)

运行代码并打印网格分数后,我得到以下结果:

[mean: -3.28593, std: 1.69134, params: {'gamma': 0.0001, 'C': 0.0001}, mean: -3.29370, std: 1.69346, params: {'gamma': 0.001, 'C': 0.0001}, mean: -3.28933, std: 1.69104, params: {'gamma': 0.01, 'C': 0.0001}, mean: -3.28925, std: 1.69106, params: {'gamma': 0.1, 'C': 0.0001}, mean: -3.28925, std: 1.69106, params: {'gamma': 1.0, 'C': 0.0001}, mean: -3.28925, std: 1.69106, params: {'gamma': 10.0, 'C': 0.0001},etc] 

我想根据 gamma 和 C 参数可视化所有分数(平均值)。我试图获得的图表应如下所示:

enter image description here

其中 x 轴是 gamma,y 轴是平均分数(本例中的均方根误差),不同的线代表不同的 C 值。

最佳答案

@sascha 显示的代码是正确的。但是,grid_scores_ 属性很快就会被弃用。最好使用 cv_results 属性。

它可以以与@sascha 方法类似的方式实现:

def plot_grid_search(cv_results, grid_param_1, grid_param_2, name_param_1, name_param_2):
# Get Test Scores Mean and std for each grid search
scores_mean = cv_results['mean_test_score']
scores_mean = np.array(scores_mean).reshape(len(grid_param_2),len(grid_param_1))

scores_sd = cv_results['std_test_score']
scores_sd = np.array(scores_sd).reshape(len(grid_param_2),len(grid_param_1))

# Plot Grid search scores
_, ax = plt.subplots(1,1)

# Param1 is the X-axis, Param 2 is represented as a different curve (color line)
for idx, val in enumerate(grid_param_2):
ax.plot(grid_param_1, scores_mean[idx,:], '-o', label= name_param_2 + ': ' + str(val))

ax.set_title("Grid Search Scores", fontsize=20, fontweight='bold')
ax.set_xlabel(name_param_1, fontsize=16)
ax.set_ylabel('CV Average Score', fontsize=16)
ax.legend(loc="best", fontsize=15)
ax.grid('on')

# Calling Method
plot_grid_search(pipe_grid.cv_results_, n_estimators, max_features, 'N Estimators', 'Max Features')

以上结果如下图:

enter image description here

关于python - 如何从 GridSearchCV 绘制网格分数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37161563/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com