check_is_fitted#
- sklearn.utils.validation.check_is_fitted(estimator,attributes=None,*,msg=None,all_or_any=<built-infunctionall>)[source]#
Perform is_fitted validation for estimator.
Checks if the estimator is fitted by verifying the presence offitted attributes (ending with a trailing underscore) and otherwiseraises a
NotFittedErrorwith the given message.If an estimator does not set any attributes with a trailing underscore, itcan define a
__sklearn_is_fitted__method returning a boolean tospecify if the estimator is fitted or not. See__sklearn_is_fitted__ as Developer APIfor an example on how to use the API.If no
attributesare passed, this function will pass if an estimator is stateless.An estimator can indicate it’s stateless by setting therequires_fittag. SeeEstimator Tags for more information. Note that therequires_fittagis ignored ifattributesare passed.- Parameters:
- estimatorestimator instance
Estimator instance for which the check is performed.
- attributesstr, list or tuple of str, default=None
Attribute name(s) given as string or a list/tuple of stringsEg.:
["coef_","estimator_",...],"coef_"If
None,estimatoris considered fitted if there exist anattribute that ends with a underscore and does not start with doubleunderscore.- msgstr, default=None
The default error message is, “This %(name)s instance is not fittedyet. Call ‘fit’ with appropriate arguments before using thisestimator.”
For custom messages if “%(name)s” is present in the message string,it is substituted for the estimator name.
Eg. : “Estimator, %(name)s, must be fitted before sparsifying”.
- all_or_anycallable, {all, any}, default=all
Specify whether all or any of the given attributes must exist.
- Raises:
- TypeError
If the estimator is a class or not an estimator instance
- NotFittedError
If the attributes are not found.
Examples
>>>fromsklearn.linear_modelimportLogisticRegression>>>fromsklearn.utils.validationimportcheck_is_fitted>>>fromsklearn.exceptionsimportNotFittedError>>>lr=LogisticRegression()>>>try:...check_is_fitted(lr)...exceptNotFittedErrorasexc:...print(f"Model is not fitted yet.")Model is not fitted yet.>>>lr.fit([[1,2],[1,3]],[1,0])LogisticRegression()>>>check_is_fitted(lr)
