LGB+LR的实践

article/2025/9/2 16:09:03

文章目录

  • 1 背景
  • 2 原理
  • 3 数据的准备
    • 3.1 读入数据
    • 3.2 切分训练集测试集
  • 4 LR
  • 5 LGB
  • 6 LGB+LR
    • 6.1 LGB实现
    • 6.2 LGB的vector导出来!
      • 6.2.1 训练集
      • 6.2.2 测试集
    • 6.3 LR+LGB
  • 7 结果对比

1 背景

相信大名鼎鼎的GBDT+LR组合很多小伙伴都听过,这种组合模型的预测效果要比单模型要好,但之前一直没有亲自实践过,最近刚好公司一个项目用到了,故抓紧时间总结一波~

2 原理

简单来说就是首先用树模型(GBDT、Xgboost、Lightgbm)来预测样本结果,然后将树模型的结果转为标准的变量形式放入LR中,最终进行预测~

  • 具有stacking思想的二分类器模型,GBDT用来对训练集提取特征作为新的训练输入数据,LR作为新训练输入数据的分类器。
  • GBDT算法的特点正好可以用来发掘有区分度的特征、特征组合,减少特征工程中人力成本。而LR则可以快速实现算法

具体的一个demo例子见下方,根据树模型的结果转为标准变量形式并放入模型~

在这里插入图片描述

下面就拿一个具体数据来看看GBDT+LR的效果,以及与其余模型的比较

3 数据的准备

3.1 读入数据

import pandas as pd
import warnings
warnings.filterwarnings('ignore')# 读入数据
df = pd.read_csv('telecom_churn.csv')
df['churn'] = df['churn'].map(str)
churn_dic = {'True':1, 'False':0}
df['churn'] = df['churn'].map(churn_dic)
print(df.shape)
df.head()
(3333, 21)
stateaccount lengtharea codephone numberinternational planvoice mail plannumber vmail messagestotal day minutestotal day callstotal day charge...total eve callstotal eve chargetotal night minutestotal night callstotal night chargetotal intl minutestotal intl callstotal intl chargecustomer service callschurn
0KS128415382-4657noyes25265.111045.07...9916.78244.79111.0110.032.7010
1OH107415371-7191noyes26161.612327.47...10316.62254.410311.4513.733.7010
2NJ137415358-1921nono0243.411441.38...11010.30162.61047.3212.253.2900
3OH84408375-9999yesno0299.47150.90...885.26196.9898.866.671.7820
4OK75415330-6626yesno0166.711328.34...12212.61186.91218.4110.132.7330

5 rows × 21 columns

df['churn'].value_counts()
0    2850
1     483
Name: churn, dtype: int64

3.2 切分训练集测试集

X = df[['total day calls', 'total night charge', 'number vmail messages', 'total intl charge', 'total eve calls']]
y = df['churn'].values
from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.3,random_state = 23)
print(X_train.shape, X_test.shape, y_train.shape, y_test.shape)
(2333, 5) (1000, 5) (2333,) (1000,)

4 LR

from sklearn.linear_model import LogisticRegression
from sklearn import metrics# 初始建模
lr = LogisticRegression(random_state = 23)
print(lr)
lr.fit(X_train, y_train)# 计算AUC
scores = lr.predict_proba(X_test)[:,1]
LR_auc = metrics.roc_auc_score(y_test, scores) # y_test真实标签 scores为预测为1的概率
LR_auc
LogisticRegression(random_state=23)0.5834069949026194

5 LGB

