__sklearn_is_fitted__ 作为开发者 API#

__sklearn_is_fitted__ 方法是 scikit-learn 中用于检查估计器对象是否已拟合的约定。此方法通常在基于 scikit-learn 的基类(如 BaseEstimator 或其子类)构建的自定义估计器类中实现。

开发者应在除 fit 之外的所有方法开头使用 check_is_fitted。如果需要自定义或加速检查,他们可以实现 __sklearn_is_fitted__ 方法,如下所示。

在此示例中,自定义估计器展示了 __sklearn_is_fitted__ 方法和 check_is_fitted 实用函数作为开发者 API 的用法。 __sklearn_is_fitted__ 方法通过验证 _is_fitted 属性的存在来检查拟合状态。

实现简单分类器的示例自定义估计器#

此代码片段定义了一个名为 CustomEstimator 的自定义估计器类,该类扩展了 scikit-learn 中的 BaseEstimatorClassifierMixin 类,并展示了 __sklearn_is_fitted__ 方法和 check_is_fitted 实用函数的用法。

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

from sklearn.base import BaseEstimator, ClassifierMixin
from sklearn.utils.validation import check_is_fitted


class CustomEstimator(BaseEstimator, ClassifierMixin):
    def __init__(self, parameter=1):
        self.parameter = parameter

    def fit(self, X, y):
        """
        Fit the estimator to the training data.
        """
        self.classes_ = sorted(set(y))
        # Custom attribute to track if the estimator is fitted
        self._is_fitted = True
        return self

    def predict(self, X):
        """
        Perform Predictions

        If the estimator is not fitted, then raise NotFittedError
        """
        check_is_fitted(self)
        # Perform prediction logic
        predictions = [self.classes_[0]] * len(X)
        return predictions

    def score(self, X, y):
        """
        Calculate Score

        If the estimator is not fitted, then raise NotFittedError
        """
        check_is_fitted(self)
        # Perform scoring logic
        return 0.5

    def __sklearn_is_fitted__(self):
        """
        Check fitted status and return a Boolean value.
        """
        return hasattr(self, "_is_fitted") and self._is_fitted

相关示例

归纳聚类

归纳聚类

带自定义核的 SVM

带自定义核的 SVM

元数据路由

元数据路由

scikit-learn 1.6 发布亮点

scikit-learn 1.6 发布亮点

由 Sphinx-Gallery 生成的图库