LightGBM -- Light Gradient Boosting Machine

article/2025/11/11 12:18:04

在这里插入图片描述

LightGBM 是微软开源的一个基于决策树和XGBoost的机器学习算法。具有分布式和高效处理大量数据的特点。

  • 更快的训练速度,比XGBoost的准确性更高
  • 更低的内存使用率,通过使用直方图算法将连续特征提取为离散特征,实现了惊人的快速训练速度和较低的内存使用率
  • 通过使用按叶分割而不是按级别分割来获得更高精度,加快目标函数收敛速度,并在非常复杂的树中捕获训练数据的底层模式。使用num_leaves和max_depth超参数控制过拟合
  • 支持并行计算、分布式处理和GPU学习

LightGBM的特点

  • XGBoost 使用决策树对一个变量进行拆分,并在该变量上探索不同的切割点(按级别划分的树生长策略)
  • LightGBM 专注于按叶子节点进行拆分,以便获得更好的拟合(按叶划分的树生长策略)

这使得LightGBM 能够快速获得很好的数据拟合,并生成能够替代XGBoost的解决方案。从算法上讲,XGBoost将决策树进行的分割结构作为一个图来计算,使用广度搜索优先(BFS),而LightGBM使用的是深度优先(DFS)

安装

# conda 安装
conda install -c conda-forge lightgbm# pip安装
python3.6 -m pip install lightgbm

基本使用

训练的过程有很多API接口可以使用, 下面分别说明一些常用API的使用方法和使用示例
https://lightgbm.readthedocs.io/en/v3.3.2/Python-API.html

lightgbm.train

parameters = {'learning_rate': 0.05,'boosting_type': 'gbdt','objective': 'binary','metrics': classification_metrics,'num_leaves': 32,'feature_fraction': 0.8,'bagging_fraction': 0.8,'bagging_freq': 5,'seed': 2022,'bagging_seed': 1,'feature_fraction_seed': 7,'min_data_in_leaf': 20,'n_jobs': -1,'verbose': -1,}lightgbm.train(params, train_set, num_boost_round=100, valid_sets=None, valid_names=None, fobj=None, feval=None, init_model=None, feature_name='auto', categorical_feature='auto', early_stopping_rounds=None, evals_result=None, verbose_eval='warn', learning_rates=None, keep_training_booster=False, callbacks=None)
参数说明
params模型训练的超参数, 比如学习率、评价指标等
train_set训练集
num_boost_roundboosting 迭代次数
valid_sets验证集,一般 valid_sets = [valid_set, train_set]
verbose_eval
early_stopping_rounds模型在验证分数停止提升(收敛了)就停止迭代了,early_stopping_rounds 限制一个最小的迭代次数,比如不少于200次
evals_resultstore all evaluation results of all the items in valid_sets, 一般用evals_result 来画loss在迭代过程中的图

使用示例 :lightgbm.train K折交叉验证 Train 二分类模型的过程

import lightgbm as lgb
import numpy as np
from sklearn.model_selection import StratifiedKFold
from sklearn.metrics import roc_auc_score, accuracy_score, f1_score, precision_score, recall_scoreX_train, X_test = data[~data['label'].isna()], data[data['label'].isna()]
Y_train = X_train['label']
KF = StratifiedKFold(n_splits=5, shuffle=True, random_state=2022)
parameters = {'learning_rate': 0.05,'boosting_type': 'gbdt','objective': 'binary','metric': 'auc','num_leaves': 32,'feature_fraction': 0.8,'bagging_fraction': 0.8,'bagging_freq': 5,'seed': 2022,'bagging_seed': 1,'feature_fraction_seed': 7,'min_data_in_leaf': 20,'n_jobs': -1, 'verbose': -1,
}
lgb_result = np.zeros(len(X_train))for fold_, (trn_idx, val_idx) in enumerate(KF.split(X_train.values, Y_train.values)):print("fold 5 of {}".format(fold_))trn_data = lgb.Dataset(X_train.iloc[trn_idx][features],label=Y_train.iloc[trn_idx])    val_data = lgb.Dataset(X_train.iloc[val_idx][features],label=Y_train.iloc[val_idx])evaluation_result = {}model = lgb.train(params=parameters,train_set=trn_data,num_boost_round=num_round,valid_sets=[trn_data, val_data],verbose_eval=500,early_stopping_rounds=100,  evals_result=evaluation_result)lgb_result[val_idx] = model.predict(X_train.iloc[val_idx][features], num_iteration=model.best_iteration)model.save_model(f'model/model_{fold_}.txt')lgb.plot_metric(evaluation_result, metric=current_metrics)    train_predict = model.predict(X_train, num_iteration=model.best_iteration)test_predict = model.predict(X_test, num_iteration=model.best_iteration)print('Train Precision score: {}'.format(precision_score(Y_train, [1 if i >= 0.5 else 0 for i in train_predict])))print('Train Recall score: {}'.format(recall_score(Y_train, [1 if i >= 0.5 else 0 for i in train_predict])))print('Train AUC score: {}'.format(roc_auc_score(Y_train, train_predict)))print('Train F1 score: {}\r\n'.format(f1_score(Y_train, [1 if i >= 0.5 else 0 for i in train_predict])))print('Test Precision score: {}'.format(precision_score(Y_test, [1 if i >= 0.5 else 0 for i in test_predict])))print('Test Recall score: {}'.format(recall_score(Y_test, [1 if i >= 0.5 else 0 for i in test_predict])))print('Test AUC score: {}'.format(roc_auc_score(Y_test, test_predict)))print('Test F1 score: {}'.format(f1_score(Y_test, [1 if i >= 0.5 else 0 for i in test_predict])))