import lightgbm as lgb
from lightgbm.sklearn import LGBMClassifier # 是lightgbm的sklearn包。这个包允许我们像GBM一样使用Grid Search 和并行处理。# 搭建模型
model_lgb = lgb.LGBMClassifier(boosting_type='gbdt',objective = 'binary',metric = 'auc',verbose = 0,learning_rate = 0.01,num_leaves = 35,feature_fraction=0.8,bagging_fraction= 0.9,bagging_freq= 8,lambda_l1= 0.6,lambda_l2= 0)#  拟合模型
model_lgb.fit(X_train, y_train)# 计算AUC
scores = model_lgb.predict_proba(X_test)[:,1]
LGB_auc = metrics.roc_auc_score(y_test, scores) # y_test真实标签 scores为预测为1的概率
LGB_auc
[LightGBM] [Warning] feature_fraction is set=0.8, colsample_bytree=1.0 will be ignored. Current value: feature_fraction=0.8
[LightGBM] [Warning] lambda_l1 is set=0.6, reg_alpha=0.0 will be ignored. Current value: lambda_l1=0.6
[LightGBM] [Warning] bagging_fraction is set=0.9, subsample=1.0 will be ignored. Current value: bagging_fraction=0.9
[LightGBM] [Warning] lambda_l2 is set=0, reg_lambda=0.0 will be ignored. Current value: lambda_l2=0
[LightGBM] [Warning] bagging_freq is set=8, subsample_freq=0 will be ignored. Current value: bagging_freq=8
[LightGBM] [Warning] Find whitespaces in feature_names, replace with underlines
[LightGBM] [Warning] feature_fraction is set=0.8, colsample_bytree=1.0 will be ignored. Current value: feature_fraction=0.8
[LightGBM] [Warning] lambda_l1 is set=0.6, reg_alpha=0.0 will be ignored. Current value: lambda_l1=0.6
[LightGBM] [Warning] bagging_fraction is set=0.9, subsample=1.0 will be ignored. Current value: bagging_fraction=0.9
[LightGBM] [Warning] lambda_l2 is set=0, reg_lambda=0.0 will be ignored. Current value: lambda_l2=0
[LightGBM] [Warning] bagging_freq is set=8, subsample_freq=0 will be ignored. Current value: bagging_freq=8
[LightGBM] [Warning] Auto-choosing col-wise multi-threading, the overhead of testing was 0.000353 seconds.
You can set `force_col_wise=true` to remove the overhead.0.601792922596423

6 LGB+LR

6.1 LGB实现

import lightgbm as lgb
from lightgbm.sklearn import LGBMClassifier # 是lightgbm的sklearn包。这个包允许我们像GBM一样使用Grid Search 和并行处理。
# 搭建模型
lgb_param = {'boosting_type':'gbdt','objective' : 'binary','metric' : 'auc','verbose' : 0,'learning_rate' : 0.01,'num_leaves' : 4,'feature_fraction':0.8,'bagging_fraction': 0.9,'bagging_freq': 8,'lambda_l1': 0.6,'lambda_l2': 0,'n_estimators' : 200}'''
num_leaves:代表的是一棵树上的叶子数
n_estimators:代表的是多少棵树!
- 每棵树4个叶子,然后默认是100棵树!!!!本场景选择200!
'''model = lgb.LGBMClassifier(boosting_type='gbdt',objective = 'binary',metric = 'auc',verbose = 0,learning_rate = 0.01,num_leaves = 4,feature_fraction=0.8,bagging_fraction= 0.9,bagging_freq= 8,lambda_l1= 0.6,lambda_l2= 0,n_estimators = 200)#  拟合模型
model.fit(X_train, y_train)
[LightGBM] [Warning] feature_fraction is set=0.8, colsample_bytree=1.0 will be ignored. Current value: feature_fraction=0.8
[LightGBM] [Warning] lambda_l1 is set=0.6, reg_alpha=0.0 will be ignored. Current value: lambda_l1=0.6
[LightGBM] [Warning] bagging_fraction is set=0.9, subsample=1.0 will be ignored. Current value: bagging_fraction=0.9
[LightGBM] [Warning] lambda_l2 is set=0, reg_lambda=0.0 will be ignored. Current value: lambda_l2=0
[LightGBM] [Warning] bagging_freq is set=8, subsample_freq=0 will be ignored. Current value: bagging_freq=8
[LightGBM] [Warning] Find whitespaces in feature_names, replace with underlines
[LightGBM] [Warning] feature_fraction is set=0.8, colsample_bytree=1.0 will be ignored. Current value: feature_fraction=0.8
[LightGBM] [Warning] lambda_l1 is set=0.6, reg_alpha=0.0 will be ignored. Current value: lambda_l1=0.6
[LightGBM] [Warning] bagging_fraction is set=0.9, subsample=1.0 will be ignored. Current value: bagging_fraction=0.9
[LightGBM] [Warning] lambda_l2 is set=0, reg_lambda=0.0 will be ignored. Current value: lambda_l2=0
[LightGBM] [Warning] bagging_freq is set=8, subsample_freq=0 will be ignored. Current value: bagging_freq=8
[LightGBM] [Warning] Auto-choosing col-wise multi-threading, the overhead of testing was 0.000282 seconds.
You can set `force_col_wise=true` to remove the overhead.LGBMClassifier(bagging_fraction=0.9, bagging_freq=8, feature_fraction=0.8,lambda_l1=0.6, lambda_l2=0, learning_rate=0.01, metric='auc',n_estimators=200, num_leaves=4, objective='binary', verbose=0)
model.get_params()
{'boosting_type': 'gbdt','class_weight': None,'colsample_bytree': 1.0,'importance_type': 'split','learning_rate': 0.01,'max_depth': -1,'min_child_samples': 20,'min_child_weight': 0.001,'min_split_gain': 0.0,'n_estimators': 200,'n_jobs': -1,'num_leaves': 4,'objective': 'binary','random_state': None,'reg_alpha': 0.0,'reg_lambda': 0.0,'silent': True,'subsample': 1.0,'subsample_for_bin': 200000,'subsample_freq': 0,'metric': 'auc','verbose': 0,'feature_fraction': 0.8,'bagging_fraction': 0.9,'bagging_freq': 8,'lambda_l1': 0.6,'lambda_l2': 0}

