【机器学习】嘿马机器学习(算法篇)第13篇:集成学习进阶,5.6 lightGBM算法api介绍【附代码文档】
🏆🏆🏆教程全知识点简介:1.定位、目标。2. K-近邻算法涵盖距离度量、k值选择、kd树、鸢尾花种类预测数据集介绍、练一练、交叉验证网格搜索、facebook签到位置预测案例。3. 线性回归包括线性回归简介、线性回归损失和优化、梯度下降法介绍、波士顿房价预测案例、欠拟合和过拟合、正则化线性模型、正规方程推导方式、梯度下降法算法比较优化、维灾难。4. 逻辑回归涵盖逻辑回归介绍、癌症分类预测案例(良恶性乳腺癌肿瘤预测、获取数据)、ROC曲线绘制。5. 朴素贝叶斯算法包括朴素贝叶斯算法简介、概率基础复习、产品评论情感分析案例(取出内容列数据分析、判定评判标准好评差评)。6. 支持向量机涵盖SVM算法原理、SVM损失函数、数字识别器案例。7. 决策树算法包括决策树分类原理、cart剪枝、特征工程特征提取、决策树算法api、泰坦尼克号乘客生存预测案例。8. EM算法涵盖初识EM算法、EM算法介绍。9. HMM模型包括马尔科夫链、HMM简介、前向后向算法评估观察序列概率、维特比算法解码隐藏状态序列、HMM模型API介绍。10. 集成学习进阶涵盖Bagging、xgboost算法原理、otto案例(Otto Group Product Classification Challenge xgboost实现)、数据变化可视化、lightGBM、stacking算法基本思想、住房月租金预测。11. 聚类算法包括聚类算法api初步使用、聚类算法实现流程、模型评估、算法优化、特征降维、用户对物品类别喜好细分案例、算法选择指导。12. 数学基础涵盖向量与矩阵范数、朗格朗日乘子法、Huber Loss、极大似然函数取对数原因。
📚📚👉👉👉本站这篇博客: https://blog.csdn.net/yinuo_432/article/details/151331407 中查看
📚📚👉👉👉本站这篇博客: https://blog.csdn.net/yinuo_432/article/details/151331407 中查看
✨ 本教程项目亮点
🧠 知识体系完整:覆盖从基础原理、核心方法到高阶应用的全流程内容
💻 全技术链覆盖:完整前后端技术栈,涵盖开发必备技能
🚀 从零到实战:适合 0 基础入门到提升,循序渐进掌握核心能力
📚 丰富文档与代码示例:涵盖多种场景,可运行、可复用
🛠 工作与学习双参考:不仅适合系统化学习,更可作为日常开发中的查阅手册
🧩 模块化知识结构:按知识点分章节,便于快速定位和复习
📈 长期可用的技术积累:不止一次学习,而是能伴随工作与项目长期参考
🎯🎯🎯全教程总章节