调参

可视化

特征重要性分布lightgbm.plot_importance

lightgbm.plot_importance(booster, ax=None, height=0.2, xlim=None, ylim=None, title='Feature importance', xlabel='Feature importance', ylabel='Features', 
importance_type='auto', max_num_features=None, 
ignore_zero=True, figsize=None, dpi=None, grid=True, precision=3, **kwargs)
lightgbm.plot_importance(model, max_num_features=10)

模型保存 / 模型加载

  • 模型保存 lightgbm.Booster.save_model()
model = lgb.train(.....)
model.save_model(filename, num_iteration=None, start_iteration=0, importance_type='split')
model.save_model(os.path.join(MODEL_PATH, MODEL_NAME), num_iteration=model.best_iteration)
  • 模型加载:lightgbm.Booster实例化
lightgbm.Booster(params=None, train_set=None, model_file=None, model_str=None)
def load_model(model_path):if not os.path.exists(model_path):return Nonetry:model = lgb.Booster(model_file=model_path)except IOError:print('Failed to load model, path: ', model_path)return Nonereturn model
  • 另一种方式使用sklearn的 joblib扩展库
    注意:保存的后缀名是.pkl
from sklearn.externals import joblib# 模型存储
joblib.dump(model, 'model.pkl')# 模型加载
model= joblib.load('model.pkl')# 模型预测
Y_pred = model.predict(X_test, num_iteration=model.best_iteration_)

模型转化

参考文档

  • LightGBM’s documentation
  • LightGBM 中文文档
  • LightGBM’s 项目GitHub地址
  • LightGBM 在Kaggle机器学习竞赛的应用示例
  • 论文"LightGBM: A Highly Efficient Gradient Boosting Decision Tree". Advances in Neural Information Processing Systems 30 (NIPS 2017), pp. 3149-3157.

http://chatgpt.dhexx.cn/article/KBpak4mX.shtml

相关文章

Mifare UltraLight

