0.引言如果你活跃于机器学习社区,你一定了解提升机器(Boosting Machine)及其能力。从AdaBoost发展到如今广受欢迎的XGBoost,XGBoost已成为Kaggle比赛中公认的获胜算法。这是因为它极其强大。然而,当数据量极大时,XGBoost的训练时间也会变得很长。
大多数人可能对Light Gradient Boosting不太熟悉,但读完本文后,你将对其有深入了解。一个自然的问题会浮现:为什么会出现另一个提升机器算法?它比XGBoost更好吗?
注意:本文假设读者对GBMs和XGBoost算法有一定的了解。如果你不了解它们,请先学习它们的原理再阅读本文。
- 什么是LightGBMLightGBM是一个快速的、分布式的、高性能的基于决策树算法的梯度提升框架,适用于排序、分类、回归及其他许多机器学习任务。
由于它基于决策树算法,LightGBM采用最优的leaf-wise策略来分裂叶子节点,而其他提升算法通常采用depth-wise或level-wise方法。因此,在增长到相同的叶子节点时,leaf-wise算法比level-wise算法减少更多的损失,从而带来更高的精度,同时速度也令人惊叹,这就是LightGBM名字中“Light”的由来。
上述是LightGBM算法作者对其不同之处的简要概述。
XGBoost中决策树的增长方式示意图![image.png-17.6kB][1]
LightGBM中决策树的增长方式示意图undefined
Leaf-Wise分裂会增加复杂性,并可能导致过拟合,但可以通过设置max-depth参数来克服这一问题,限制树的最大深度。
接下来,我们将介绍如何安装LightGBM并使用它运行一个模型。我们将通过实验结果对比LightGBM和XGBoost,证明你应该以一种轻便的方式(Light Manner)使用LightGBM。
- LightGBM的优势首先让我们看看LightGBM的优势。
更快的训练速度和更高的效率:LightGBM使用基于直方图的算法。例如,它将连续的特征值分桶(buckets)装进离散的箱子(bins),这使得训练过程更快。更低的内存占用:使用离散的箱子(bins)保存并替换连续值,导致更少的内存占用。更高的准确率(相比于其他任何提升算法):通过leaf-wise分裂方法产生比level-wise分裂方法更复杂的树,这是实现更高准确率的主要因素。然而,它有时会导致过拟合,但我们可以通过设置max-depth参数来防止过拟合。大数据处理能力:由于其在训练时间上的缩减,LightGBM也具备处理大数据的能力。支持并行学习3. 安装LightGBM本节介绍如何在各种操作系统下安装LightGBM。由于桌面系统中最常用的操作系统是Windows、Linux和macOS,我们将依次介绍如何在这三种系统上安装LightGBM。
3.1 Windows对于Windows操作系统,由于其并非开源操作系统,开发者一直面临挑战。我们需要安装相应的编译环境才能编译LightGBM源代码。对于Windows下的底层C/C++编译环境,主要有微软的Visual Studio(或MSBuild)和开源的MinGW64,下面我们分别介绍这两种编译环境下的LightGBM安装。
注意,对于以下两种编译环境,我们都需要确保系统已安装Windows下的Git和CMake工具。
3.1.1 基于Visual Studio(MSBuild)环境代码语言:txtsvg fill=”none” height=”16″ viewbox=”0 0 16 16″ width=”16″ xmlns=”http://www.w3.org/2000/svg”> 复制“`txt git clone –recursive https://www.php.cn/link/2aae855e4fce821396110897f2513c60 LightGBMmkdir buildcd buildcmake -DCMAKE_GENERATOR_PLATFORM=x64 ..cmake –build . –target ALL_BUILD –config Release
txt git clone –recursive https://www.php.cn/link/2aae855e4fce821396110897f2513c60 LightGBMmkdir buildcd buildcmake ..make -jtxt
importing standard libraries import numpy as np import pandas as pd from pandas import Series, DataFrame #import lightgbm and xgboost import lightgbm as lgb import xgboost as xgb #loading our training dataset ‘adult.csv’ with name ‘data’ using pandas data=pd.read_csv(‘adult.csv’,header=None) #Assigning names to the columns data.columns=[‘age’,’workclass’,’fnlwgt’,’education’,’education-num’,’marital_Status’,’occupation’,’relationship’,’race’,’sex’,’capital_gain’,’capital_loss’,’hours_per_week’,’nativecountry’,’Income’] #glimpse of the dataset data.head() # Label Encoding our target variable from sklearn.preprocessing import LabelEncoder,OneHotEncoderl=LabelEncoder() l.fit(data.Income) l.classes data.Income=Series(l.transform(data.Income)) #label encoding our target variable data.Income.value_counts() #One Hot Encoding of the Categorical features one_hot_workclass=pd.get_dummies(data.workclass) one_hot_education=pd.get_dummies(data.education) one_hot_marital_Status=pd.get_dummies(data.marital_Status) one_hot_occupation=pd.get_dummies(data.occupation)one_hot_relationship=pd.get_dummies(data.relationship) one_hot_race=pd.get_dummies(data.race) one_hot_sex=pd.get_dummies(data.sex) one_hot_native_country=pd.get_dummies(data.native_country) #removing categorical features data.drop([‘workclass’,’education’,’marital_Status’,’occupation’,’relationship’,’race’,’sex’,’native_country’],axis=1,inplace=True) #Merging one hot encoded features with our dataset ‘data’ data=pd.concat([data,one_hot_workclass,one_hot_education,one_hot_marital_Status,one_hot_occupation,one_hot_relationship,one_hot_race,one_hot_sex,one_hot_nativecountry],axis=1) #removing dulpicate columns , i = np.unique(data.columns, return_index=True) data=data.iloc[:, i] #Here our target variable is ‘Income’ with values as 1 or 0. #Separating our data into features dataset x and our target dataset y x=data.drop(‘Income’,axis=1) y=data.Income #Imputing missing values in our target variable y.fillna(y.mode()[0],inplace=True) #Now splitting our dataset into test and train from sklearn.model_selection import train_test_split x_train,x_test,y_train,y_test=train_test_split(x,y,test_size=.3)
5.2 使用LightGBM代码语言:txt 复制“`txt
train_data=lgb.Dataset(x_train,label=y_train)setting parameters for lightgbmparam = {‘num_leaves’:150, ‘objective’:’binary’,’max_depth’:7,’learning_rate’:.05,’max_bin’:200}param[‘metric’] = [‘auc’, ‘binary_logloss’]#Here we have set max_depth in xgb and LightGBM to 7 to have a fair comparison between the two.#training our model using light gbmnum_round=50start=datetime.now()lgbm=lgb.train(param,train_data,num_round)stop=datetime.now()#Execution time of the modelexecution_time_lgbm = stop-startprint(execution_time_lgbm)#predicting on test setypred2=lgbm.predict(x_test)print(ypred2[0:5]) # showing first 5 predictions#converting probabilities into 0 or 1for i in range(0,9769): if ypred2[i]>=.5: # setting threshold to .5 ypred2[i]=1 else: ypred2[i]=0#calculating accuracyaccuracy_lgbm = accuracy_score(ypred2,y_test)accuracy_lgbmy_test.value_counts()from sklearn.metrics import roc_auc_score#calculating roc_auc_score for xgboostauc_xgb = roc_auc_score(y_test,ypred)print(auc_xgb)#calculating roc_auc_score for light gbm. auc_lgbm = roc_auc_score(y_test,ypred2)auc_lgbm comparison_dict = {‘accuracy score’:(accuracy_lgbm,accuracy_xgb),’auc score’:(auc_lgbm,auc_xgb),’execution time’:(execution_time_lgbm,execution_time_xgb)}#Creating a dataframe ‘comparison_df’ for comparing the performance of Lightgbm and xgb. comparison_df = DataFrame(comparison_dict) comparison_df.index= [‘LightGBM’,’xgboost’] print(comparison_df)