Forked from danyashorokh/[Python] Information value calculation
Created
January 14, 2020 16:17
-
-
Save lakshay92-cyber/d7d711e07b24b25baa29c6c182226b0b to your computer and use it in GitHub Desktop.
[Python] Information value calculation
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import pandas as pd | |
# Calculate information value | |
def calc_iv(df, feature, target, pr=0): | |
lst = [] | |
for i in range(df[feature].nunique()): | |
val = list(df[feature].unique())[i] | |
lst.append([feature, val, df[df[feature] == val].count()[feature], df[(df[feature] == val) & (df[target] == 1)].count()[feature]]) | |
data = pd.DataFrame(lst, columns=['Variable', 'Value', 'All', 'Bad']) | |
data = data[data['Bad'] > 0] | |
data['Share'] = data['All'] / data['All'].sum() | |
data['Bad Rate'] = data['Bad'] / data['All'] | |
data['Distribution Good'] = (data['All'] - data['Bad']) / (data['All'].sum() - data['Bad'].sum()) | |
data['Distribution Bad'] = data['Bad'] / data['Bad'].sum() | |
data['WoE'] = np.log(data['Distribution Good'] / data['Distribution Bad']) | |
data['IV'] = (data['WoE'] * (data['Distribution Good'] - data['Distribution Bad'])).sum() | |
data = data.sort_values(by=['Variable', 'Value'], ascending=True) | |
if pr == 1: | |
print(data) | |
return data['IV'].values[0] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment