快速学习如何为XGboost优化超参数!
在过去的几年中,XGBoost被广泛用于表格数据推断,并且赢得了数百个挑战。但是,仅仅通过XGBoost并不能完成完成整的解决方案,同样的模型为什么有些人能获得更好的准确性呢?除了经验方面的差异,还有一个事实,那就是他们优化了超参数!
因此,我们今天将告诉您如何获取特定数据集的最佳超参数。
我们将在Hacker Earth挑战(https://www.hackerearth.com/en-us/challenges/competitive/hackerearth-machine-learning-challenge-predict-defcon-level/problems/)的数据集上使用scikit-learn配合XGBoost。
以下我使用的全部代码。我排除了分析部分和数据处理部分,因为这不是本文的目标。
#imported libs import numpy as np import pandas as pd from xgboost import XGBClassifier import matplotlib.pyplot as plt from scipy import stats import seaborn as sns from sklearn.model_selection import train_test_split from sklearn.preprocessing import StandardScaler from sklearn.pipeline import Pipeline from sklearn.model_selection import RandomizedSearchCV, GridSearchCV import sys train = pd.read_csv("train.csv") X = train.drop(['DEFCON_Level','ID'],axis=1) y = train['DEFCON_Level'] X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=42) #For classification #Random Search xgb_pipeline = Pipeline([('scaler', StandardScaler()), ('classifier',XGBClassifier())]) params = { 'min_child_weight': [1, 5, 10], 'gamma': [0.5, 1, 1.5, 2, 5], 'subsample': [0.6, 0.8, 1.0], 'colsample_bytree': [0.6, 0.8, 1.0], 'max_depth': [3, 4, 5] } random_search = RandomizedSearchCV(xgb_pipeline, param_distributions=params, n_iter=100, scoring='f1_weighted', n_jobs=4, verbose=3, random_state=1001 ) random_search.fit(X_train,y_train) #OR #Grid Search xgb_pipeline = Pipeline([('scaler', StandardScaler()), ('classifier',XGBClassifier())]) gbm_param_grid = { 'classifier__learning_rate': np.array([0.01,0.001]), 'classifier__n_estimators': np.array([100,200,300,400]), 'classifier__subsample': np.array([0.7,0.8,0.9]), 'classifier__max_depth': np.array([10,11,12,13,14,15,16,17]), 'classifier__lambda': np.array([1]), 'classifier__gamma': np.array([0]) #'classifier__colsample_bytree': np.arange(0,1.1,.2) } grid_search = GridSearchCV(estimator=xgb_pipeline, param_grid=gbm_param_grid, n_jobs= -1, scoring='f1_weighted', verbose=10) grid_search.fit(X_train,y_train) #Print out best parameters print(random_search.best_params_) print(grid_search.best_params_) #Print out scores on validation set print(random_search.score(X_test,y_test)) print(grid_search.score(X_test,y_test))
随机搜索优化
随机搜索优化
让我们分析一下随机搜索的区块:
#Random Search xgb_pipeline = Pipeline([('scaler', StandardScaler()), ('classifier',XGBClassifier())]) params = {'min_child_weight': [1, 5, 10], 'gamma': [0.5, 1, 1.5, 2, 5], 'subsample': [0.6, 0.8, 1.0], 'colsample_bytree': [0.6, 0.8, 1.0], 'max_depth': [3, 4, 5]}random_search = RandomizedSearchCV(xgb_pipeline, param_distributions=params, n_iter=100, scoring='f1_weighted', n_jobs=4, verbose=3, random_state=1001 )random_search.fit(X_train,y_train)
当我们使用XGBClassifier时,XGBRegressor的工作原理相同。您想搜索的参数在params中,可以简单地添加要尝试的值。
我们将f1_weighted作为指标,因为这是比赛中的要求。作业数量(n_jobs)基本上取决于是否要并行化计算。(如果有多个核心)
如前所述,这是一个随机搜索,因此并不是所有的参数组合都将被试用,这有助于节省计算时间,并具有超参数的初步建议。
网格搜索优化
#Grid Search xgb_pipeline = Pipeline([('scaler', StandardScaler()), ('classifier',XGBClassifier())])gbm_param_grid = { 'classifier__learning_rate': np.array([0.01,0.001]), 'classifier__n_estimators': np.array([100,200,300,400]), 'classifier__subsample': np.array([0.7,0.8,0.9]), 'classifier__max_depth': np.array([10,11,12,13,14,15,16,17]), 'classifier__lambda': np.array([1]), 'classifier__gamma': np.array([0])}grid_search = GridSearchCV(estimator=xgb_pipeline, param_grid=gbm_param_grid, n_jobs= -1, scoring='f1_weighted', verbose=10) grid_search.fit(X_train,y_train)
跟上面一样,可以更改XGBClassifier()使其成为XGBRegressor()。我们为变量n_jobs使用-1,以表明我们希望使用所有核进行计算。详细部署以显示分数和用于在训练时获取分数的参数。
结论
最后,只需打印以下最佳参数即可。
#Print out best parameters print(random_search.best_params_) print(grid_search.best_params_)#Print out scores on validation set print(random_search.score(X_test,y_test)) print(grid_search.score(X_test,y_test))
看看验证集的分数!