Примечание
Перейти в конец чтобы скачать полный пример кода или запустить этот пример в браузере через JupyterLite или Binder.
__sklearn_is_fitted__ как API для разработчиков#
The __sklearn_is_fitted__ метод — это соглашение, используемое в scikit-learn для проверки, был ли объект оценщика обучен или нет. Этот метод обычно реализуется в пользовательских классах оценщиков, построенных на основе базовых классов scikit-learn, таких как BaseEstimator или его подклассах.
Разработчикам следует использовать check_is_fitted
в начале всех методов, кроме fit. Если им нужно настроить или
ускорить проверку, они могут реализовать __sklearn_is_fitted__ метод, как
показано ниже.
В этом примере пользовательский оценщик демонстрирует использование
__sklearn_is_fitted__ метод и check_is_fitted функция полезности
как API для разработчиков. The __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
Связанные примеры