2.8 WOE与IV值计算实战:特征筛选的黄金标准,附完整代码
2.8 WOE与IV值计算实战:特征筛选的黄金标准,附完整代码
引言
WOE(Weight of Evidence)和IV(Information Value)是评分卡模型中特征筛选的黄金标准。WOE用于特征转换,IV用于特征筛选。本文将提供完整的WOE和IV值计算代码,帮你掌握特征筛选的核心技能。
一、WOE和IV原理
1.1 WOE定义
WOE = ln(坏样本占比 / 好样本占比)
1.2 IV定义
IV = Σ(坏样本占比 - 好样本占比) × WOE
二、完整实现代码
2.1 WOE计算函数
# WOE计算完整代码
import pandas as pd
import numpy as np
def calculate_woe_iv(data, feature, target, n_bins=5, method='qcut'):
"""
计算WOE和IV值
参数:
data: DataFrame,包含特征和目标变量
feature: 特征列名
target: 目标变量列名(0/1,1表示坏样本)
n_bins: 分箱数量
method: 分箱方法,'qcut'等频分箱,'cut'等距分箱
返回:
woe_iv_df: 包含分箱、WOE、IV的DataFrame
total_iv: 总IV值
"""
# 复制数据
df = data[[feature, target]].copy()
# 分箱
if method == 'qcut':
df['bin'] = pd.qcut(df[feature], q=n_bins, duplicates='drop')
else:
df['bin'] = pd.cut(df[feature], bins=n_bins, duplicates='drop')
# 计算每箱统计
bin_stats = df.groupby('bin').agg({
target: ['count', 'sum']
})
bin_stats.columns = ['total', 'bad']
bin_stats['good'] = bin_stats['total'] - bin_stats['bad']
# 计算总体好坏样本数
total_bad = bin_stats['bad'].sum()
total_good = bin_stats['good'].sum()
# 计算占比
bin_stats['bad_rate'] = bin_stats['bad'] / total_bad
bin_stats['good_rate'] = bin_stats['good'] / total_good
# 避免除零
bin_stats['bad_rate'] = bin_stats['bad_rate'].replace(0, 0.0001)
bin_stats['good_rate'] = bin_stats['good_rate'].replace(0, 0.0001)
# 计算WOE
bin_stats['woe'] = np.log(bin_stats['bad_rate'] / bin_stats['good_rate'])
# 计算IV
bin_stats['iv'] = (bin_stats['bad_rate'] - bin_stats['good_rate']) * bin_stats['woe']
# 计算特征统计
bin_stats['min'] = df.groupby('bin')[feature].min()
bin_stats['max'] = df.groupby('bin')[feature].max()
bin_stats['mean'] = df.groupby('bin')[feature].mean()
total_iv = bin_stats['iv'].sum()
return bin_stats, total_iv
# 使用示例
from sklearn.datasets import make_classification
# 生成示例数据
X, y = make_classification(n_samples=1000, n_features=1, n_informative=1,
n_redundant=0, random_state=42)
df = pd.DataFrame({'feature': X.flatten(), 'target': y})
# 计算WOE和IV
woe_iv_df, total_iv = calculate_woe_iv(df, 'feature', 'target', n_bins=5)
print("WOE和IV计算结果:")
print(woe_iv_df)
print(f"\\n总IV值: {total_iv:.4f}")
2.2 IV值评估标准
# IV值评估标准
def iv_evaluation(iv_value):
"""
IV值评估标准
"""
if iv_value < 0.02:
return "无预测能力,建议删除"
elif iv_value < 0.1:
return "预测能力较弱"
elif iv_value < 0.3:
return "预测能力中等,可以使用"
elif iv_value < 0.5:
return "预测能力较强"
else:
return "预测能力很强,但需检查是否有数据问题"
print("IV值评估:")
for iv in [0.01, 0.05, 0.15, 0.25, 0.4, 0.6]:
print(f" IV={iv:.2f}: {iv_evaluation(iv)}")
2.3 批量计算IV值
# 批量计算IV值
def batch_calculate_iv(data, features, target, n_bins=5):
"""
批量计算多个特征的IV值
"""
iv_results = []
for feature in features:
try:
_, total_iv = calculate_woe_iv(data, feature, target, n_bins=n_bins)
iv_results.append({
'feature': feature,
'iv': total_iv,
'evaluation': iv_evaluation(total_iv)
})
except Exception as e:
iv_results.append({
'feature': feature,
'iv': np.nan,
'evaluation': f'计算失败: {str(e)}'
})
iv_df = pd.DataFrame(iv_results).sort_values('iv', ascending=False)
return iv_df
# 使用示例
print("\\n批量IV值计算:")
# 假设有多个特征
# iv_df = batch_calculate_iv(df, ['feature1', 'feature2', ...], 'target')
# print(iv_df)
三、WOE转换
3.1 WOE值替换
# WOE值替换
def woe_transform(data, feature, woe_dict):
"""
将特征值替换为WOE值
"""
def get_woe(value):
for bin_range, woe in woe_dict.items():
if isinstance(bin_range, pd.Interval):
if bin_range.left < value <= bin_range.right:
return woe
return np.nan
return data[feature].apply(get_woe)
# 使用示例
print("WOE转换函数已准备")
四、总结与思考
4.1 核心要点
WOE计算:基于分箱的好坏样本占比IV值计算:衡量特征预测能力评估标准:IV值>0.1有预测能力应用:特征筛选和WOE转换
4.2 思考题
如何选择合适的分箱数量?如何处理缺失值?如何优化WOE转换?
4.3 实践建议
分箱策略:根据数据分布选择分箱方法IV阈值:通常选择IV>0.1的特征WOE转换:用于逻辑回归模型持续优化:根据模型效果调整
下一节预告:我们将学习字段分箱技术详解,连续变量离散化,提升模型效果的关键步骤。