title: “Learning R—smbinning”
author: “刘栋”
date: “2018年4月5日”
output: word_document
knitr::opts_chunk$set(echo = TRUE)
这个包主要是进行woe分组时候用的,有比较丰富的函数可以用。简单介绍其中两个函数,最优分箱和自定义分箱。业务希望可以自动寻参,虽然实际用的时候,自动分箱经常无解,但是也可以通过手动设置阈值来作为参考。
Intro
对R的版本有要求,3.4.0以上。升级R的话用installr倒是可以,但是默认是升级到最新版本。最新版本的R,RStudio又不支持,所以还是很坑的。
最优分箱
评分卡模型中需要对数值型连续变量进行分箱处理,这一过程又称为有监督的离散化。这里最优分箱采用的算法是条件推断决策树(Conditional Inference Tree)。该算法开始排除缺失值进行分割点的寻找,最后计算IV值时,会考虑缺失值。
函数形式
library(smbinning)
smbinning(df, y, x, p = 0.05)
其中各个参数的意义如下:
- df 数据框
- y 响应变量(0,1),必须是整数且变量名不能包含"."
- x 连续性变量,至少5个不同的值且变量名不能包含"."
- p 每组样本占比,默认5%,即分箱之后每组样本数不能小于5%。该参数区间为0-0.5
Examples
# Load library and its dataset
library(smbinning) # Load package and its data
# Example: Optimal binning
result=smbinning(df=chileancredit,y="fgood",x="cbs1") # Run and save result
分组情况和IV值的计算
result$ivtable # Tabulation and Information Value
这里woe的计算:
ln
(
G
i
/
G
t
o
t
a
l
)
ln
(
B
i
/
B
t
o
t
a
l
)
\frac{{\ln \left( {{G_i}/{G_{total}}} \right)}}{{\ln \left( {{B_i}/{B_{total}}} \right)}}
ln(Bi/Btotal)ln(Gi/Gtotal)
G
i
G_i
Gi为第
i
i
i组中好用户(未违约)的数量,
G
t
o
t
a
l
G_{total}
Gtotal为所有好用户的数量
B
i
B_i
Bi为第
i
i
i组中坏用户(违约)的数量,
B
t
o
t
a
l
B_{total}
Btotal为所有坏用户的数量
WOE可以理解为当前分组中好用户占所有好用户的比例和坏用户占所有坏用户的比例的差异,如果差异越大,说明这个组别的区分能力越强。比如woe越大,该段用户的违约风险就越低
IV值的计算:
(
G
i
G
t
o
t
a
l
−
B
i
B
t
o
t
a
l
)
∗
ln
(
G
i
/
G
t
o
t
a
l
)
ln
(
B
i
/
B
t
o
t
a
l
)
\left( {\frac{{{G_i}}}{{{G_{total}}}} - \frac{{{B_i}}}{{{B_{total}}}}} \right) * \frac{{\ln \left( {{G_i}/{G_{total}}} \right)}}{{\ln \left( {{B_i}/{B_{total}}} \right)}}
(GtotalGi−BtotalBi)∗ln(Bi/Btotal)ln(Gi/Gtotal)
一般而言,IV值小于0.02认为变量没有什么价值,0.1-0.3预测力中等,0.3以上预测能力强。IV值相当与WOE的修正,比如分子分母差很多,woe会很小,但是IV值会偏大些,因为有个乘积项。
还有下面几个返回结果,不多说
result$iv # Information value
result$bands # Bins or bands
result$ctree # Decision tree
自定义分箱
library(smbinning)
smbinning(df, y, x, cuts)
- cuts 人为给定的分割点
看一个例子,输出和最优分箱一致:
# Load library and its dataset
library(smbinning) # Load package and its data
# Custom cutpoints using percentiles (20% each)
cbs1cuts=as.vector(quantile(chileancredit$cbs1, probs=seq(0,1,0.2), na.rm=TRUE)) # Quantiles
cbs1cuts=cbs1cuts[2:(length(cbs1cuts)-1)] # Remove first (min) and last (max) values
# Example: Customized binning
result=smbinning.custom(df=chileancredit,y="fgood",x="cbs1",cuts=cbs1cuts) # Run and save
result$ivtable # Tabulation and Information Value
Summary
还有数据探索、画图的函数,总体比较简单,可以看help。
2018-04-05 于杭州