1. 程式人生 > >【資料建模 IV】特徵資訊度

【資料建模 IV】特徵資訊度

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}