How to check if the model object is Xgboost or not in python

Viewed 594

I am trying to evaluate if the model object is xgboost or not, If it is not then raise an error

import pandas as pd
import xgboost as xgb
from sklearn.datasets import load_boston
from sklearn.model_selection import train_test_split
from sklearn.metrics import mean_squared_error

boston = load_boston()
X = pd.DataFrame(boston.data, columns=boston.feature_names)
y = pd.Series(boston.target)
regressor = xgb.XGBRegressor(
    n_estimators=100,
    reg_lambda=1,
    gamma=0,
    max_depth=3
)

regressor.fit(X, y)


type(regressor)


I tried using below two condition but getting failed 1st approach

if type(regressor) == 'xgboost.sklearn.XGBRegressor':
    print("Xgboost Model")


2nd approach

if not isinstance(regressor,XGBRegressor):
    raise TypeError("wrong input ")

I need to evaluate model object for xgboost irrespective of whether it is classifier or regressor , it should check the condition for both

1 Answers

You may consider (preferred):

if isinstance(regressor, xgb.sklearn.XGBRegressor) or isinstance(regressor, xgb.sklearn.XGBClassifier):
    print("Xgboost Model")
else:
    raise TypeError("wrong input")

or, given your comment:

if regressor.__class__.__name__ in ['XGBRegressor', 'XGBClassifier']:
    print("Xgboost Model")
else:
    raise TypeError("wrong input")
Related