评分卡模型开发-定量特征筛选

在模型开发中,并不是所有的特征要全部筛选进模型,因为金融数据一般特征有很多,如果全部放入模型,一方面可能会引起“维度灾难”,另一方面得到的结果也许并不是最好的,因为有些特征之间的相关性较强。所以我们有必要对特征进行一定程度的筛选.数据的话可以去评分卡模型开发-数据集缺失值处理下载

import pandas as pd
import os
os.chdir("C:\\Users\\Administrator\\OneDrive\\步履不停\\评分卡制作\\数据")
df = pd.read_csv(".\\GermanCredit.csv",index_col=0)
df.head()

#将违约样本用"1"表示,正常样本用0表示
import numpy as np
df['credit_risk'] = df['credit_risk'].apply(lambda x:np.where(x=='good',0,1))

#获取定量指标
df.info()

continuous_vars = []
category_vars = []
for i in df.columns: 
    if df[i].dtype=='int64': #判断条件依据df.info()的结果而定
        continuous_vars.append(i)
    else:
        category_vars.append(i) 

X = df.loc[:,continuous_vars[:-1]]
X.head()

y = df.loc[:,continuous_vars[-1]]
y.head()

至此,我们将数据源中的所有特征分为了定量和定性,接下来我们讲讲怎么在python中选取定量特征

  • 通过随机森林判断特征的重要性
from sklearn.ensemble import RandomForestClassifier
#无需对基于树的模型做标准化或归一化处理
forest = RandomForestClassifier(n_estimators=10000,random_state=0,n_jobs=-1)
forest.fit(X,y)
importances=forest.feature_importances_
importances

得到如下结果:

array([ 0.18996948,  0.34514053,  0.06920705,  0.07587584,  0.2470823 ,
        0.04564897,  0.02707582])

接下来我们利用numpy中argsort函数得到imoortances中从大到小排列的索引值,并根据索引值将每个特征的重要性值排列出来

indices=np.argsort(importances)[::-1]
feat_labels=X.columns
for f in range(X.shape[1]):
    print("%2d) %-*s %f " %(f+1,30,feat_labels[f],importances[indices[f]]))

得到如下结果:该结果是根据均值精度下降法得出来的

1) duration                       0.345141 
 2) amount                         0.247082 
 3) installment_rate               0.189969 
 4) present_residence              0.075876 
 5) age                            0.069207 
 6) number_credits                 0.045649 
 7) people_liable                  0.027076 

最后我们可以将其可视化:

import matplotlib.pyplot as plt
%matplotlib inline
plt.title('Feature Importances')
plt.bar(range(X.shape[1]),importances[indices],color='lightblue',align='center')
plt.xticks(range(X.shape[1]),feat_labels,rotation=90)
plt.xlim([-1,X.shape[1]])
plt.tight_layout()

《评分卡模型开发-定量特征筛选》 1.png

    原文作者:鸣人吃土豆
    原文地址: https://www.jianshu.com/p/6bba76e750f4
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