Python 在sklearn中使用自定义评分功能
假设我在sci工具包学习中使用了以下自定义损失函数。在这种情况下,我只对模型得分高于0.8的观察值进行评分Python 在sklearn中使用自定义评分功能,python,scikit-learn,Python,Scikit Learn,假设我在sci工具包学习中使用了以下自定义损失函数。在这种情况下,我只对模型得分高于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'
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函数中的第三个参数放在哪里有点困惑?根据make_scorer
接受一个传递给评分函数的**kwargs
参数,以便在调用该函数时可以按名称添加任何其他参数。看。这是您的代码和对scorer的更新调用
# New function with the `threshold` parameter
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']))
scorer = make_scorer(mf.customLoss ,greater_is_better = True, threshold = 0.8)