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

问题描述 投票:0回答:1

如果我想基于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

  • 这是如何运作的?我假设通过导入GridSearchCV我们以某种方式在幕后导入roc_auc_score?不幸的是,我似乎无法在source code中遵循这一点 - 我真的很感激解释。
  • 如果是这种情况,它是否也意味着通过导入GridSearchCV我们最终导入幕后所有可能的评分方法?
  • 为什么我不能自己“手动”使用roc_auc_score,如果我只导入GridSearchCV而不是roc_auc_score本身?幕后是否暗中“存在”?

我很欣赏这可能是一个关于python导入的更一般的问题,而不是特定于scikit-learn ...

python scikit-learn python-import
1个回答
3
投票

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

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

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

它在这里检查GridSearchCV构造期间提供的所有参数。对于'scoring' param,它称为_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正确地说的那样,那些导入是该模块的本地导入,而不是全局导入。

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

this python documentation page

© www.soinside.com 2019 - 2024. All rights reserved.