Search code examples
pythonxgboostisinstance

How to differentiate model types from xgboost XGBRFClassifier and XGBClassifier


I'm building a module that supports both XGBClassifier and XGBRFClassifier from xgboost. I want to differentiate them in my module but I noticed that:


from xgboost import XGBRFClassifier, XGBClassifier

xgbrf_model = XGBRFClassifier()
isinstance(xgbrf_model, XGBClassifier) # True

This should obviously not be true. I want to stick to isinstance and not try:

type(xgbrf_model) == XGBClassifier # False

Solution

  • This should obviously not be true ..isinstance(XGBRFClassifier(), XGBClassifier)

    As of XGBoost version v1.7.3, the XGBRFClassifier class is a direct subclass of the XGBClassifier class: https://github.com/dmlc/xgboost/blob/v1.7.3/python-package/xgboost/sklearn.py#L1627

    Therefore, this isinstance check correctly evaluates to True.

    Your best bet is to perform checks from more specific classes to less specific classes. That is, check for XGBRFClassifier first, and if that evaluates to False, only then check for XGBClassifier.