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

后端 未结 4 996
误落风尘
误落风尘 2021-02-07 02:30

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. <

4条回答
  •  傲寒
    傲寒 (楼主)
    2021-02-07 03:15

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

提交回复
热议问题