1

Check if RandomForestClassifier object have been fitted to data. I can catch NotFittedError from sklearn.exceptions but is there better way? And in general we can't then is relaying on error catching good practice in Python ?

Matt Hall
  • 7,614
  • 1
  • 23
  • 36
Qbik
  • 5,885
  • 14
  • 62
  • 93
  • 1
    you can use check_is_fitted method: https://scikit-learn.org/stable/modules/generated/sklearn.utils.validation.check_is_fitted.html – Rodrigo A Jun 15 '22 at 19:42

1 Answers1

2

Probably the best way to check sklearn estimators is the check_is_fitted utility function, although that too will raise the NotFittedError on failure. Docs pages. That function mostly looks for "fitted attributes" that end in an underscore, so if you want to check specifically for RandomForestClassifier, maybe you should just check for hasattr(model, "estimators_")?

As to whether try-except'ing is pythonic, see e.g. Using 'try' vs. 'if' in Python and Better to 'try' something and catch the exception or test if it's possible first to avoid an exception?.

Ben Reiniger
  • 10,517
  • 3
  • 16
  • 29