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. <
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('__')] )