Spec-Zone.ru › scikit-learn

Примечание

Перейти в конец, чтобы скачать полный код примера или запустить этот пример в браузере через JupyterLite или Binder.

__sklearn_is_fitted__ как API для разработчиков

Метод __sklearn_is_fitted__ — это соглашение, используемое в scikit-learn для проверки того, был ли обучен объект оценщика. Этот метод обычно реализуется в пользовательских классах оценщиков, построенных на основе базовых классов scikit-learn, таких как BaseEstimator, или их подклассов.

Разработчикам следует вызывать check_is_fitted в начале всех методов, кроме fit. Если требуется настроить проверку или ускорить её, можно реализовать метод __sklearn_is_fitted__, как показано ниже.

В этом примере пользовательский оценщик демонстрирует использование метода __sklearn_is_fitted__ и служебной функции check_is_fitted в качестве API для разработчиков. Метод __sklearn_is_fitted__ проверяет, был ли оценщик обучен, проверяя наличие атрибута _is_fitted.

Пример пользовательского оценщика, реализующего простой классификатор

Этот фрагмент кода определяет пользовательский класс оценщика с именем CustomEstimator, который наследуется от классов BaseEstimator и ClassifierMixin из scikit-learn и демонстрирует использование метода __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
Launch binder
Launch JupyterLite

Download Jupyter notebook: sklearn_is_fitted.ipynb

Download Python source code: sklearn_is_fitted.py

Download zipped: sklearn_is_fitted.zip

Похожие примеры

Индуктивная кластеризация

SVM с пользовательским ядром

Разработка оценщиков, совместимых с маршрутизацией метаданных

Основные нововведения scikit-learn 1.6

© 2007–2026 The scikit-learn developers
Licensed under the 3-clause BSD License.
https://scikit-learn.org/1.9/auto_examples/developing_estimators/sklearn_is_fitted.html

Spec-Zone.ru

Настройки Оффлайн Что нового Помощь О нас
Spec-Zone .ru
спецификации, руководства, описания, API