机器学习训练营——机器学习爱好者的自由交流空间(入群联系qq:2279055353)

这是“银行客户交易行为预测”的第三篇文章,我们将建立LightGBM模型预测客户交易行为。结果的交叉验证分数显示,该模型预测效果比较理想。

准备工作

加载包

import gc
import os
import logging
import datetime
import warnings
import numpy as np
import pandas as pd
import seaborn as sns
import lightgbm as lgb
from tqdm import tqdm_notebook
import matplotlib.pyplot as plt
from sklearn.metrics import mean_squared_error
from sklearn.metrics import roc_auc_score, roc_curve
from sklearn.model_selection import StratifiedKFold
warnings.filterwarnings('ignore')

加载数据

IS_LOCAL = False
if(IS_LOCAL):PATH="e:/kaggle_exercises/santander/input/Santander/"
else:PATH="e:/kaggle_exercises/santander/input/"
os.listdir(PATH)
train_df = pd.read_csv(PATH+"train.csv")
test_df = pd.read_csv(PATH+"test.csv")

数据探索

检查数据

train_df.shape, test_df.shape
train_df.head()
test_df.head()

训练集包括的特征:ID_code, target, 200个数值变量(var_0 to var_199). 检验集包括的特征:ID_code, 200个数值变量(var_0 to var_199).

我们检查数据集里是否有缺失值,也检查数据类型。

def missing_data(data):total = data.isnull().sum()percent = (data.isnull().sum()/data.isnull().count()*100)tt = pd.concat([total, percent], axis=1, keys=['Total', 'Percent'])types = []for col in data.columns:dtype = str(data[col].dtype)types.append(dtype)tt['Types'] = typesreturn(np.transpose(tt))
missing_data(train_df)
missing_data(test_df)

结果显示,训练集与检验集里没有缺失值。现在,我们检查一下训练集里target值的分布。

sns.countplot(train_df['target'])
plt.show()

print("There are {}% target values with 1".format(100 * train_df["target"].value_counts()[1]/train_df.shape[0]))

There are 10.049% target values with 1

target的1值只占约10%, 是不平衡的。

LightGBM模型

我们从训练集的列变量里扔掉ID_code and target, 组成特征列表。

features = [c for c in train_df.columns if c not in ['ID_code', 'target']]
target = train_df['target']

设置LightGBM模型的超参数。

param = {'bagging_freq': 5,'bagging_fraction': 0.4,'boost_from_average':'false','boost': 'gbdt','feature_fraction': 0.05,'learning_rate': 0.01,'max_depth': -1,  'metric':'auc','min_data_in_leaf': 80,'min_sum_hessian_in_leaf': 10.0,'num_leaves': 13,'num_threads': 8,'tree_learner': 'serial','objective': 'binary', 'verbosity': 1
}

使用交叉验证运行模型。

folds = StratifiedKFold(n_splits=10, shuffle=False, random_state=44000)
oof = np.zeros(len(train_df))
predictions = np.zeros(len(test_df))
feature_importance_df = pd.DataFrame()for fold_, (trn_idx, val_idx) in enumerate(folds.split(train_df.values, target.values)):print("Fold {}".format(fold_))trn_data = lgb.Dataset(train_df.iloc[trn_idx][features], label=target.iloc[trn_idx])val_data = lgb.Dataset(train_df.iloc[val_idx][features], label=target.iloc[val_idx])num_round = 1000000clf = lgb.train(param, trn_data, num_round, valid_sets = [trn_data, val_data], verbose_eval=1000, early_stopping_rounds = 3000)oof[val_idx] = clf.predict(train_df.iloc[val_idx][features], num_iteration=clf.best_iteration)fold_importance_df = pd.DataFrame()fold_importance_df["Feature"] = featuresfold_importance_df["importance"] = clf.feature_importance()fold_importance_df["fold"] = fold_ + 1feature_importance_df = pd.concat([feature_importance_df, fold_importance_df], axis=0)predictions += clf.predict(test_df[features], num_iteration=clf.best_iteration) / folds.n_splitsprint("CV score: {:<8.5f}".format(roc_auc_score(target, oof)))

CV score: 0.90022

检查特征重要性:

cols = (feature_importance_df[["Feature", "importance"]].groupby("Feature").mean().sort_values(by="importance", ascending=False)[:150].index)
best_features = feature_importance_df.loc[feature_importance_df.Feature.isin(cols)]plt.figure(figsize=(14,28))
sns.barplot(x="importance", y="Feature", data=best_features.sort_values(by="importance",ascending=False))
plt.title('Features importance (averaged/folds)')
plt.tight_layout()
plt.savefig('FI.png')

