I am using the below code which is consistent with what I have been reading on tutorials such as https://medium.com/analytics-vidhya/hyperparameters-optimization-for-lightgbm-catboost-and-xgboost-regressors-using-bayesian-6e7c495947a9. However, the final step that is supposed to print a dictionary of thee best parameters for my model causes this error
''' NameError Traceback (most recent call last) in 40 41 bayesion_opt_lgbm(X, y, init_iter=5, n_iters=10, random_state=77, seed = 101, num_iterations = 200) ---> 42 print(optimizer.max)
NameError: name 'optimizer' is not defined ''' This is the full code I am using.
from bayes_opt import BayesianOptimization #From the library bayesian-optimization
import warnings
warnings.filterwarnings('ignore')
def bayesion_opt_lgbm(X, y, init_iter=3, n_iters=7, random_state=11, seed = 101, num_iterations = 100):
dtrain = lgb.Dataset(data=X, label=y)
def lgb_r2_score(preds, dtrain): #in case want to use R2 as metric
labels = dtrain.get_label()
return 'r2', r2_score(labels, preds), True
# Objective Function
def hyp_lgbm(num_leaves, feature_fraction, bagging_fraction, max_depth, min_split_gain, min_child_weight):
params = {'application':'regression','num_iterations': num_iterations,
'learning_rate':0.05, 'early_stopping_round':50,
'metric':'rmse'} # Default parameters
params["num_leaves"] = int(round(num_leaves))
params['feature_fraction'] = max(min(feature_fraction, 1), 0)
params['bagging_fraction'] = max(min(bagging_fraction, 1), 0)
params['max_depth'] = int(round(max_depth))
params['min_split_gain'] = min_split_gain
params['min_child_weight'] = min_child_weight
cv_results = lgb.cv(params, dtrain, nfold=5, seed=seed,categorical_feature=[], stratified=False,
verbose_eval =None)
# print(cv_results)
return np.max(cv_results['rmse-mean'])
# Domain space-- Range of hyperparameters
pds = {'num_leaves': (80, 100),
'feature_fraction': (0.1, 0.9),
'bagging_fraction': (0.8, 1),
'max_depth': (17, 25),
'min_split_gain': (0.001, 0.1),
'min_child_weight': (10, 25)
}
# Surrogate model
optimizer = BayesianOptimization(hyp_lgbm, pds, random_state=random_state)
# Optimize
optimizer.maximize(init_points=init_iter, n_iter=n_iters)
bayesion_opt_lgbm(X, y, init_iter=5, n_iters=10, random_state=77, seed = 101, num_iterations = 200)
optimizer.max['params']
Why is the name 'optimizer' not defined when it is clearly defined in the function and how do I remedy this?