6.2 LGB的vector导出来!

6.2.1 训练集

import numpy as npy_pred = model.predict(X_train,pred_leaf=True) 
#  预测结果为该样本最终落在树的哪一个节点上!如果'num_leaves': 4,则可能落在 0 1 2 3 这四个位置上!
train_matrix = np.zeros([len(y_pred), len(y_pred[0])*lgb_param['num_leaves']],dtype=np.int64)
print(train_matrix.shape) # 1000行 800列 因为是1000个样本点,同时200棵树,每棵树4个节点,则800个变量
train_matrix
(2333, 800)array([[0, 0, 0, ..., 0, 0, 0],[0, 0, 0, ..., 0, 0, 0],[0, 0, 0, ..., 0, 0, 0],...,[0, 0, 0, ..., 0, 0, 0],[0, 0, 0, ..., 0, 0, 0],[0, 0, 0, ..., 0, 0, 0]], dtype=int64)
for i in range(len(y_pred)):# 对每一个样本点做循环!然后卡一个点,每隔4个设一个关卡!temp = np.arange(len(y_pred[0]))*lgb_param['num_leaves'] + np.array(y_pred[i])train_matrix[i][temp] += 1
lgb_output_vec_train = pd.DataFrame(train_matrix)
lgb_output_vec_train.columns = ['leaf_' + str(i) for i in lgb_output_vec_train.columns]
lgb_output_vec_train
leaf_0leaf_1leaf_2leaf_3leaf_4leaf_5leaf_6leaf_7leaf_8leaf_9...leaf_790leaf_791leaf_792leaf_793leaf_794leaf_795leaf_796leaf_797leaf_798leaf_799
01000001000...1000100010
11000001000...1000010010
21000100010...1000100010
31000100010...1000100010
41000100010...0000100100
..................................................................
23281000100010...1000010010
23291000100010...1000010010
23301000001000...1000100010
23311000001000...1000100010
23321000001000...0000010100

2333 rows × 800 columns

6.2.2 测试集

import numpy as npy_pred = model.predict(X_test,pred_leaf=True) 
#  预测结果为该样本最终落在树的哪一个节点上!如果'num_leaves': 4,则可能落在 0 1 2 3 这四个位置上!
test_matrix = np.zeros([len(y_pred), len(y_pred[0])*lgb_param['num_leaves']],dtype=np.int64)
print(test_matrix.shape) # 1000行 800列 因为是1000个样本点,同时200棵树,每棵树4个节点,则800个变量
test_matrix
(1000, 800)array([[0, 0, 0, ..., 0, 0, 0],[0, 0, 0, ..., 0, 0, 0],[0, 0, 0, ..., 0, 0, 0],...,[0, 0, 0, ..., 0, 0, 0],[0, 0, 0, ..., 0, 0, 0],[0, 0, 0, ..., 0, 0, 0]], dtype=int64)
for i in range(len(y_pred)):# 对每一个样本点做循环!然后卡一个点,每隔4个设一个关卡!temp = np.arange(len(y_pred[0]))*lgb_param['num_leaves'] + np.array(y_pred[i])test_matrix[i][temp] += 1
lgb_output_vec = pd.DataFrame(test_matrix)
lgb_output_vec.columns = ['leaf_' + str(i) for i in lgb_output_vec.columns]
lgb_output_vec
leaf_0leaf_1leaf_2leaf_3leaf_4leaf_5leaf_6leaf_7leaf_8leaf_9...leaf_790leaf_791leaf_792leaf_793leaf_794leaf_795leaf_796leaf_797leaf_798leaf_799
01000100010...1000010010
10100010001...0100100001
21000001000...1000100010
31000100010...1000010010
41000001000...1000100010
..................................................................
9951000100010...1000100010
9961000100010...0010001000
9971000100010...1000010010
9980001010001...0100100001
9991000100010...1000010010