🚀🚀🚀本篇主要内容
集成学习进阶
学习目标
- 知道xgboost算法原理
- 知道otto案例通过xgboost实现流程
- 知道lightGBM算法原理
- 知道PUBG案例通过lightGBM实现流程
- 知道stacking算法原理
- 知道住房月租金预测通过stacking实现流程
5.6 lightGBM算法api介绍
学习目标
- 了解lightGBM算法api中常用的参数
1 lightGBM的安装
- windows下:
pip3 install lightgbm
- mac下:
2 lightGBM参数介绍
2.1 Control Parameters
| Control Parameters | 含义 | 用法 |
|---|---|---|
| max_depth | 树的最大深度 | 当模型过拟合时,可以考虑首先降低 max_depth |
| min_data_in_leaf | 叶子可能具有的最小记录数 | 默认20,过拟合时用 |
| feature_fraction | 例如 为0.8时,意味着在每次迭代中随机选择80%的参数来建树 | boosting 为 random forest 时用 |
| bagging_fraction | 每次迭代时用的数据比例 | 用于加快训练速度和减小过拟合 |
| early_stopping_round | 如果一次验证数据的一个度量在最近的early_stopping_round 回合中没有提高,模型将停止训练 | 加速分析,减少过多迭代 |
| lambda | 指定正则化 | 0~1 |
| min_gain_to_split | 描述分裂的最小 gain | 控制树的有用的分裂 |
| max_cat_group | 在 group 边界上找到分割点 | 当类别数量很多时,找分割点很容易过拟合时 |
| n_estimators | 最大迭代次数 | 最大迭代数不必设置过大,可以在进行一次迭代后,根据最佳迭代数设置 |
2.2 Core Parameters
| Core Parameters | 含义 | 用法 |
|---|---|---|
| Task | 数据的用途 | 选择 train 或者 predict |
| application | 模型的用途 | 选择 regression: 回归时,binary: 二分类时,multiclass: 多分类时 |
| boosting | 要用的算法 | gbdt,rf: random forest,dart: Dropouts meet Multiple Additive Regression Trees,goss: Gradient-based One-Side Sampling |
| num_boost_round | 迭代次数 | 通常 100+ |
| learning_rate | 学习率 | 常用 0.1, 0.001, 0.003… |
| num_leaves | 叶子数量 | 默认 31 |
| device | cpu 或者 gpu | |
| metric | mae: mean absolute error ,mse: mean squared error ,binary_logloss: loss for binary classification ,multi_logloss: loss for multi classification |
2.3 IO parameter
| IO parameter | 含义 |
|---|---|
| max_bin | 表示 feature 将存入的 bin 的最大数量 |
| categorical_feature | 如果 categorical_features = 0,1,2, 则列 0,1,2是 categorical 变量 |
| ignore_column | 与 categorical_features 类似,只不过不是将特定的列视为categorical,而是完全忽略 |
| save_binary | 这个参数为 true 时,则数据集被保存为二进制文件,下次读数据时速度会变快 |
3 调参建议
| IO parameter | 含义 |
|---|---|
num_leaves | 取值应 <=2(max_depth)2^{(max_depth)}2(max_depth) |
min_data_in_leaf | 将它设置为较大的值可以避免生长太深的树,但可能会导致 underfitting,在大型数据集时就设置为数百或数千 |
max_depth | 这个也是可以限制树的深度 |
下表对应了 Faster Speed ,better accuracy ,over-fitting 三种目的时,可以调的参数
| Faster Speed | better accuracy | over-fitting |
|---|---|---|
将 max_bin 设置小一些 | 用较大的 max_bin | max_bin 小一些 |
num_leaves 大一些 | num_leaves 小一些 | |
用 feature_fraction来做 sub-sampling | 用 feature_fraction | |
用 bagging_fraction 和 bagging_freq | 设定 bagging_fraction 和 bagging_freq | |
| training data 多一些 | training data 多一些 | |
用 save_binary来加速数据加载 | 直接用 categorical feature | 用 gmin_data_in_leaf 和 min_sum_hessian_in_leaf |
| 用 parallel learning | 用 dart | 用 lambda_l1, lambda_l2 ,min_gain_to_split 做正则化 |
num_iterations 大一些,learning_rate小一些 | 用 max_depth 控制树的深度 |
5.7 lightGBM案例介绍
学习目标
- 通过鸢尾花数据集知道lightGBM算法对应api的使用
接下来,通过鸢尾花数据集对lightGBM的基本使用,做一个介绍。
from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split
from sklearn.model_selection import GridSearchCV
from sklearn.metrics import mean_squared_error
import lightgbm as lgb
加载数据,对数据进行基本处理
# 加载数据
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)
模型训练
gbm = lgb.LGBMRegressor(objective='regression', learning_rate=0.05, n_estimators=20)
gbm.fit(X_train, y_train, eval_set=[(X_test, y_test)], eval_metric='l1', early_stopping_rounds=5)
gbm.score(X_test, y_test)
# 0.810605595102488
# 网格搜索,参数优化
estimator = lgb.LGBMRegressor(num_leaves=31)
param_grid = {
'learning_rate': [0.01, 0.1, 1],
'n_estimators': [20, 40]
}
gbm = GridSearchCV(estimator, param_grid, cv=4)
gbm.fit(X_train, y_train)
print('Best parameters found by grid search are:', gbm.best_params_)
# Best parameters found by grid search are: {'learning_rate': 0.1, 'n_estimators': 40}
模型调优训练
gbm = lgb.LGBMRegressor(num_leaves=31, learning_rate=0.1, n_estimators=40)
gbm.fit(X_train, y_train, eval_set=[(X_test, y_test)], eval_metric='l1', early_stopping_rounds=5)
gbm.score(X_test, y_test)
# 0.9536626296481988
5.8 《绝地求生》玩家排名预测
1 项目背景
绝地求生(Player unknown's Battlegrounds),俗称吃鸡,是一款战术竞技型射击类沙盒游戏。
这款游戏是一款大逃杀类型的游戏,每一局游戏将有最多100名玩家参与,他们将被投放在绝地岛(battlegrounds)上,在游戏的开始时所有人都一无所有。玩家需要在岛上收集各种资源,在不断缩小的安全区域内对抗其他玩家,让自己生存到最后。
本作拥有很高的自由度,玩家可以体验飞机跳伞、开越野车、丛林射击、抢夺战利品等玩法,小心四周埋伏的敌人,尽可能成为最后1个存活的人。
该游戏中,玩家需要在游戏地图上收集各种资源,并在不断缩小的安全区域内对抗其他玩家,让自己生存到最后。
2 数据集介绍
本项目中,将为您提供大量匿名的《绝地求生》游戏统计数据。
其格式为每行包含一个玩家的游戏后统计数据,列为数据的特征值。
数据来自所有类型的比赛:单排,双排,四排;不保证每场比赛有100名人员,每组最多4名成员。
文件说明:
- train_V2.csv - 训练集
- test_V2.csv - 测试集
数据集局部图如下图所示:
数据集中字段解释:
-
Id [用户id]
-
Player’s Id
-
groupId [所处小队id]
-
ID to identify a group within a match. If the same group of players plays in different matches, they will have a different groupId each time.
-
matchId [该场比赛id]
-
ID to identify match. There are no matches that are in both the training and testing set.
-
assists [助攻数]
-
Number of enemy players this player damaged that were killed by teammates.
-
boosts [使用能量,道具数量]
-
Number of boost items used.
-
damageDealt [总伤害]
-
Total damage dealt. Note: Self inflicted damage is subtracted.
-
DBNOs [击倒敌人数量]
-
Number of enemy players knocked.
-
headshotKills [爆头数]
-
Number of enemy players killed with headshots.
-
heals [使用治疗药品数量]
-
Number of healing items used.
-
killPlace [本厂比赛杀敌排行]
-
Ranking in match of number of enemy players killed.
-
killPoints [Elo杀敌排名]
-
Kills-based external ranking of player. (Think of this as an Elo ranking where only kills matter.) If there is a value other than -1 in rankPoints, then any 0 in killPoints should be treated as a “None”.
-
kills [杀敌数]
-
Number of enemy players killed.
-
killStreaks [连续杀敌数]
-
Max number of enemy players killed in a short amount of time.
-
longestKill [最远杀敌距离]
-
Longest distance between player and player killed at time of death. This may be misleading, as downing a player and driving away may lead to a large longestKill stat.
-
matchDuration [比赛时长]
-
Duration of match in seconds.
-
matchType [比赛类型(小组人数)]
-
String identifying the game mode that the data comes from. The standard modes are “solo”, “duo”, “squad”, “solo-fpp”, “duo-fpp”, and “squad-fpp”; other modes are from events or custom matches.
-
maxPlace [本局最差名次]
-
Worst placement we have data for in the match. This may not match with numGroups, as sometimes the data skips over placements.
-
numGroups [小组数量]
-
Number of groups we have data for in the match.
-
rankPoints [Elo排名]
-
Elo-like ranking of player. This ranking is inconsistent and is being deprecated in the API’s next version, so use with caution. Value of -1 takes place of “None”.
-
revives [救活队员的次数]
-
Number of times this player revived teammates.
-
rideDistance [驾车距离]
-
Total distance traveled in vehicles measured in meters.
-
roadKills [驾车杀敌数]
-
Number of kills while in a vehicle.
-
swimDistance [游泳距离]
-
Total distance traveled by swimming measured in meters.
-
teamKills [杀死队友的次数]
-
Number of times this player killed a teammate.
-
vehicleDestroys [毁坏机动车的数量]
-
Number of vehicles destroyed.
-
walkDistance [步行距离]
-
Total distance traveled on foot measured in meters.
-
weaponsAcquired [收集武器的数量]
-
Number of weapons picked up.
-
winPoints [胜率Elo排名]
-
Win-based external ranking of player. (Think of this as an Elo ranking where only winning matters.) If there is a value other than -1 in rankPoints, then any 0 in winPoints should be treated as a “None”.
-
winPlacePerc [百分比排名]
-
The target of prediction. This is a percentile winning placement, where 1 corresponds to 1st place, and 0 corresponds to last place in the match. It is calculated off of maxPlace, not numGroups, so it is possible to have missing chunks in a match.
3 项目评估方式
你必须创建一个模型,根据他们的最终统计数据预测玩家的排名,从1(第一名)到0(最后一名)。
最后结果通过平均绝对误差(MAE)进行评估,即通过预测的winPlacePerc和真实的winPlacePerc之间的平均绝对误差
关于MAE:
- sklearn.metrics.mean_absolute_error
4 代码实现
见【PUBG-lightGBM.ipynb】
🚀✨ (未完待续)项目系列下一章
📚下一篇 将进入更精彩的环节! 🔔 记得收藏 & 关注,第一时间获取更新! 🍅 一起见证整个系列逐步成型的全过程。
更多推荐



所有评论(0)