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

sklearn的GridSearch中如何将候选模型传入parameter-aware自定义评分函数

sklearn GridSearchCV 传入候选模型到自定义评分函数的解决方案

实现方法

sklearn的GridSearchCV(包括所有继承自BaseSearchCV的调参类)的scoring参数原生支持接收带(estimator, X, y_true)签名的自定义评分函数,调用时会自动传入当前候选参数、在对应折叠训练集上拟合完成的模型实例,无需额外手动传参。
示例代码如下:

import numpy as np
from sklearn.ensemble import RandomForestClassifier
from sklearn.model_selection import GridSearchCV

# 自定义parameter-aware评分函数,第一个参数直接接收当前候选拟合模型
def custom_scorer(estimator, X_val, y_val):
    # 可直接获取当前模型的所有参数、拟合后属性
    current_params = estimator.get_params()
    y_pred = estimator.predict(X_val)
    acc = np.mean(y_pred == y_val)
    # 示例:结合参数做自定义计算,比如对max_depth过大的模型加惩罚
    return acc - current_params["max_depth"] * 0.01

# 初始化模型和参数网格
clf = RandomForestClassifier(random_state=42)
param_grid = {"max_depth": [3, 5, 10], "n_estimators": [50, 100]}

# 直接将自定义评分函数传给scoring参数即可,无需make_scorer包装
grid = GridSearchCV(clf, param_grid, scoring=custom_scorer, cv=5)
grid.fit(X, y)

注意事项

  • 不需要用make_scorer包装你的自定义函数:make_scorer仅用于将仅接收y_true、y_pred的普通指标转为sklearn兼容的scorer,使用estimator作为首参数的签名直接传入函数即可。
  • 此方法拿到的模型是当前候选参数拟合完成的实例,完全和cross_val_score传入的模型逻辑一致,不会出现默认参数未拟合的问题。
  • 如需同时计算多个自定义指标,可给scoring传入字典,键为指标名称,值为对应的评分函数。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.30 12:57:05