Mifare UltraLight又称为MF0,从UltraLight(超轻的)这个名字就可以看出来,它是一个低成本、小容量的卡片。低成本,是指它是目前市场中价格最低的遵守ISO14443A协议的芯片之一;小容量,是指其存储容量只有512bit(Mifare S…

Low-light images enhancement/暗光/低光/微光增强系列:Attention-guided Low-light Image Enhancement(详解)

以下文字为博主翻译并添加了自己的理解,斜体为博主自己的想法,若有出错请指出。 摘要 暗光图像增强需要同时有效地处理颜色、亮度、对比度、伪影和噪声等多种因素。本文提出了一种新颖的注意力引导增强方案,并在此基础上构建了 端到端多分支…

STM32+PN532写UltraLight标签

第一次写博客记录下日常开发,最近公司一个项目需要用到NFC模块,所以开始了解NFC相关的一些知识,并在此MARK一下。 1、项目背景: 需要一个NFC模块为一个Mifare UltraLight的NFC标签写入一个蓝牙MAC地址,让手持设备接触…

零基础CSS入门教程(30)–CSS布局实例

点此查看 所有教程、项目、源码导航 本文目录 1. 前言2. 本章任务3. 开发过程3.1 设定全局样式3.2 头部标题栏样式3.3 导航栏样式3.4 内容区域3.5 底部版权区域 4. 小结 1. 前言 本篇是JavaWeb学习之路,CSS部分的最后一章。 从第24章初识CSS,到第53章C…

HTML+CSS的小实例

通过一个月以来对HTML5CSS的学习。这篇随笔给大家来做一个简单的网页中常见的导航栏。 这些都称之为网页中的导航栏。 我简单的做了一个某宝和58同城的导航栏,供大家学习参考。 一、58同城导航栏: 解析:首先我们来看到这个导航栏,…

CSS简单网页示例

简单今日头条页面实现: <!DOCTYPE html> <html><head><meta charset"utf-8"><title>今日头条</title><style>/* 设置body */body{/* 取消doby的内边距 */margin: 0;}/* 设置最底层标签d1 */.d1{/* 设置底层标签的大小 */…

css背景 ( 6种实例)

css背景实例 图片网站背景1.设置页面的背景颜色2.设置图像作为页面背景2.1图片加入至背景的方式2.1.1通过链接 2.2背景样式 3.定位背景图像4.固定背景5. 多图片背景6.渐变背景 CSS背景属性 图片网站 阿里巴巴矢量图标库 pixabay 图片转链接网站 背景 1.设置页面的背景颜色 …

CSS---‘样式’基础用法 与 案例

1、外部样式表 方式1&#xff1a; <link rel"stylesheet" type"text/css" href"文件路径"></link>方式2&#xff1a;&#xff08;常用&#xff09; <style>import url(文件地址) </style> 2、伪类选择器 a:hover{属性…

HTML+CSS案例

综合案例 1、分析1.1 整体结构1.2 部分结构 2、代码部分2.1 初始化_CSS2.2 头部2.2.1 头部_HTML2.2.2 头部_CSS 2.3、中间轮播图2.3.1 中间轮播图_HTML2.3.2 中间轮播图_CSS 2.4 精品推荐2.4.1 精品推荐_HTML2.4.2 精品推荐_CSS 2.5 底部样式2.5.1 底部样式_HTML2.5.2 底部样式…

css 的常用案例

Css 的几个常用案例 1. css 编写三角形 <!-- 三角形 --><div classtriangle-page><div class"triangle-top"></div><div class"triangle-right"></div><div class"triangle-bottom"></div>&l…

HTML CSS JavaScript简单案例实现

文章目录 简易计算器个人简历登录页面注册页面注册&#xff08;一&#xff09;注册&#xff08;二&#xff09; html、css 实现一个漂亮的表格书城列表页面简单框架全选反选功能 简易计算器 calculator.html <!doctype html> <html> <head><meta charse…

CSS基础学习案例

CSS–小米商城案例 小米商城案例目录 CSS--小米商城案例1.内容回顾2.案例顶部菜单3.二级菜单3.1 划分区域3.2搭建骨架 4.整合 顶部菜单 二级菜单小结5. 推荐菜单5.1整合案例如下5.2 小结 6.CSS进阶知识点6.1 hover&#xff08;伪类&#xff09;6.2 after&#xff08;伪类&…

html/css 个人网站实例(一)

显示效果 HTML代码 <!DOCTYPE html> <html lang"en"> <head><meta charset"UTF-8"><meta name"viewport" content"widthdevice-width, initial-scale1.0"><title>alalasheep的个人网站</titl…

CSS实例 简单案例

CSS文件 注意改变图片的样式时&#xff0c;是要加给图片所在的标签 比如p /* 整体 */ body {font: 16px/28px "Microsoft YaHei"; }/* 大标题 */ h1 {font-weight: 600;text-align: center; }/* 连接a */ a {text-decoration: none; }/* 时间 来源 */ .scor {font-…

CSS案例(1)

写在前面&#xff1a;本篇所有 css 均使用内嵌式引入。若想使用外链式&#xff0c;需先新建 .css 文件&#xff0c;再通过 link 标签引入到 html 里&#xff0c;样式部分的代码基本不用做其他修改。 目录 1 导航栏样式 2 商品展示页面 3 简单新闻页面 4 布局样式 1 导航栏样…

小案例CSS

代码&#xff1a; <!DOCTYPE html> <html lang"en"> <head> <meta charset"UTF-8"> <meta http-equiv"X-UA-Compatible" content"IEedge"> <meta name"viewport" content"widthde…

CSS常见样式的介绍和使用(附加案例)

CSS样式 一、css介绍 层叠样式表(英文全称&#xff1a;Cascading Style Sheets) ​ 是一种用来表现HTML标准通用标记语言的一个应用&#xff09;或XML&#xff08;标准通用标记语言的一个子集&#xff09;等文件样式的计算机语言。CSS不仅可以静态地修饰网页&#xff0c;还可以…

CSS 示例

基础内容 引入样式表&#xff1a;<link rel"stylesheet" href"test.css"> em&#xff1a;相对大小单位 选择器 示例说明#id选择所有类.clsss选择所有类p选择所有p标签&#xff0c;可以加逗号分组p em后代选择器&#xff0c;选中p标签中所有em标签…

CSS-200个小案例(一)

最近我在youtube上跟着大神学习200个CSS小案例&#xff0c;作者Online Tutorials 编码的内容很实用&#xff0c;案例中涉及定位、变换、动画等概念&#xff0c;适合进一步学习和巩固CSS知识&#xff0c;能帮助我们实现页面的特效。 youtube视频链接&#xff1a;https://www.you…

30个超棒的CSS应用实例

这 篇文章是很早之前在博客园看到的&#xff0c;收藏在网摘里&#xff0c;今天再看发现实在很棒&#xff0c;转载过来方便以后参考用&#xff0c;最棒的地方是这些效果的实现都只是利用CSSHTML 来实现的&#xff0c;基本上没有用到什么FLASH或JS脚本&#xff0c;大家也可以看看…