FrozenEstimator 使用示例#

此示例展示了 FrozenEstimator 的一些用例。

FrozenEstimator 是一个实用类,允许冻结一个已拟合的估计器。这在例如我们想将一个已拟合的估计器传递给一个元估计器(如 FixedThresholdClassifier)而不想让元估计器重新拟合该估计器时非常有用。

# Authors: The scikit-learn developers
# SPDX-License-Identifier: BSD-3-Clause

为预拟合分类器设置决策阈值#

scikit-learn 中已拟合的分类器使用任意决策阈值来决定给定样本属于哪个类别。决策阈值可以是 decision_function 返回值的 0.0,也可以是 predict_proba 返回概率的 0.5

然而,人们可能想要设置一个自定义决策阈值。我们可以通过使用 FixedThresholdClassifier 并使用 FrozenEstimator 包装分类器来做到这一点。

from sklearn.datasets import make_classification
from sklearn.frozen import FrozenEstimator
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import FixedThresholdClassifier, train_test_split

X, y = make_classification(n_samples=1000, random_state=0)
X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=0)
classifier = LogisticRegression().fit(X_train, y_train)

print(
    "Probability estimates for three data points:\n"
    f"{classifier.predict_proba(X_test[-3:]).round(3)}"
)
print(
    "Predicted class for the same three data points:\n"
    f"{classifier.predict(X_test[-3:])}"
)
Probability estimates for three data points:
[[0.18 0.82]
 [0.29 0.71]
 [0.   1.  ]]
Predicted class for the same three data points:
[1 1 1]

现在想象一下,您想对概率估计设置不同的决策阈值。我们可以通过使用 FrozenEstimator 包装分类器并将其传递给 FixedThresholdClassifier 来做到这一点。

threshold_classifier = FixedThresholdClassifier(
    estimator=FrozenEstimator(classifier), threshold=0.9
)

请注意,在上述代码中,在 FixedThresholdClassifier 上调用 fit 不会重新拟合底层分类器。

现在,让我们看看预测如何随着概率阈值的变化而改变。

print(
    "Probability estimates for three data points with FixedThresholdClassifier:\n"
    f"{threshold_classifier.predict_proba(X_test[-3:]).round(3)}"
)
print(
    "Predicted class for the same three data points with FixedThresholdClassifier:\n"
    f"{threshold_classifier.predict(X_test[-3:])}"
)
Probability estimates for three data points with FixedThresholdClassifier:
[[0.18 0.82]
 [0.29 0.71]
 [0.   1.  ]]
Predicted class for the same three data points with FixedThresholdClassifier:
[0 0 1]

我们看到概率估计保持不变,但由于使用了不同的决策阈值,预测的类别也不同。

请参阅 成本敏感学习的决策阈值后调优,了解成本敏感学习和决策阈值调优。

预拟合分类器的校准#

您可以使用 FrozenEstimator,通过 CalibratedClassifierCV 来校准预拟合的分类器。

from sklearn.calibration import CalibratedClassifierCV
from sklearn.metrics import brier_score_loss

calibrated_classifier = CalibratedClassifierCV(
    estimator=FrozenEstimator(classifier)
).fit(X_train, y_train)

prob_pos_clf = classifier.predict_proba(X_test)[:, 1]
clf_score = brier_score_loss(y_test, prob_pos_clf)
print(f"No calibration: {clf_score:.3f}")

prob_pos_calibrated = calibrated_classifier.predict_proba(X_test)[:, 1]
calibrated_score = brier_score_loss(y_test, prob_pos_calibrated)
print(f"With calibration: {calibrated_score:.3f}")
No calibration: 0.033
With calibration: 0.032

脚本总运行时间: (0 分钟 0.023 秒)

相关示例

分类器的概率校准

分类器的概率校准

scikit-learn 1.5 的发布亮点

scikit-learn 1.5 的发布亮点

概率校准曲线

概率校准曲线

决策函数截止点的后验调优

决策函数截止点的后验调优

由 Sphinx-Gallery 生成的图库