为什么 scikit-learn 中的参数搜索不需要记分器导入?

Why is scorer import unnecessary for parameter search in scikit-learn?

如果我想根据 ROC 曲线下的面积优化逻辑回归模型的正则化参数(例如),我可以使用 GridSearchCV 来获得合适的参数范围并设置 scoring='roc_auc'.

这可以使用 from sklearn.model_selection import GridSearchCV 完成,不需要 包含 from sklearn.metrics import roc_auc_score

但是,如果我想为特定的拟合数据集手动计算 ROC 曲线下的面积,那么我需要包括 from sklearn.metrics import roc_auc_score

我明白这可能是一个关于 python 导入的更普遍的问题,而不是特定于 scikit-learn...

GridSearchCV 扩展了 BaseSearchCV class。这意味着它将使用 fit() function defined in BaseSearchCV.

所以现在你可以在 source code here 中看到:

    ...
    ...
    scorers, self.multimetric_ = _check_multimetric_scoring(
    self.estimator, scoring=self.scoring)
    ...
    ...

它检查在此处构建 GridSearchCV 期间提供的所有参数。 对于 'scoring' 参数,它调用方法 _check_multimetric_scoring()。现在在此文件之上,您将看到许多导入。

方法_check_multimetric_scoring指向scorer.py file:

类似地跟踪方法调用,我们 will reach here:

SCORERS = dict(explained_variance=explained_variance_scorer,
               r2=r2_scorer,
               neg_median_absolute_error=neg_median_absolute_error_scorer,
               neg_mean_absolute_error=neg_mean_absolute_error_scorer,
               neg_mean_squared_error=neg_mean_squared_error_scorer,
               neg_mean_squared_log_error=neg_mean_squared_log_error_scorer,
               accuracy=accuracy_scorer, roc_auc=roc_auc_scorer,
               ...
               ...
 ...
 ...

查看roc_auc,我们将reach here:

roc_auc_scorer = make_scorer(roc_auc_score, greater_is_better=True,
needs_threshold=True)

现在看这里的参数,roc_auc_score发送给make_scorer。那么它是从哪里进口的呢?查看此文件的顶部,您将看到:

from . import (r2_score, median_absolute_error, mean_absolute_error,
               mean_squared_error, mean_squared_log_error, accuracy_score,
               f1_score, roc_auc_score, average_precision_score,
               precision_score, recall_score, log_loss,
               balanced_accuracy_score, explained_variance_score,
               brier_score_loss)

所以从这里开始,实际的评分对象返回到 GridSearchCV。

现在,该库正在使用相对和绝对导入,正如@Denziloe 正确所说的那样,这些导入是该模块的本地导入,而不是全局导入。

有关导入范围和命名空间的更多信息,请参阅这些答案:

  • Python "import" scope
  • Python: Namespaces with Module Imports

this python documentation page