1000 rows × 800 columns

y_pred[0] # 第一个样本点在100棵树上分别落的位置!
array([0, 0, 0, 3, 3, 0, 3, 0, 3, 3, 0, 3, 3, 0, 3, 0, 0, 0, 0, 0, 0, 0,0, 0, 0, 3, 0, 0, 3, 3, 3, 2, 0, 3, 0, 2, 2, 2, 3, 0, 2, 0, 2, 0,0, 0, 0, 3, 3, 3, 0, 3, 0, 0, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3,3, 3, 0, 3, 3, 0, 2, 0, 2, 2, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 0,3, 3, 3, 3, 1, 3, 3, 3, 0, 0, 0, 0, 2, 0, 0, 1, 0, 0, 2, 0, 0, 3,0, 2, 2, 2, 3, 2, 3, 3, 3, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 0, 0,3, 3, 0, 3, 1, 1, 1, 1, 1, 1, 1, 1, 3, 0, 3, 3, 0, 3, 0, 0, 0, 0,0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 1, 3, 1, 0, 0, 0, 0, 0, 0, 0, 0,1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 1, 1, 2, 2, 3, 2, 2, 2,3, 2])
len(y_pred) # 表示1000个样本点!
1000
len(y_pred[0]) # 表示200棵树
200

6.3 LR+LGB

from sklearn.linear_model import LogisticRegression
from sklearn import metrics# 初始建模
lr = LogisticRegression(random_state = 23)
print(lr)
lr.fit(lgb_output_vec_train, y_train)# 计算AUC
scores = lr.predict_proba(lgb_output_vec)[:,1]
LR_LGB_auc = metrics.roc_auc_score(y_test, scores) # y_test真实标签 scores为预测为1的概率
LR_LGB_auc
LogisticRegression(random_state=23)0.58792613217832

7 结果对比

df = pd.DataFrame({'model':['LR', 'LGB', 'LGB+LR'], 'AUC':[LR_auc, LGB_auc, LR_LGB_auc]})
df
modelAUC
0LR0.583407
1LGB0.601793
2LGB+LR0.587926

结论:就本案例而言,LGB+LR的效果没有LGB好,所以并不能绝对说某一个模型效果如何好,应该根据不同数据场景选择最优的模型。一般而言,在CTR预估场景下LGB+LR效果还是不错的



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

相关文章

[机器学习] LR与SVM的异同

1 为什么将LR和SVM放在一起来进行比较? 回答这个问题其实就是回答LR和SVM有什么相同点。 第一,LR和SVM都是分类算法。 看到这里很多人就不会认同了,因为在很大一部分人眼里,LR是回归算法。我是非常不赞同这一点的,因…

pytorch:多标签分类的损失函数和准确率计算

1 损失函数 我们先用sklearn生成一个多标签分类数据集。 from sklearn.datasets import make_multilabel_classificationX, y make_multilabel_classification(n_samples1000,n_features10,n_classes3,n_labels2,random_state1) print(X.shape, y.shape)看一下标签长啥样。 …

caffe训练分类模型教程

caffe训练分类模型教程 1.已有图像存放在train和val下,book和not-book(两类)的图片数量相同 在caffe/data下新建一個myself文件夾,并新建两个文件夹分别命名为train和val 批量重命名图片 # -*- coding:utf8 -*- import os class …

金融风控实战——模型融合

过采样方法使用条件 (1)负样本可以代表样本空间 (2)数据是足够干净的(样本、特征没有噪声) 过拟合 (1)增多数据 (2)特征筛选 (3)调参…

【推荐算法】ctr预估模型总结(LR、FM、FFM、NFM、AFM、WDL、DCN、DeepFM、FwFM、FLEN)

