美文网首页
LightGBM算法 & XGBoost算法对比分析

LightGBM算法 & XGBoost算法对比分析

作者: ShowMeCoding | 来源:发表于2020-09-21 22:36 被阅读0次

    官方文档
    https://lightgbm.readthedocs.io/en/latest/index.html(微软开源)

    参考文档:机器学习算法之LightGBM
    https://www.biaodianfu.com/lightgbm.html

    1 简介

    LightGBM算法属于GBDT模型的进阶,和XGBoost一样采用损失函数的负梯度作为当前决策树的残差近似值,去拟合新的决策树。
    因为GBDT在每一次迭代的时候,都需要遍历整个训练数据多次。如果把整个训练数据装进内存则会限制训练数据的大小;如果不装进内存,反复地读写训练数据又会消耗非常大的时间。因此,为了弥补普通的GBDT算法无法处理海量数据的问题,提出了LightGBM算法。

    2 算法核心思想

    2.1 XGBoost算法

    XGBoost使用的是pre-sorted算法,能够更精确的找到数据分隔点

    • 首先,对所有特征按数值进行预排序。
    • 其次,在每次的样本分割时,用O(# data)的代价找到每个特征的最优分割点。
    • 最后,找到最后的特征以及分割点,将数据分裂成左右两个子节点。
      这种pre-sorting算法能够准确找到分裂点,但是在空间和时间上有很大的开销。
    • 由于需要对特征进行预排序并且需要保存排序后的索引值(为了后续快速的计算分裂点),因此内存需要训练数据的两倍。
    • 在遍历每一个分割点的时候,都需要进行分裂增益的计算,消耗的代价大。

    决策树的生长方式
    XGBoost采用的是按层生长level(depth)-wise生长策略,能够同时分裂同一层的叶子,从而进行多线程优化,不容易过拟合;但不加区分的对待同一层的叶子,带来了很多没必要的开销。因为实际上很多叶子的分裂增益较低,没必要进行搜索和分裂。

    2.2 LightGBM算法

    LightGBM使用的是histogram算法(直方图算法),首先将连续的浮点数据转换为bin数据,具体过程是首先确定对于每一个特征需要多少的桶bin,然后均分,将属于该桶的样本数据更新为bin的值,最后用直方图表示。(看起来很高大上,其实就是直方图统计,最后我们将大规模的数据放在了直方图中)。
    占用的内存更低,数据分隔的复杂度更低。其思想是将连续的浮点特征离散成k个离散值,并构造宽度为k的Histogram。然后遍历训练数据,统计每个离散值在直方图中的累计统计量。在进行特征选择时,只需要根据直方图的离散值,遍历寻找最优的分割点。
    使用直方图算法的优点

    • 首先最明显就是内存消耗的降低,直方图算法不仅不需要额外存储预排序的结果;
    • 而且可以只保存特征离散化后的值,而这个值一般用8位整型存储就足够了,内存消耗可以降低为原来的1/8。
    • 然后在计算上的代价也大幅降低,预排序算法每遍历一个特征值就需要计算一次分裂的增益,而直方图算法只需要计算k次(k可以认为是常数)。

    决策树的生长方式
    LightGBM采用leaf-wise生长策略,每次从当前所有叶子中找到分裂增益最大(一般也是数据量最大)的一个叶子,然后分裂,如此循环。因此同Level-wise相比,在分裂次数相同的情况下,Leaf-wise可以降低更多的误差,得到更好的精度。Leaf-wise的缺点是可能会长出比较深的决策树,产生过拟合。因此LightGBM在Leaf-wise之上增加了一个最大深度的限制,在保证高效率的同时防止过拟合。

    3 优势——相比较XGBoost

    • 更快的训练效率
    • 低内存使用
    • 更高的准确率
    • 支持并行化学习
    • 可处理大规模数据
    • 支持直接使用category特征

    4 在Scikit-Learn与XGBoost对比

    https://scikit-learn.org/stable/modules/generated/sklearn.ensemble.HistGradientBoostingClassifier.html?highlight=lightgbm
    histogram-based gradient boosting classification tree:基于直方图的梯度提升分类树

    4.1 导入所需要的包和库

    from xgboost import XGBRegressor
    import lightgbm as lgb
    import numpy as np
    from sklearn.metrics import mean_squared_error
    from sklearn.model_selection import GridSearchCV
    from sklearn.datasets import load_iris
    from sklearn.model_selection import train_test_split
    

    4.2 加载鸢尾花数据

    iris = load_iris()
    data = iris.data
    target = iris.target
    X_train, X_test, y_train, y_test = train_test_split(data, target, test_size=0.2)
    

    4.3 分别创建XGB和LGB模型进行训练

    4.3.1 训练XGBoost

    reg = XGBRegressor(
        n_estimators = 20,   # 迭代次数
        learning_rate = 0.1, # 学习率
        max_depth=5
    )
    reg.fit(X_train, y_train)
    
    # 测试集预测
    y_pred = reg.predict(X_test)
    # 模型评估
    print('The rmse of prediction is:', mean_squared_error(y_test, y_pred) ** 0.5)
    
    The rmse of prediction is: 0.2579017768469883
    
    # feature importances
    print('Feature importances:', list(reg.feature_importances_))
    
    Feature importances: [0.008026785, 0.025713025, 0.7764279, 0.1898323]
    

    网格搜索

    estimator = XGBRegressor()
    param_grid = {
        'learning_rate':[0.2,0.5,0.8],
        'n_estimators': np.arange(0,100,20)
    }
    reg = GridSearchCV(estimator, param_grid)
    clf = reg.fit(X_train, y_train)
    y_pred = clf.predict(X_test)
    mean_squared_error(y_test, y_pred)
    
    0.05894615685616801
    

    4.3.2 LightGBM训练

    gbm = lgb.LGBMRegressor(objective='regression', num_leaves=31, learning_rate=0.1, n_estimators=20)
    gbm.fit(X_train, y_train, eval_set=[(X_test, y_test)], eval_metric='l1', early_stopping_rounds=5)
    
    [1] valid_0's l1: 0.558965  valid_0's l2: 0.507722
    Training until validation scores don't improve for 5 rounds
    [2] valid_0's l1: 0.508315  valid_0's l2: 0.422938
    [3] valid_0's l1: 0.469458  valid_0's l2: 0.354078
    [4] valid_0's l1: 0.428637  valid_0's l2: 0.297129
    [5] valid_0's l1: 0.397107  valid_0's l2: 0.251408
    [6] valid_0's l1: 0.363512  valid_0's l2: 0.210417
    [7] valid_0's l1: 0.334591  valid_0's l2: 0.179052
    [8] valid_0's l1: 0.311293  valid_0's l2: 0.151726
    [9] valid_0's l1: 0.288382  valid_0's l2: 0.130775
    [10]    valid_0's l1: 0.269027  valid_0's l2: 0.111078
    [11]    valid_0's l1: 0.250241  valid_0's l2: 0.097117
    [12]    valid_0's l1: 0.231755  valid_0's l2: 0.0847149
    [13]    valid_0's l1: 0.219546  valid_0's l2: 0.0744859
    [14]    valid_0's l1: 0.206336  valid_0's l2: 0.0668118
    [15]    valid_0's l1: 0.193833  valid_0's l2: 0.0604602
    [16]    valid_0's l1: 0.183163  valid_0's l2: 0.0551445
    [17]    valid_0's l1: 0.173473  valid_0's l2: 0.0503368
    [18]    valid_0's l1: 0.164622  valid_0's l2: 0.0465006
    [19]    valid_0's l1: 0.156789  valid_0's l2: 0.0433829
    [20]    valid_0's l1: 0.153458  valid_0's l2: 0.0419514
    Did not meet early stopping. Best iteration is:
    [20]    valid_0's l1: 0.153458  valid_0's l2: 0.0419514
    
    LGBMRegressor(n_estimators=20, objective='regression')
    
    # 测试集预测
    y_pred = gbm.predict(X_test, num_iteration=gbm.best_iteration_)
    # 模型评估
    print('The rmse of prediction is:', mean_squared_error(y_test, y_pred) ** 0.5)
    
    The rmse of prediction is: 0.20482033985501885
    
    # feature importances
    print('Feature importances:', list(gbm.feature_importances_))
    
    Feature importances: [15, 9, 27, 21]
    

    网格搜索,参数优化

    estimator = lgb.LGBMRegressor(num_leaves=31)
    param_grid = {
        'learning_rate':[0.2,0.5,0.8],
        'n_estimators': np.arange(0,100,20)
    }
    gbm = GridSearchCV(estimator, param_grid)
    clf = gbm.fit(X_train, y_train)
    y_pred = clf.predict(X_test)
    mean_squared_error(y_test, y_pred)
    
     0.03318734265620019
    
    ​print('Best parameters found by grid search are:', reg.best_params_)
    print('Best parameters found by grid search are:', gbm.best_params_)
    
    Best parameters found by grid search are: {'learning_rate': 0.2, 'n_estimators': 20}
    Best parameters found by grid search are: {'learning_rate': 0.2, 'n_estimators': 20}
    

    4.4 总结

    model 默认参数 网格搜索 网格搜索参数
    XGBoost 0.2579017768469883 0.05894615685616801 'learning_rate': 0.2, 'n_estimators': 20
    LightGBM 0.20482033985501885 0.03318734265620019 'learning_rate': 0.2, 'n_estimators': 20

    在评价标准为RMSE的情况下,从预测的精度来看,LightGBM明显优于XGBoost。

    相关文章

      网友评论

          本文标题:LightGBM算法 & XGBoost算法对比分析

          本文链接:https://www.haomeiwen.com/subject/dkvbyktx.html