Hyperopt: How to Know Which Variables Were Selected for the Best Model When I Load Saved Model for Sklearn?
I Trained a Sklearn Gradient Boosting Classifier and Optimized with Hyperopt. Hyperopt Select Only 20 Variables, out of 769. However, When I Try to Load...
I trained a sklearn Gradient Boosting classifier and optimized with Hyperopt. Hyperopt select only 20 variables, out of 769. However, when I try to load weights for sklearn, in a blind test, it is unclear which variables were selected. Here's the code:
from xgboost import XGBClassifier
from hyperopt import fmin, tpe, hp, STATUS_OK, Trials
from sklearn.model_selection import cross_val_score
from sklearn.metrics import accuracy_score,precision_score,confusion_matrix,f1_score,recall_score
# multi:mlogloss // binary:logistic
def accuracy(params):
clf = XGBClassifier(**params,learning_rate=0.7,objective='binary:logistic',
booster='gbtree', n_jobs=64,eval_metric="error",eval_set=eval_set, verbose=True)
clf.fit(X_train,y_train) #eval_set=eval_set,
return clf.score(X_test, y_test)
eval_set=eval_set = [(X_test, y_test)]
parameters = {
'n_estimators': hp.choice('n_estimators', range(20,40)),
'max_depth': hp.choice('max_depth', range(4,100)),
'gamma': hp.choice('gamma', range(0,10)),
"min_child_weight":hp.choice("min_child_weight",range(0,1)),
"num_features":hp.choice("num_features",range(10,X_train.shape[1])),
"max_delta_step":hp.choice("max_delta_step",range(0,10))}
best = 0
def f(params):
global best
acc = accuracy(params)
if acc > best:
best = acc
print ('Improving:', best, params)
return {'loss': -acc, 'status': STATUS_OK}
trials = Trials()
best = fmin(f, parameters, algo=tpe.suggest, max_evals=80, trials=trials)
print ('best:',best)
clf = XGBClassifier(gamma=best['gamma'],max_delta_step=best['max_delta_step'],max_depth=best['max_depth'],
learning_rate=0.1, n_estimators=best['n_estimators'], objective='binary:logistic', min_child_weight=best['min_child_weight'],
num_features=best['num_features'],
booster='gbtree', n_jobs=64,eval_metric="error",eval_set=eval_set, verbose=True)
clf.fit(X_train,y_train)
clf.score(X_test, y_test)
import joblib
filename = '/home/rubens.../modelos/Argumenta_Multi.sav'
joblib.dump(clf, filename)
loaded_model = joblib.load(filename)
result = loaded_model.predict(X_new)
How can I know which 20 variables hyperopt selected ? I'm afraid to use chi squared (select K best = 20) with saved hyperopt weights because hyperopt may not be using chi squared as variable selection.
At result=loaded_model... I get the following error:
ValueError: X has 769 features, but DecisionTreeClassifier is expecting 20 features as input.
I also don't know if Hyperopt follows sklearn's feature importance, previously to saving Hyperopt best model:
model.feature_importances_