2

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

Dexter1611
  • 492
  • 1
  • 4
  • 15

1 Answers1

1

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")
Sergey Bushmanov
  • 23,310
  • 7
  • 53
  • 72
  • is there any other way because xgb would depend on what others has used alias for importing , I need more of a general solution which could be used by everyone – Dexter1611 Oct 16 '20 at 20:16
  • Given your comments I would do the same `X.__class__.__name__ == 'DataFrame'`. But you may wish to check https://stackoverflow.com/questions/14808945/check-if-variable-is-dataframe – Sergey Bushmanov Oct 16 '20 at 20:47