1. 代碼
- 基于jupyter notebook
#導包
import numpy as np
import math
import pandas as pd
from sklearn.utils.multiclass import type_of_target
from scipy import stats
#求woe值和iv值
def woe(X, y, event):
res_woe = [] #列表存放woe字典
res_iv = [] #列表存放iv
X1 = feature_discretion(X) #對連續(xù)型特征進行處理
for i in range(0, X1.shape[-1]): #遍歷所有特征
x = X1[:, i] #單個特征
woe_dict, iv1 = woe_single_x(x, y, event) #計算單個特征的woe值
res_woe.append(woe_dict)
res_iv.append(iv1)
return np.array(res_woe), np.array(res_iv) #返回數(shù)組
#求單個特征的woe值
def woe_single_x(x, y, event):
event_total, non_event_total = count_binary(y, event) #計算好人壞人總數(shù)
x_labels = np.unique(x) #特征中的分段
woe_dict = {} #存放每個分段的名稱 以及 其對應(yīng)的woe值
iv = 0
for x1 in x_labels: #遍歷每個分段
y1 = y[np.where(x == x1)[0]]
event_count, non_event_count = count_binary(y1, event=event)
rate_event = 1.0 * event_count / event_total
rate_non_event = 1.0 * non_event_count / non_event_total
#woe無窮大時處理
if rate_event == 0:
print()#print("{'",x1,"'}"+":全是好人") #只輸出不做處理
elif rate_non_event == 0:
print()#print("{'",x1,"'}"+":全是壞人")
else:
woe1 = math.log(rate_event / rate_non_event)
woe_dict[x1] = woe1
iv += (rate_event - rate_non_event) * woe1
return woe_dict, iv
#計算個數(shù)
def count_binary(a, event):
event_count = (a == event).sum()
non_event_count = a.shape[-1] - event_count
return event_count, non_event_count
#判斷特征數(shù)據(jù)是否為離散型
def feature_discretion(X):
temp = []
for i in range(0, X.shape[-1]):
x = X[:, i]
x_type = type_of_target(x)
if pd.Series(list(x)).dtype != 'O':
x1 = discrete(x)
temp.append(x1)
else:
temp.append(x)
return np.array(temp).T
#對連續(xù)型特征進行離散化
def discrete(x):
res = np.array([0] * x.shape[-1], dtype=int)
for i in range(5):
point1 = stats.scoreatpercentile(x, i * 20)
point2 = stats.scoreatpercentile(x, (i + 1) * 20)
x1 = x[np.where((x >= point1) & (x <= point2))]
mask = np.in1d(x, x1)
res[mask] = (i + 1)
return res
2. 數(shù)據(jù)
- 讀取數(shù)據(jù)
df = pd.read_csv("telephone_test.csv") - 目標變量
y=df['status'].values - 所有特征
X=df.drop(['status','sid', 'uid'],axis=1).values
3. 結(jié)果
- 將特征的IV值和特征構(gòu)建成字典并按IV值對特征進行排序
dic = dict(zip(a,b)) #a為IV值列表彤蔽,b為特征列表
dic_sort= sorted(dic.items(),key = lambda x:x[1],reverse = True) -
部分截圖