TunedThresholdClassifierCV#

class sklearn.model_selection.TunedThresholdClassifierCV(estimator, *, scoring='balanced_accuracy', response_method='auto', thresholds=100, cv=None, refit=True, n_jobs=None, random_state=None, store_cv_results=False)[source]#

使用交叉验证对决策阈值进行后调整的分类器。

此估计器对用于将后验概率估计(即 predict_proba 的输出)或决策分数(即 decision_function 的输出)转换为类别标签的决策阈值(截止点)进行后期调整。调整通过优化二元度量完成,可能会受到另一个度量的约束。

用户指南中阅读更多内容。

1.5 版本新增。

参数:
estimatorestimator instance

分类器,无论是否已拟合,我们都希望优化在 predict 期间使用的决策阈值。

scoringstr 或 callable,默认为“balanced_accuracy”

要优化的目标度量。可以是以下之一:

  • str:与二元分类评分函数关联的字符串,请参阅字符串名称评分器以获取选项。

  • callable: 带有签名 scorer(estimator, X, y) 的可调用评分器对象(例如函数)。有关详细信息,请参阅 Callable scorers

response_method{“auto”,“decision_function”,“predict_proba”},默认为“auto”

分类器 estimator 的方法,对应于我们希望找到阈值的决策函数。它可以是

  • 如果 "auto",它将尝试按顺序为每个分类器调用 "predict_proba""decision_function"

  • 否则,为 "predict_proba""decision_function" 之一。如果分类器未实现该方法,则会引发错误。

thresholdsint 或 array-like,默认为 100

当对分类器 method 的输出进行离散化时要使用的决策阈值数量。传入 array-like 以手动指定要使用的阈值。

cvint,float,交叉验证生成器,可迭代对象或“prefit”,默认为 None

确定用于训练分类器的交叉验证拆分策略。cv 的可能输入为

  • None,使用默认的 5 折分层 K 折交叉验证;

  • 一个整数,指定分层 K 折中的折数;

  • 一个浮点数,指定单个洗牌拆分。浮点数应在 (0, 1) 之间,表示验证集的大小;

  • 用作交叉验证生成器的对象;

  • 生成训练集、测试集拆分的可迭代对象;

  • "prefit",绕过交叉验证。

有关此处可使用的各种交叉验证策略,请参阅 用户指南

警告

使用 cv="prefit" 并传入相同的数据集用于拟合 estimator 和调整截止点可能会导致不期望的过拟合。您可以参考关于模型再拟合和交叉验证的考虑以获取示例。

此选项仅应用于拟合 estimator 的数据集与用于调整截止点(通过调用 TunedThresholdClassifierCV.fit)的数据集不同时。

refitbool,默认为 True

是否在找到决策阈值后,在整个训练集上重新拟合分类器。请注意,在具有多个拆分的交叉验证中强制 refit=False 将引发错误。同样,refit=Truecv="prefit" 结合使用也将引发错误。

n_jobsint, default=None

并行运行的作业数。当 cv 代表交叉验证策略时,每个数据拆分上的拟合和评分是并行完成的。None 表示 1,除非在 joblib.parallel_backend 上下文中。-1 表示使用所有处理器。有关更多详细信息,请参阅术语表

random_stateint, RandomState instance or None, default=None

cv 是浮点数时,控制交叉验证的随机性。请参阅术语表

store_cv_resultsbool, default=False

是否存储在交叉验证过程中计算的所有分数和阈值。

属性:
estimator_估计器实例

预测时使用的已拟合分类器。

best_threshold_float

新的决策阈值。

best_score_float 或 None

目标度量的最佳分数,在 best_threshold_ 处评估。

cv_results_dict 或 None

包含在交叉验证过程中计算的分数和阈值的字典。仅当 store_cv_results=True 时存在。键为 "thresholds""scores"

classes_形状为 (n_classes,) 的 ndarray

类别标签。

n_features_in_int

fit 期间看到的特征数。仅当底层估计器在拟合时暴露此属性时才定义。

feature_names_in_shape 为 (n_features_in_,) 的 ndarray

拟合 期间看到的特征名称。仅当底层估计器在拟合时公开此类属性时才定义。

另请参阅

sklearn.model_selection.FixedThresholdClassifier

使用恒定阈值的分类器。

sklearn.calibration.CalibratedClassifierCV

校准概率的估计器。

示例

>>> from sklearn.datasets import make_classification
>>> from sklearn.ensemble import RandomForestClassifier
>>> from sklearn.metrics import classification_report
>>> from sklearn.model_selection import TunedThresholdClassifierCV, train_test_split
>>> X, y = make_classification(
...     n_samples=1_000, weights=[0.9, 0.1], class_sep=0.8, random_state=42
... )
>>> X_train, X_test, y_train, y_test = train_test_split(
...     X, y, stratify=y, random_state=42
... )
>>> classifier = RandomForestClassifier(random_state=0).fit(X_train, y_train)
>>> print(classification_report(y_test, classifier.predict(X_test)))
              precision    recall  f1-score   support

           0       0.94      0.99      0.96       224
           1       0.80      0.46      0.59        26

    accuracy                           0.93       250
   macro avg       0.87      0.72      0.77       250
weighted avg       0.93      0.93      0.92       250

>>> classifier_tuned = TunedThresholdClassifierCV(
...     classifier, scoring="balanced_accuracy"
... ).fit(X_train, y_train)
>>> print(
...     f"Cut-off point found at {classifier_tuned.best_threshold_:.3f}"
... )
Cut-off point found at 0.342
>>> print(classification_report(y_test, classifier_tuned.predict(X_test)))
              precision    recall  f1-score   support

           0       0.96      0.95      0.96       224
           1       0.61      0.65      0.63        26

    accuracy                           0.92       250
   macro avg       0.78      0.80      0.79       250
weighted avg       0.92      0.92      0.92       250
decision_function(X)[source]#

使用已拟合的估计器对 X 中的样本进行决策函数计算。

参数:
Xshape 为 (n_samples, n_features) 的 {array-like, sparse matrix}

训练向量,其中 n_samples 是样本数量,n_features 是特征数量。

返回:
decisions形状为 (n_samples,) 的 ndarray

已拟合的估计器计算的决策函数。

fit(X, y, **params)[source]#

拟合分类器。

参数:
Xshape 为 (n_samples, n_features) 的 {array-like, sparse matrix}

训练数据。

yarray-like of shape (n_samples,)

目标值。

**paramsdict

要传递给底层分类器的 fit 方法的参数。

返回:
selfobject

Returns an instance of self.

get_metadata_routing()[source]#

获取此对象的元数据路由。

请查阅 用户指南,了解路由机制如何工作。

返回:
routingMetadataRouter

封装路由信息的 MetadataRouter

get_params(deep=True)[source]#

获取此估计器的参数。

参数:
deepbool, default=True

如果为 True,将返回此估计器以及包含的子对象(如果它们是估计器)的参数。

返回:
paramsdict

参数名称映射到其值。

predict(X)[source]#

预测新样本的目标。

参数:
Xshape 为 (n_samples, n_features) 的 {array-like, sparse matrix}

样本,如 estimator.predict 所接受。

返回:
class_labels形状为 (n_samples,) 的 ndarray

预测的类别。

predict_log_proba(X)[source]#

使用已拟合的估计器预测 X 的对数类别概率。

参数:
Xshape 为 (n_samples, n_features) 的 {array-like, sparse matrix}

训练向量,其中 n_samples 是样本数量,n_features 是特征数量。

返回:
log_probabilities形状为 (n_samples, n_classes) 的 ndarray

输入样本的对数类别概率。

predict_proba(X)[source]#

使用已拟合的估计器预测 X 的类别概率。

参数:
Xshape 为 (n_samples, n_features) 的 {array-like, sparse matrix}

训练向量,其中 n_samples 是样本数量,n_features 是特征数量。

返回:
probabilities形状为 (n_samples, n_classes) 的 ndarray

输入样本的类别概率。

score(X, y, sample_weight=None)[source]#

返回在提供的数据和标签上的 准确率 (accuracy)

在多标签分类中,这是子集准确率 (subset accuracy),这是一个严格的指标,因为它要求每个样本的每个标签集都被正确预测。

参数:
Xshape 为 (n_samples, n_features) 的 array-like

测试样本。

yshape 为 (n_samples,) 或 (n_samples, n_outputs) 的 array-like

X 的真实标签。

sample_weightshape 为 (n_samples,) 的 array-like, default=None

样本权重。

返回:
scorefloat

self.predict(X) 相对于 y 的平均准确率。

set_params(**params)[source]#

设置此估计器的参数。

此方法适用于简单的估计器以及嵌套对象(如 Pipeline)。后者具有 <component>__<parameter> 形式的参数,以便可以更新嵌套对象的每个组件。

参数:
**paramsdict

估计器参数。

返回:
selfestimator instance

估计器实例。

set_score_request(*, sample_weight: bool | None | str = '$UNCHANGED$') TunedThresholdClassifierCV[source]#

配置是否应请求元数据以传递给 score 方法。

请注意,此方法仅在以下情况下相关:此估计器用作 元估计器 中的子估计器,并且通过 enable_metadata_routing=True 启用了元数据路由(请参阅 sklearn.set_config)。请查看 用户指南 以了解路由机制的工作原理。

每个参数的选项如下:

  • True:请求元数据,如果提供则传递给 score。如果未提供元数据,则忽略该请求。

  • False:不请求元数据,元估计器不会将其传递给 score

  • None:不请求元数据,如果用户提供元数据,元估计器将引发错误。

  • str:应将元数据以给定别名而不是原始名称传递给元估计器。

默认值 (sklearn.utils.metadata_routing.UNCHANGED) 保留现有请求。这允许您更改某些参数的请求而不更改其他参数。

在版本 1.3 中新增。

参数:
sample_weightstr, True, False, or None, default=sklearn.utils.metadata_routing.UNCHANGED

score 方法中 sample_weight 参数的元数据路由。

返回:
selfobject

更新后的对象。