IV(Information Value), 衡量特征包含预测变量浓度的一种指标
特征信息度解构:
其中Gi,Bi表示箱i中好坏样本占全体好坏样本的比例。
WOE表示两类样本分布的差异性。
(Gi-Bi):衡量差异的重要性。
特征信息度的作用
选择变量:
非负指标
高IV表示该特征和目标变量的关联度高
目标变量只能是二分类
过高的IV,可能有潜在的风险
特征分箱越细,IV越高
常用的阈值有:
<=0.02: 没有预测性,不可用
0.02 to 0.1: 弱预测性
0.1 to 0.2: 有一定的预测性
0.2 +: 高预测性
注意上面说的IV是指一个变量里面所有箱的IV之和。
计算WOE和IV代码:
def CalcWOE(df, col, target):
'''
:param df: dataframe containing feature and target
:param col: 注意col这列已经经过分箱了,现在计算每箱的WOE和总的IV。
:param target: good/bad indicator
:return: 返回每箱的WOE(字典类型)和总的IV之和。
'''
total = df.groupby([col])[target].count()
total = pd.DataFrame({'total': total})
bad = df.groupby([col])[target].sum()
bad = pd.DataFrame({'bad': bad})
regroup = total.merge(bad, left_index=True, right_index=True, how='left')
regroup.reset_index(level=0, inplace=True)
N = sum(regroup['total'])
B = sum(regroup['bad'])
regroup['good'] = regroup['total'] - regroup['bad']
G = N - B
regroup['bad_pcnt'] = regroup['bad'].map(lambda x: x*1.0/B)
regroup['good_pcnt'] = regroup['good'].map(lambda x: x * 1.0 / G)
regroup['WOE'] = regroup.apply(lambda x: np.log(x.good_pcnt*1.0/x.bad_pcnt),axis = 1)
WOE_dict = regroup[[col,'WOE']].set_index(col).to_dict(orient='index')
IV = regroup.apply(lambda x: (x.good_pcnt-x.bad_pcnt)*np.log(x.good_pcnt*1.0/x.bad_pcnt),axis = 1)
IV = sum(IV)
return {"WOE": WOE_dict, 'IV':IV}