文章目录 前言LRPOLY2FM(Factorization Machine)FFM(Field-aware Factorization Machine)AFM(Attention Factorization Machine)NFM(Neural Factorization Machine)WDL(w…

概率图模型 —— 串连 NB、LR、MEM、HMM、CRF

概率图模型(PGM),作为机器学习的重要分支,能串连起很多传统模型,比如 NB、LR、MEM、HMM、CRF、DBN 等。本篇文章,从串连多个模型的角度,来谈谈 PGM,顺便把这些模型回顾下。 1 Why PG…

基于GBDT+LR模型的深度学习推荐算法

GBDTLR算法最早是由Facebook在2014年提出的一个推荐算法,该算法分两部分构成,第一部分是GBDT,另一部分是LR.下面先介绍GBDT算法,然后介绍如何将GBDT和LR算法融合 1.1 GBDT算法 GBDT的全称是 Gradient Boosting Decision Tree&am…

Logistic逻辑回归模型(LR)基础

逻辑回归(Logistic Regression, LR)模型其实仅在线性回归的基础上,套用了一个逻辑函数,但也就由于这个逻辑函数,使得逻辑回归模型成为了机器学习领域一颗耀眼的明星,更是计算广告学的核心。本文主要详述逻辑回归模型的基础&#x…

模型压缩一-知识蒸馏

一、知识蒸馏简介 知识蒸馏是模型压缩方法中的一个大类,是一种基于“教师-学生网络(teacher-student-network)思想”的训练方法, 其主要思想是拟合教师模型(teacher-model)的泛化性等(如输出概率…

推荐系统之GBDT+LR

前言 前面讲过的FM与FFM模型虽然增强了模型的交叉能力,但是不管怎样都只能做二阶的交叉,如果想要继续加大特征交叉的维度,那就会出大计算爆炸的情况。所以Facebook提出了梯度提升树(GBDT)逻辑回归(LR&…

使用Keras进行单模型多标签分类

原文:https://www.pyimagesearch.com/2018/05/07/multi-label-classification-with-keras/ 作者:Adrian Rosebrock 时间:2018年5月7日 源码:https://pan.baidu.com/s/1x7waggprAHQDjalkA-ctvg (wa61) 译者&…

LR模型常见问题小议

 LR模型常见问题小议 标签: LR机器学习 2016-01-10 23:33 671人阅读 评论(0) 收藏 举报 本文章已收录于: 分类: 机器学习(10) 作者同类文章 X 版权声明:本文为博主原创文章&…

信用评分卡(A卡) 基于LR模型的数据处理及建模过程

数据来自:魔镜杯风控算法大赛(拍拍贷)。有关数据的具体描述可以看比赛页面。 0. 数据集的关键字段及描述: Master:每一行代表一个样本(一笔成功成交借款),每个样本包含200多个各类…

机器分类---LR分类+模型评估

文章目录 数据集ROC曲线与AUC理论知识曲线理解实例计算 代码 更详细的数据集介绍(有图形分析,应该比较好理解) https://blog.csdn.net/weixin_42567027/article/details/107416002 数据集 数据集有三个类别,每个类别有50个样本。…

python机器学习算法(赵志勇)学习笔记( Logistic Regression,LR模型)

Logistic Regression(逻辑回归) 分类算法是典型的监督学习,分类算法通过对训练样本的学习,得到从样本特征到样本的标签之间的映射关系,也被称为假设函数,之后可利用该假设函数对新数据进行分类。 通过训练数据中的正负样本,学习样本特征到样本标签之间的假设函数,Log…

推荐系统实战中LR模型训练(二)

背景: 上一篇推荐系统实战中LR模型训练(一) 中完成了LR模型训练的代码部分。本文中将详细讲解数据准备部分,即将文本数据数值化为稀疏矩阵的形式。 文本数据: 稀疏矩阵: 实现过程: 文本数据格…

机器学习 | LR逻辑回归模型

逻辑回归(Logistic Regression,简称LR)名为“回归”却是用来分类工作、在线性数据上表现优异的分类器。 视频教程:第07讲:逻辑回归是线性分类器的佼佼者 LR是数据挖掘领域常用的一种分类模型,常用于解决二分类问题,例如垃圾邮件判定、经济预测、疾病诊断(通过年龄、性…

推荐系统实战中LR模型训练(一)

背景: 在“批量导入数据到Redis” 中已经介绍了将得到的itema item1:score1,item2:score2…批量导入到Redis数据库中。本文的工作是运用机器学习LR技术,抽取相应的特征,进行点击率的估计。 点击率(Click-Through-Rate, CTR&#…

Prometheus TSDB存储原理

Python微信订餐小程序课程视频 https://blog.csdn.net/m0_56069948/article/details/122285951 Python实战量化交易理财系统 https://blog.csdn.net/m0_56069948/article/details/122285941 Prometheus 包含一个存储在本地磁盘的时间序列数据库,同时也支持与远程…

数据库必知必会:TiDB(8)TiDB 数据库 SQL 执行流程

数据库必知必会:TiDB(8)TiDB 数据库 SQL 执行流程 数据库 SQL 执行流程DML语句读流程概述SQL的Parse与CompileSQL的Execute DML语句写流程概述执行 DDL语句流程概要执行 知识点回顾 数据库 SQL 执行流程 在TiDB中三个重要组件: …