首页 > 解决方案 > sklearn中make_scorer中的自定义函数

问题描述

我正在尝试创建一个自定义评分函数以在 GridSearchCV 中实现分类问题,但我认为我不太了解它的工作原理(我已阅读文档)。我的目标是对错误分类的类型赋予不同的权重。我的代码如下所示。good并且excellent是我的样本所属的两个类别。我认为问题在于何时GridSearchCV将真实值和预测值传递给score_func但我不知道如何解决它。

def score_func(y, y_pred):
    '''score function for grid search'''
    error = 0
    for i in range(len(y)):
        if y[i] == 'excellent':
            if y_pred[i] == 'excellent':
                error += 10
            elif y_pred[i] == 'good':
                error += 5
    return error

score_f = make_scorer(score_func, needs_proba=False ,needs_threshold=False)

RF = make_pipeline(
        StandardScaler(),
        RandomForestClassifier(random_state=101, criterion = 'gini')
        )

gs_rf = GridSearchCV(estimator=RF, param_grid=param_grid, scoring=score_f, 
                     cv=KFold(5, True, random_state=1234)).fit(X_data,y_data)

提前致谢!

标签: pythonmachine-learningscikit-learnclassificationscoring

解决方案


如果您的目标是为标签关联权重,则无需创建函数。

只需使用class_weight参数 from RandomForestClassifier

weight_dict = {'excellent':10, 'good':5}
RandomForestClassifier(random_state=101, criterion='gini', class_weight=weight_dict)

推荐阅读