Python 网格搜索分类的自定义评分函数

Python 网格搜索分类的自定义评分函数,python,scikit-learn,classification,grid-search,Python,Scikit Learn,Classification,Grid Search,我想在scikit learn中为RandomForestClassifier执行GridSearchCV,并且我有一个我想使用的自定义评分函数 评分函数仅在提供概率的情况下有效(例如,必须调用rfc.predict\u probabila(…),而不是rfc.predict(…)) 我如何指示GridSearchCV使用predict\u proba()而不是predict() 请参阅文档:可调用项应具有参数(估计器,X,y) 然后你可以在定义中使用,estimator.predict\u p

我想在scikit learn中为
RandomForestClassifier
执行
GridSearchCV
,并且我有一个我想使用的自定义评分函数

评分函数仅在提供概率的情况下有效(例如,必须调用
rfc.predict\u probabila(…)
,而不是
rfc.predict(…)

我如何指示GridSearchCV使用
predict\u proba()
而不是
predict()

请参阅文档:可调用项应具有参数(估计器,X,y)

然后你可以在定义中使用,
estimator.predict\u proba(X)

或者,您可以使用with
needs\u proba=True

完整的代码示例:

from sklearn.datasets import make_classification
from sklearn.model_selection import GridSearchCV
from sklearn.ensemble import RandomForestClassifier
from sklearn.metrics import make_scorer
import pandas as pd
import numpy as np

X, y = make_classification()
def my_custom_loss_func_est(estimator, X, y):
    # predictions must be probabilities - e.g. model.predict_proba()
    # example code here:
    diff = np.abs(y - estimator.predict_proba(X)[:, 1]).max()
    return -np.log(1 + diff)

def my_custom_loss_func(ground_truth, predictions):
    # predictions must be probabilities - e.g. model.predict_proba()
    # example code here:
    diff = np.abs(ground_truth - predictions[:, 1]).max()
    return np.log(1 + diff)

custom_scorer = make_scorer(my_custom_loss_func, 
                            greater_is_better=False,
                            needs_proba=True)
使用记分器对象:

param_grid = {'min_samples_leaf': [10, 50], 'n_estimators': [100, 200]}
grid = GridSearchCV(RandomForestClassifier(), param_grid=param_grid,
                scoring=custom_scorer, return_train_score=True)
grid.fit(X, y)
pd.DataFrame(grid.cv_results_)[['mean_test_score',
                                   'mean_train_score',
                                   'param_min_samples_leaf',
                                   'param_n_estimators']]

    mean_test_score mean_train_score    param_min_samples_leaf    param_n_estimators
0         -0.505201        -0.495011                        10                   100
1         -0.509190        -0.498283                        10                   200
2         -0.406279        -0.406292                        50                   100
3         -0.406826        -0.406862                        50                   200
直接使用损失函数也很容易

grid = GridSearchCV(RandomForestClassifier(), param_grid=param_grid,
                scoring=my_custom_loss_func_est,     return_train_score=True)
grid.fit(X, y)
pd.DataFrame(grid.cv_results_)[['mean_test_score',
                                   'mean_train_score',
                                   'param_min_samples_leaf',
                                   'param_n_estimators']]

    mean_test_score mean_train_score    param_min_samples_leaf  param_n_estimators
0         -0.509098        -0.491462                        10                100
1         -0.497693        -0.490936                        10                200
2         -0.409025        -0.408957                        50                100
3         -0.409525        -0.409500                        50                200

结果因cv折叠不同而不同(我假设,但我现在太懒了,无法设置种子并再次编辑(或者有没有更好的方法来粘贴代码而不需要手动缩进?)

使用scorer对象(
scoring=custom\u scorer
)时,使用
sklearn==0.23.2
),它给出了这个错误
索引器:数组的索引太多:数组是一维的,但有2个索引了
,它指向这一行
diff=np.abs(ground\u truth-predictions[:,1]).max()。这似乎表明
predictions
是一个1D数组,但它被索引为一个2D数组。这是令人困惑的,因为
.predict_proba()
应该返回一个2D数组,所以使用
[:,1]
对其进行索引应该是可以的。有没有线索说明是什么导致了这个错误?
grid = GridSearchCV(RandomForestClassifier(), param_grid=param_grid,
                scoring=my_custom_loss_func_est,     return_train_score=True)
grid.fit(X, y)
pd.DataFrame(grid.cv_results_)[['mean_test_score',
                                   'mean_train_score',
                                   'param_min_samples_leaf',
                                   'param_n_estimators']]

    mean_test_score mean_train_score    param_min_samples_leaf  param_n_estimators
0         -0.509098        -0.491462                        10                100
1         -0.497693        -0.490936                        10                200
2         -0.409025        -0.408957                        50                100
3         -0.409525        -0.409500                        50                200