银行客户交易行为预测:LightGBM模型相关推荐

  1. LightGBM模型简单预测股票涨跌情况

    最近入迷研究各种股票分析的指标,一想不如用熟悉的Python帮忙搞一搞,顺便做了一个二分类预测模型,供大家参考学习,也欢迎有量化分析兴趣的朋友沟通交流! Python中使用akshare这个第三方库来 ...

  2. 天池案例赛--银行产品认购预测

    大赛是以银行产品认购预测为背景,根据记录的用户信息来推测该银行的用户是否会购买银行的产品. 赛题提供的数据集有3万条(训练集2.25万,测试集0.75万),包括20个特征变量,本文构建了XGBoost ...

  3. 广告点击率(CTR)预测经典模型 GBDT + LR 理解与实践(附数据 + 代码)

    CTR 系列文章: 广告点击率(CTR)预测经典模型 GBDT + LR 理解与实践(附数据 + 代码) CTR经典模型串讲:FM / FFM / 双线性 FFM 相关推导与理解 CTR深度学习模型之 ...

  4. 【算法竞赛学习】二手车交易价格预测-Task5模型融合

    二手车交易价格预测-Task5 模型融合 五.模型融合 Tip:此部分为零基础入门数据挖掘的 Task5 模型融合 部分,带你来了解各种模型结果的融合方式,在比赛的攻坚时刻冲刺Top,欢迎大家后续多多 ...

  5. 天池学习赛:工业蒸汽量预测4——模型验证

    上一篇<天池学习赛:工业蒸汽量预测3--模型训练>中已经是使用了几种机器学习的模型,接下来将介绍一些模型的评价方法. 目录 1 模型评估的方法 2 模型调参 3 赛题模型验证与调参 3.1 ...

  6. 天池学习赛:工业蒸汽量预测3——模型训练

    接上一篇<天池学习赛:工业蒸汽量预测2--特征工程> 数据划分: from sklearn.model_selection import train_test_split #切分数据new ...

  7. Kaggle泰坦尼克号生存预测挑战——模型建立、模型调参、融合

    Kaggle泰坦尼克号生存预测挑战 这是kaggle上Getting Started 的Prediction Competition,也是比较入门和简单的新人赛,我的最好成绩好像有进入top8%,重新 ...

  8. 【第十一届泰迪杯B题产品订单的数据分析与需求预测产品订单的数据分析与需求预测 】第二大问代码分享+解题思路(EDA数据再探索+LightGBM模型)

    [第十一届泰迪杯B题产品订单的数据分析与需求预测]第二大问代码分享+解题思路(EDA数据再探索+LightGBM模型) 写在前面: ​ 拖了这么长时间,一方面是我在找实习面试准备.另一方面是在做第二问 ...

  9. 数据挖掘算法中,预测类模型详解

    预测类模型根据被解释变量的度量类型,分为对连续变量建模的回归,对分类变量建模的分类器,其中以二分类器为主.这里的回归不是仅有线性回归,还有回归决策树.回归神经网络,甚至最近邻域(KNN)和支持向量机( ...

  10. CTR预测经典模型GBDT+LR

    CTR预测:点击率预测, 基本思想: GBDT 基于集成学习中的boosting思想,每次迭代都在减少残差的梯度方向新建立一颗决策树,迭代多少次就会生成多少颗决策树,不断减少误差.假设GBDT由两颗树 ...

最新文章

  1. Nature方法 | 三代长读长宏基因组组装软件metaFlye
  2. 基于机器学习逻辑回归算法完成癌症病人的肿瘤是否良性的判断
  3. Android之文件数据存储
  4. java list接口为何要重新声明collection接口的方法_JAVA Collection接口中List Map 和Set的区别(转)...
  5. Kafka 0.10.0文档翻译二
  6. Centos7下安装redis
  7. vue koa2即时聊天,实时推送比特币价格,爬取电影网站
  8. oracle数据库stuff的用法,sql STUFF用法
  9. 栈中对象定位的方式(句柄池,直接引用)
  10. pat1070. Mooncake (25)
  11. zjoi2018day1 游记
  12. C语言中的.h文件的作用
  13. 【原创】JS 数字转换成英文写法(包含小数)
  14. python与大数据分析实验报告_Python与大数据分析.pptx
  15. ScannerException: while scanning for the next token found character ‘@‘ 问题解决
  16. 抑郁症,莫要讳疾忌医。
  17. 文章来源于--英国《金融时报》中文网专栏作家丁学良 2008-09-19
  18. 通过logback-spring.xml配置,概述log4j与logback之间的使用
  19. U盘“文件或目录损坏且无法读取”
  20. 阿斯汤加瑜伽(Ashtanga Yoga)第一序列学习与实践笔记(十)

热门文章

  1. 【Git入门之二】基本术语
  2. NDK配置文件Android.mk简介
  3. 使用 JSONModel
  4. 在ASP.NET 中实现单点登录(利用Cache, 将用户信息保存在服务器缓存中)
  5. MPC模型预测控制器——数学推导
  6. PX4避障和轨迹规划(3DVFH*)
  7. IS-IS详解(十八)——IS-IS 缺省路由
  8. IdleHandler,页面启动优化神器
  9. SpringBoot 2.0参数校验Hibernate Validator
  10. java集合框架之Collection