【问题标题】:How to print Recall and Accuracy along with Parameters used in a GridSearch in Sklearn?如何在 Sklearn 的 GridSearch 中打印召回率和准确性以及使用的参数?
【发布时间】:2018-06-01 14:27:30
【问题描述】:

我想打印精度,连同网格中使用的每个参数一起调用,如何做到这一点。

我的 Gridsearch 代码

from sklearn.grid_search import GridSearchCV
rf1=RandomForestClassifier(n_jobs=-1, max_features='sqrt') 
#fit_rf1=rf.fit(X_train_res,y_train_res)

# Use a grid over parameters of interest
param_grid = { 
           "n_estimators" : [50, 100, 150, 200],
           "max_depth" : [2, 5, 10],
           "min_samples_leaf" : [10,20,30]}




from sklearn.metrics import make_scorer
from sklearn.metrics import precision_score,recall_score
scoring = {'precision': make_scorer(precision_score), 'Recall': make_scorer(recall_score)}
    CV_rfc = GridSearchCV(estimator=rf1, param_grid=param_grid, cv= 10,scoring=scoring)
    CV_rfc.fit(X_train_res, y_train_res)

我的预期输出

{'max_depth': 10, 'min_samples_leaf': 2, 'n_estimators': 50,'accuracy':.97,'recall':.89}
{'max_depth': 5, 'min_samples_leaf':10 , 'n_estimators': 100,'accuracy':.98,'recall':.92}

【问题讨论】:

    标签: pandas machine-learning scikit-learn grid-search


    【解决方案1】:

    如果您将scoring 设置为得分者列表,则可以在CV_rfc.cv_results_ 中获得每个得分者的平均得分。

    例如:

    from sklearn.datasets import make_classification
    from sklearn.model_selection import GridSearchCV
    from sklearn.ensemble import RandomForestClassifier
    X, y = make_classification()
    base_clf = RandomForestClassifier()
    param_grid = { 
               "n_estimators" : [50, 100, 150, 200],}
    CV_rf = GridSearchCV(base_clf, param_grid, scoring=['accuracy', 'roc_auc'], refit=False)
    CV_rf.fit(X, y)
    
    print(CV_rf.cv_results_)
    

    你会得到如下输出:

    {'mean_fit_time': array([ 0.05867839,  0.10268728,  0.15536443,  0.19937317]),
     'mean_score_time': array([ 0.00600123,  0.01033529,  0.0146695 ,  0.02000403]),
     'mean_test_accuracy': array([ 0.9 ,  0.91,  0.89,  0.91]),
     'mean_test_roc_auc': array([ 0.91889706,  0.94610294,  0.94253676,  0.94308824]),
     'mean_train_accuracy': array([ 1.,  1.,  1.,  1.]),
     'mean_train_roc_auc': array([ 1.,  1.,  1.,  1.]),
     [...]
     }
    

    所以mean_test_[scoring] 就是您所追求的。请注意,您可以将 cv_results_ 作为 Pandas DataFrame 导入。这对可读性有很大帮助!

    【讨论】:

    • 我收到一个错误:评分值应该是可调用的、字符串或无。 ['accuracy', 'roc_auc'] 已通过
    • 我刚刚尝试了您的方法,使用了一本记分员字典。这也有效。您仍然可以在cv_results_ 中访问分数。
    • 当我使用分数字典时,我得到以下错误:ValueError:评分值应该是可调用的、字符串或无。 {'precision': make_scorer(precision_score), 'Recall': make_scorer(recall_score)} 已通过
    • 我很确定您实际上使用的是 scikit-learn 0.18。你能尝试在与上面代码相​​同的环境中运行import sklearn; print(sklearn.__version__)吗? 0.18 的文档与您的描述相匹配 scikit-learn.org/0.18/modules/generated/…
    猜你喜欢
    • 2019-02-11
    • 1970-01-01
    • 1970-01-01
    • 2018-06-02
    • 2018-07-04
    • 1970-01-01
    • 2022-12-17
    • 2021-06-24
    • 2021-02-22
    相关资源
    最近更新 更多