You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

sklearn 0.22.1中GridSearchCV无cv_results_属性,绘图报错求助

解决GridSearchCV无cv_results_属性的问题

嘿,这个问题我之前也碰到过,核心原因很简单——你没有执行网格搜索的拟合步骤!

问题分析

  1. cv_results_属性只有在调用GridSearchCV.fit(X, y)完成网格搜索后才会生成,你现在只定义了GridSearchCV对象,但没让它跑起来,自然找不到这个属性。
  2. 至于grid_scores_,它在scikit-learn 0.20版本就被弃用了,0.22.1已经彻底移除,所以用不了是正常的。

修正后的完整代码

我帮你补全了缺失的导入和关键的fit步骤,还修正了一处绘图的小问题:

import matplotlib.pyplot as plt
import pandas as pd
from sklearn.model_selection import GridSearchCV
import xgboost as xgb  # 确保你初始化了xgb模型,比如xgb = xgb.XGBRegressor()

# 替换成你的训练特征X和目标变量y
# X = ... 
# y = ...

trees_grid = {"n_estimators":[100,150,200,250,300,350,400,450]}
grid_search = GridSearchCV(estimator=xgb, n_jobs=1, param_grid=trees_grid, 
                           scoring="neg_mean_absolute_error", cv=10, verbose=1, 
                           return_train_score=True)

# 关键步骤:执行网格搜索拟合
grid_search.fit(X, y)

# 现在可以正常获取cv_results_了
results = pd.DataFrame(grid_search.cv_results_)

plt.figure(figsize=(8,8))  # 替换原代码里的figsize(8,8),这才是正确的调用方式
plt.style.use("ggplot")
plt.plot(results["param_n_estimators"], -1*results["mean_test_score"], label="testing error")
plt.plot(results["param_n_estimators"], -1*results["mean_train_score"], label="training error")
plt.legend()
plt.ylabel("mean absolute error", size=20)
plt.xlabel("number of trees", size=20)
plt.show()

额外注意点

  • 确保你已经正确初始化了XGBoost模型(比如xgb = xgb.XGBRegressor()),不然estimator=xgb会报错。
  • 一定要替换代码里的X和y为你的真实训练数据,不然fit步骤无法执行。

内容的提问来源于stack exchange,提问作者Senior

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.06 15:32:31