首页 > 解决方案 > 自定义评分指标 sklearn 逻辑回归

问题描述

假设我在 sci-kit learn 中使用了以下自定义损失函数。在这种情况下,我只对模型得分高于 0.8 的观察结果进行评分。

def customLoss(y_true, y_pred):
    a = pd.DataFrame({'Actuals':y_true, 'Preds': y_pred})
    a = a.query('Preds > 0.8')
    return(precision_score(a['Actuals'], a['Preds']))

param_grid = {'C': [0.001, 0.01, 0.1, 1, 10]}
scorer = make_scorer(mf.customLoss ,greater_is_better = True)
grid = GridSearchCV(LogisticRegression(class_weight = 'balanced'), param_grid = param_grid, scoring = scorer, cv = 5)

但是,假设我想让阈值 (0.8) 可配置。显然,我需要向我的损失函数添加第三个参数,如下所示:

def customLoss(y_true, y_pred, threshold):
        a = pd.DataFrame({'Actuals':y_true, 'Preds': y_pred})
        a = a.query('Preds > @threshold')
        return(precision_score(a['Actuals'], a['Preds']))

但是,我对make_scorer将第三个参数放在函数中的哪个位置有点困惑?

标签: pythonscikit-learn

解决方案


尝试

grid = GridSearchCV(LogisticRegression(class_weight = 'balanced'), param_grid = param_grid, scoring = 'metric_you_want', cv = 5)

推荐阅读