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

使用GridSearchCV调优DecisionTreeRegressor时遇Criterion的KeyError问题

解决DecisionTreeRegressor调优时的KeyError问题

问题原因分析

  • criterion参数取值不匹配sklearn版本:在sklearn 0.24.2中,DecisionTreeRegressor的criterion可选值为'mse'、'mae'、'friedman_mse'、'poisson'。你使用的'squared_root'是不存在的参数值(推测是squared_error的笔误,但squared_error也是1.0+版本才引入的别名);'absolute_error'同样是1.0+版本才有的'mae'别名,0.24.2不支持。
  • 参数网格格式错误:max_depth=(list(range(1, 20)))的写法会将整个列表作为单个候选值传递给模型,而不是逐个遍历1到19的整数。这种错误会干扰参数组合的生成,可能引发异常。
  • 评分指标选择错误:用分类任务的'accuracy'指标评估回归模型不符合逻辑,会导致评分计算异常,可能与参数错误叠加触发奇怪的KeyError。

修正后的代码

from sklearn.tree import DecisionTreeRegressor
from sklearn.model_selection import GridSearchCV

# 修正参数网格:使用0.24.2支持的criterion值,修正max_depth格式
params = {
    "criterion": ('mse', 'mae', 'poisson'), 
    "splitter": ("best", "random"), 
    "max_depth": list(range(1, 20)), 
    "min_samples_split": [2, 3, 4], 
    "min_samples_leaf": list(range(1, 20)), 
}

tree_reg = DecisionTreeRegressor(random_state=42)
# 替换为回归任务的评分指标,比如r2或neg_mean_squared_error
tree_reg = GridSearchCV(tree_reg, params, scoring="r2", n_jobs=-1, verbose=1, cv=3)
tree_reg.fit(X_train, y_train)
best_params = tree_reg.best_params_
print(f"Best paramters: {best_params}")

额外说明

  • 若想使用'absolute_error'或'squared_error',需要升级sklearn到1.0及以上版本。
  • 单独测试criterion时未报错,是因为参数组合少,评分指标的异常未触发致命错误,但实际上'accuracy'对回归任务毫无意义,必须替换。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.18 09:23:19