我正在使用GridSearchCV
来调整我的机器学习结果的超参数:
grid_search = GridSearchCV(estimator=xg_clf, scoring='f1', param_grid=param_grid, n_jobs=-1, cv=kfold)
然而,我的导师希望我使用Matthews系数进行评分,但遗憾的是,这不在可用选项之列:
>>> sorted(sklearn.metrics.SCORERS.keys())['accuracy', 'adjusted_mutual_info_score', 'adjusted_rand_score', 'average_precision', 'balanced_accuracy', 'completeness_score', 'explained_variance', 'f1', 'f1_macro', 'f1_micro', 'f1_samples', 'f1_weighted', 'fowlkes_mallows_score', 'homogeneity_score', 'jaccard', 'jaccard_macro', 'jaccard_micro', 'jaccard_samples', 'jaccard_weighted', 'max_error', 'mutual_info_score', 'neg_brier_score', 'neg_log_loss', 'neg_mean_absolute_error', 'neg_mean_absolute_percentage_error', 'neg_mean_gamma_deviance', 'neg_mean_poisson_deviance', 'neg_mean_squared_error', 'neg_mean_squared_log_error', 'neg_median_absolute_error', 'neg_root_mean_squared_error', 'normalized_mutual_info_score', 'precision', 'precision_macro', 'precision_micro', 'precision_samples', 'precision_weighted', 'r2', 'rand_score', 'recall', 'recall_macro', 'recall_micro', 'recall_samples', 'recall_weighted', 'roc_auc', 'roc_auc_ovo', 'roc_auc_ovo_weighted', 'roc_auc_ovr', 'roc_auc_ovr_weighted', 'top_k_accuracy', 'v_measure_score']
我已经阅读了文档中的关于cross_val_score和GridSearchCV的多指标评估的演示,但看起来这并不容易实现。
如何在GridSearchCV中使用Matthews系数进行评分?
回答:
关于模块sklearn.metrics._scorer中make_scorer函数的帮助:
make_scorer(score_func, *, greater_is_better=True, needs_proba=False, needs_threshold=False, **kwargs) 从性能指标或损失函数创建一个评分器。 这个工厂函数包装了评分函数,以便在 :class:`~sklearn.model_selection.GridSearchCV`和 :func:`~sklearn.model_selection.cross_val_score`中使用。 它接受一个评分函数,比如:func:`~sklearn.metrics.accuracy_score`, :func:`~sklearn.metrics.mean_squared_error`,
所以解决方案是简单地使用make_scorer
并调用sklearn.metrics
中的相应函数:
grid_search = GridSearchCV(estimator=xg_clf, scoring=make_scorer(matthews_corrcoef), param_grid=param_grid, n_jobs=-1, cv=kfold)