'What's the best way to test whether an sklearn model has been fitted?

What's the most elegant way to check whether an sklearn model has been fitted? i.e. whether its fit() function has been called after it was instantiated, or not.



Solution 1:[1]

I do this for classifiers:

def check_fitted(clf): 
    return hasattr(clf, "classes_")

Solution 2:[2]

This is sort of a greedy approach, but it should be fine for most if not all models. The only time this might not work is for models that set an attribute ending in an underscore prior to being fit, which I'm pretty sure would violate scikit-learn convention so this should be fine.

import inspect

def is_fitted(model):
        """Checks if model object has any attributes ending with an underscore"""
        return 0 < len( [k for k,v in inspect.getmembers(model) if k.endswith('_') and not k.startswith('__')] )

Solution 3:[3]

Cribbing directly from the scikit-learn source code for the check_is_fitted function (similar logic to @david-marx, but a little simpler):

def is_fitted(model):
    '''
    Checks if a scikit-learn estimator/transformer has already been fit.
    
    
    Parameters
    ----------
    model: scikit-learn estimator (e.g. RandomForestClassifier) 
        or transformer (e.g. MinMaxScaler) object
        
    
    Returns
    -------
    Boolean that indicates if ``model`` has already been fit (True) or not (False).
    '''
    
    attrs = [v for v in vars(model)
             if v.endswith("_") and not v.startswith("__")]
    
    return len(attrs) != 0

Solution 4:[4]

this function to check if a scikit-learn model is fitted by comparing it to a new instance of the model.

def is_fitted(model):
    return not len(dir(model)) == len(dir(type(model)()))

model = OneHotEncoder()
print(is_fitted(model)) #False
model.fit_transform(data)
print(is_fitted(model)) #True


 

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 O.rka
Solution 2 David Marx
Solution 3 emigre459
Solution 4 Ghassen Sultana