File: sklearn_is_fitted.py

package info (click to toggle)
scikit-learn 1.7.2%2Bdfsg-3
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 25,752 kB
  • sloc: python: 219,120; cpp: 5,790; ansic: 846; makefile: 191; javascript: 110
file content (75 lines) | stat: -rw-r--r-- 2,607 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
"""
========================================
`__sklearn_is_fitted__` as Developer API
========================================

The `__sklearn_is_fitted__` method is a convention used in scikit-learn for
checking whether an estimator object has been fitted or not. This method is
typically implemented in custom estimator classes that are built on top of
scikit-learn's base classes like `BaseEstimator` or its subclasses.

Developers should use :func:`~sklearn.utils.validation.check_is_fitted`
at the beginning of all methods except `fit`. If they need to customize or
speed-up the check, they can implement the `__sklearn_is_fitted__` method as
shown below.

In this example the custom estimator showcases the usage of the
`__sklearn_is_fitted__` method and the `check_is_fitted` utility function
as developer APIs. The `__sklearn_is_fitted__` method checks fitted status
by verifying the presence of the `_is_fitted` attribute.
"""

# %%
# An example custom estimator implementing a simple classifier
# ------------------------------------------------------------
# This code snippet defines a custom estimator class called `CustomEstimator`
# that extends both the `BaseEstimator` and `ClassifierMixin` classes from
# scikit-learn and showcases the usage of the `__sklearn_is_fitted__` method
# and the `check_is_fitted` utility function.

# 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