LightGBM特征重要性画图

转载于:https://blog.csdn.net/m0_37477175/article/details/80567010

资料参考:
1. Evaluate Feature Importance using Tree-based Model
2. lgbm.fi.plot: LightGBM Feature Importance Plotting
3. lightgbm官方文档

前言

基于树的模型可以用来评估特征的重要性。 在本博客中,我将使用LightGBM中的GBDT模型来评估特性重要性的步骤。 LightGBM是由微软发布的高精度和高速度梯度增强框架(一些测试表明LightGBM可以产生与XGBoost一样的准确预测,但速度可以提高25倍)。

首先,我们导入所需的软件包:用于数据预处理的pandas,用于GBDT模型的LightGBM以及用于构建功能重要性条形图的matplotlib。

import pandas as pd
import matplotlib.pylab as plt
import lightgbm as lgb
   
   
  • 1
  • 2
  • 3

然后,我们需要加载和预处理训练数据。 在这个例子中,我们使用预测性维护数据集。

# read data
train = pd.read_csv('E:\Data\predicitivemaintance_processed.csv')

# drop the columns that are not used for the model
train = train.drop([‘Date’, ‘FailureDate’],axis=1)

# set the target column
target = ‘FailNextWeek’

# One-hot encoding
feature_categorical = [‘Model’]
train = pd.get_dummies(train, columns=feature_categorical)

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12

接下来,我们用训练数据训练GBDT模型:

lgb_params = {
    'boosting_type': 'gbdt',
    'objective': 'binary',
    'num_leaves': 30,
    'num_round': 360,
    'max_depth':8,
    'learning_rate': 0.01,
    'feature_fraction': 0.5,
    'bagging_fraction': 0.8,
    'bagging_freq': 12
}
lgb_train = lgb.Dataset(train.drop(target, 1), train[target])
model = lgb.train(lgb_params, lgb_train)
 
 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13

模型训练完成后,我们可以调用训练模型的plot_importance函数来获取特征的重要性。

plt.figure(figsize=(12,6))
lgb.plot_importance(model, max_num_features=30)
plt.title("Featurertances")
plt.show()
 
 
  • 1
  • 2
  • 3
  • 4

这里写图片描述

保存feature importance

booster = model.booster_
importance = booster.feature_importance(importance_type='split')
feature_name = booster.feature_name()
# for (feature_name,importance) in zip(feature_name,importance):
#     print (feature_name,importance) 
feature_importance = pd.DataFrame({
  
  'feature_name':feature_name,'importance':importance} )
feature_importance.to_csv('feature_importance.csv',index=False)
 
 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7

  • 12
    点赞
  • 86
    收藏
    觉得还不错? 一键收藏
  • 9
    评论
评论 9
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值