python計算iv值 python計算IV值

2021-10-13 07:50:05 字數 2514 閱讀 2555

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) #對連續型特徵進行處理

for i in range(0, x1.shape[-1]): #遍歷所有特徵

x = x1[:, i] #單個特徵

woe_dict, iv1 = woe_single_x(x, y, event) #計算單個特徵的woe值

return np.array(res_woe), np.array(res_iv) #返回陣列

#求單個特徵的woe值

def woe_single_x(x, y, event):

event_total, non_event_total = count_binary(y, event) #計算好人壞人總數

x_labels = np.unique(x) #特徵中的分段

woe_dict = {} #存放每個分段的名稱 以及 其對應的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(""+":全是好人") #只輸出不做處理

elif rate_non_event == 0:

print()#print(""+":全是壞人")

else:

woe1 = math.log(rate_event / rate_non_event)

woe_dict[x1] = woe1

iv += (rate_event - rate_non_event) * woe1

return woe_dict, iv

#計算個數

def count_binary(a, event):

event_count = (a == event).sum()

non_event_count = a.shape[-1] - event_count

return event_count, non_event_count

#判斷特徵資料是否為離散型

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)

else:

return np.array(temp).t

#對連續型特徵進行離散化

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. 資料

讀取資料

df = pd.read_csv("telephone_test.csv")

目標變數

y=df['status'].values

所有特徵

x=df.drop(['status','sid', 'uid'],axis=1).values

3. 結果

將特徵的iv值和特徵構建成字典並按iv值對特徵進行排序

dic = dict(zip(a,b)) #a為iv值列表,b為特徵列表

dic_sort= sorted(dic.items(),key = lambda x:x[1],reverse = true)

部分截圖

python計算iv值 python計算IV值

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 ...

python機器學習 IV值 WOE值的計算

評分卡模型中的iv和woe詳解 看完後,一定要注意 iv衡量的是某乙個變數的資訊量,從公式來看的話,相當於是自變數woe值的乙個加權求和,其值的大小決定了自變數對於目標變數的影響程度,對於分組 i 其對應的iv值參考下圖,其中n是分組個數,注意,在變數的任何分組中,不應該出現響應數為0或非響應數字0...

IV值的計算邏輯

在建模的時候,我們對會單個變數的 能力進行 主要使用iv值這個指標,iv值的 能力如下 iv 0.02 無 能力 0.02 0.1 弱 能力 0.1 0.3 中 能力 0.3 0.5 強 能力 大於0.5的為超強 能力 iv值的計算公式 pgood section total 分箱好使用者與整體好使...