check_is_fitted#
- pybear.base.check_is_fitted(estimator, attributes=None, *, msg=None, all_or_any=<built-in function all>)#
Perform _is_fitted validation on an estimator/transformer.
Checks if the estimator/transformer is fitted by looking for 3 things, in the presented order, via the pybear
is_fitted()function.- The estimator/transformer is fitted if it:
- has a __pybear_is_fitted__ dunder method and it returns
boolean True
- has any or all attributes given by attributes, if it is
passed; if not passed, this step is skipped
- has an attribute that ends with an underscore and does not
start with double underscore.
If none of these things are true, the estimator/transformer is not fitted and raises a
pybear.exceptions.NotFittedErrorwith the message given by msg or the default message if msg is not passed.- Parameters:
- estimatorobject
Estimator/tranformer instance for which the validation is performed.
- attributesstr | Sequence[str] | None, default=None
Attribute name(s) given as string or a list/tuple of strings Eg.: ‘coef_’ or [’coef_’, ‘estimator_’, …].
- msgstr, default=None
The default error message is, f”This {name} instance is not fitted yet. Call fit with appropriate arguments before using this estimator.”
For custom messages, if {name} is present in the message string, it is substituted for the estimator name.
E.g.: f”Estimator, {name}, must be fitted before sparsifying”.
- all_or_anycallable, {all, any}, default=all
Specifies whether all or any of the given attributes must exist.
- Raises:
- ValueError
If the passed estimator/transformer is invalid or is valid but is not instantiated.
If the value passed to attributes is invalid.
If the value passed to msg is not a string or None.
If the function passed to all_or_any is not one of the built-in Python all() or any() functions.
- NotFittedError
If the estimator/transformer fails all 3 checks for being fit.
Examples
>>> import numpy as np >>> from pybear.preprocessing import InterceptManager as IM >>> from pybear.base import check_is_fitted >>> from pybear.base.exceptions import NotFittedError >>> trf = IM() >>> try: ... check_is_fitted(trf) ... except NotFittedError as exc: ... print(f"Model is not fitted yet.") Model is not fitted yet. >>> X = np.random.randint(0, 4, (2, 2)) >>> y = np.random.randint(0, 2, (2,)) >>> trf.fit(X, y) InterceptManager() >>> print(check_is_fitted(trf)) None