Import
import xgboost as xgb
Prepare Data
dtrain = xgb.DMatrix( X_train, label = y_train)
dtest = xgb.DMatrix(X_test, label = y_test)
Params
an example
params = {
'max_depth':7, #from 4 to 7
'learning_rate':0.001, #from 0.001
'subsample':0.8,
'colsample_bytree':0.2, # from 0.2 to 1, because need to take all features
'eval_metric':'rmse',
'objective':'reg:squarederror',
'tree_method':'gpu_hist',
'predictor':'gpu_predictor',
'random_state':123
}
- max_depth:决定了决策树被分为几次,2^depth 个node
- colsample_bytree: 每次boosting(也就是做一个新树),用多少的feature,0-1, 数值小可以避免overfitting还可以加速运行
- subsample:每次boosting用多少的sample,也可以避免overfitting
- tree_method: 选‘gpu_hist’可以用gpu加速
- predictor:gpu_predictor也可以cpu_predictor
- random_state:定一个seed确保每次可重复性
- learning_rate: 调,从0.001,到0.1可以用optuna调
- objective: 你的任务是啥,如果是regression,可以用'reg:squarederror',如果是classification,可以用'binary:logistic',以下是一些available的选项。

添加图片注释,不超过 140 字(可选)

添加图片注释,不超过 140 字(可选)

添加图片注释,不超过 140 字(可选)

添加图片注释,不超过 140 字(可选)
训练
example
bst = xgb.train(params,
dtrain=dtrain,
evals = [(dtrain, 'train'), (dvalidation, 'val')], # early stop will use the last item in the evals
num_boost_round = 999,
early_stopping_rounds=100,
verbose_eval=10)
evals是一个list,里面每项是一个tuple,第一个是数据,第二个是名字,如果后面有early stop,那就会用evals里最后一项作为early stop的依据
num_boost_round决定了多少颗树,每棵树都比前一棵树要优化,树越多,越overfitting
early_stopping_rounds决定了等多少个树如果还没有进步就停止新树了,所以num_boost_round可以设大,反正也不会真的建那么多树
verbose_eval决定了每多少棵树你要看一次结果
最后会return一个模型,可以bst or model.predict
LightGBM也类似
一个param的例子
params = {
'objective': 'rmse',
'boosting_type': 'gbdt',
'max_depth': -1,
'max_bin':255,
'min_data_in_leaf':750,
'learning_rate': 0.10,
'subsample': 0.72,
'subsample_freq': 3,
'feature_fraction': 0.5,
'lambda_l1': 0.5,
'lambda_l2': 1.0,
'categorical_column':[0],
'seed':2021,
'n_jobs':-1,
'verbose': -1,
'device': 'gpu',
'num_gpu': 1,
'gpu_platform_id':-1,
'gpu_device_id':-1,
'gpu_use_dp': False,
}
model = lgb.train(params = params,
num_boost_round=2000,
train_set = train_dataset,
valid_sets = [train_dataset, valid_dataset],
verbose_eval = 20,
early_stopping_rounds=50,
feval = feval_rmspe) # function of evaluation if customized
def feval_rmspe(preds, train_data):
y_true = train_data.get_label()
rmspe = np.sqrt(np.mean(np.square((y_true - preds) / y_true)))
return 'RMSPE', rmspe, False # False means the lower the better