Kaggle---信用卡客户违约预测(2)

参考:https://blog.csdn.net/zllnau66/article/details/81742798

https://zhuanlan.zhihu.com/p/33931960

前面一节对数据进行了基本的数据清洗步骤,将一些没有意义的数据及逆行了划分和归类。这节,将对特征进行处理。

分别对离散特征和连续型特征进行处理。

离散特征有:性别、教育、婚姻、PAY_0,2,3,4,5,6

处理离散特征时候:

连续型特征有:LIMIT_BAL、年龄、BILL_AMT1,2,3,4,5,6 、PAY_AMT1,2,3,4,5,6

#对于离散型数据,对其获取哑变量(性别变量不具备顺序特征)dummies_sex=pd.get_dummies(train["SEX"],prefix="sex") #prefix代表哑变量前缀名称

dummies_sex

对教育变量也进行这样的处理

dummies_education=pd.get_dummies(train["EDUCATION"],prefix="EDUCATION") 

dummies_education


处理连续特征时候:

train.columns 可以用来查看所有列的名称

#对于连续型数据,看偏度,一般大于0.75的数值做一个log转化,使之尽量符合正态分布,因为很多模型的假设数据是服从正态分布的.BILL_AMT1,2,3,4,5,6 这几个变量存在负值,因此不可以使用Log直接对其进行标准化处理。

for i in cont_col: 

    print(i+":"+str(train[i].skew()))  

连续变量的偏度全部大于0.75,将这些变量全部进行对数化处理

log1p = log(x+1)

for i in cont_col:

    train[i]=np.log1p(train[i])

#将连续数据进行log处理

再对连续型数据进行标准化

scaled=preprocessing.scale(train[cont_col])scaled=pd.DataFrame(scaled,columns=cont_col)

scaled

m=dummies.join(scaled)data_cleaned=data[id_col].join(m)data_cleaned #合并数据集

在对非数值型特征进行onehot编码时需要先通过LabelEncoder()将分类变量转换成整数形式,然后通过OneHotEncoder()进行编码

 #将不同类别的列变量进行归类,id为主键识别列。

id_col=['ID']

cat_col1=['SEX',"MARRIAGE"]

#cat_col1为离散数据,且无顺序

#cat_col2为离散数据,但是存在顺序

cat_col2=['EDUCATION',"PAY_0",'PAY_2','PAY_3','PAY_4','PAY_5','PAY_6']

#这里是离散型无序,如果有序,请参考map用法,一些博客上有写

cont_col=['LIMIT_BAL','AGE','BILL_AMT1','BILL_AMT2','BILL_AMT3','BILL_AMT4','BILL_AMT5','BILL_AMT6','PAY_AMT1','PAY_AMT2','PAY_AMT3','PAY_AMT4','PAY_AMT5','PAY_AMT6']

#这里是数值型print (train[cat_col]) #这里是离散型的数据部分


去掉和添加行(axis=0),列(axis=1)

df1.drop(["handsome","smart"],axis=1,inplace=True)

train=train.join(a)

将train和a进行拼接 形成新的train

经过哑变量处理以及 标准化和log处理之后得到清洗之后的数据。用清洗后的数据观察相关系数。

train.corr()

#相关性的热力图

def corr_heat(df):

    dfData = abs(df.corr())#相关系数取绝对值

    plt.subplots(figsize=(9, 9)) # 设置画面大小

    sns.heatmap(dfData, annot=True, vmax=1, square=True, cmap="Blues")#热力图

  # plt.savefig('./BluesStateRelation.png')

    plt.show()

corr_heat(train)

用xgboost来输出特征重要性

from sklearn.model_selection import train_test_split

from sklearn import metrics

from xgboost.sklearn import XGBClassifier

y = train["default.payment.next.month"]x=train.drop(["default.payment.next.month"],axis=1)

X_train, X_test, y_train, y_test = train_test_split(x, y, test_size=0.3, random_state=0)##test_size测试集合所占比例clf = XGBClassifier(silent=0 ,learning_rate= 0.3,min_child_weight=1,max_depth=6, gamma=0.1, subsample=1, max_delta_step=1,colsample_bytree=1, reg_lambda=1.2, n_estimators=100, seed=1000) clf.fit(X_train,y_train,eval_metric='auc')y_true, y_pred = y_test, clf.predict(X_test)metrics.accuracy_score(y_true, y_pred)#print("Accuracy : %.4g") % 

from xgboost import plot_importance

from matplotlib import pyplot as plt

plot_importance(clf)

plt.show()

#print("Accuracy : %.4g") %


随机森林输出特征重要性 

from sklearn.ensemble import RandomForestRegressor

import numpy as np

rf = RandomForestRegressor()

names=['LIMIT_BAL', 'AGE', 'PAY_0', 'PAY_2', 'PAY_3', 'PAY_4', 'PAY_5', 'PAY_6', 'PAY_AMT1', 'PAY_AMT2', 'PAY_AMT3', 'PAY_AMT4', 'PAY_AMT5','PAY_AMT6','BILL_AMT1', 'BILL_AMT2','BILL_AMT3', 'BILL_AMT4', 'BILL_AMT5', 'BILL_AMT6', 'SEX_1', 'SEX_2', 'EDUCATION_1', 'EDUCATION_2', 'EDUCATION_3', 'EDUCATION_4','MARRIAGE_1', 'MARRIAGE_2', 'MARRIAGE_3']

rf.fit(x,y)

print ("Features sorted by their score:")

print (sorted(zip(map(lambda x: round(x, 4), rf.feature_importances_), names),

            reverse=True))


结果如下:

Features sorted by their score:

[(0.1567, 'PAY_0'), (0.0757, 'AGE'), (0.065, 'BILL_AMT1'), (0.0597, 'LIMIT_BAL'), (0.0547, 'PAY_AMT2'), (0.0535, 'PAY_AMT6'), (0.0497, 'PAY_AMT1'), (0.0495, 'PAY_AMT3'), (0.0476, 'BILL_AMT6'), (0.0466, 'PAY_AMT4'), (0.0454, 'BILL_AMT2'), (0.0446, 'PAY_AMT5'), (0.0438, 'BILL_AMT3'), (0.0425, 'BILL_AMT4'), (0.0417, 'BILL_AMT5'), (0.032, 'PAY_2'), (0.011, 'PAY_4'), (0.0101, 'PAY_5'), (0.0096, 'PAY_6'), (0.0089, 'PAY_3'), (0.0082, 'EDUCATION_2'), (0.0079, 'EDUCATION_1'), (0.0072, 'EDUCATION_3'), (0.0064, 'SEX_1'), (0.0064, 'MARRIAGE_1'), (0.0062, 'MARRIAGE_2'), (0.0061, 'SEX_2'), (0.0021, 'MARRIAGE_3'), (0.0012, 'EDUCATION_4')]

根据随机森林输出的结果,选取变量PAY_0AGE,BILL_AMT1,LIMIT_BAL,PAY_AMT2,PAY_AMT6,PAY_AMT1,PAY_AMT3,BILL_AMT6,PAY_AMT4, BILL_AMT2,PAY_AMT5,BILL_AMT3,BILL_AMT4,BILL_AMT5,PAY_2进行建模。

对测试集数据进行了同样的处理方式,用16 个变量进行了建模以及预测。首先使用了逻辑回归模型如下:

#-*- coding: utf-8 -*-

#逻辑回归 自动建模

#参数初始化

lr = LR() #建立逻辑回归模型

lr.fit(X, y) #用筛选后的特征数据来训练模型

print(u'逻辑回归模型训练结束。')

print(u'模型的平均正确率为:%s' % lr.score(X, y))


tx=pd.DataFrame(test['PAY_0'])

for i in feature_select:

    tx=tx.join(test[i])

predict=lr.predict(tx)

predict=pd.DataFrame(predict)

predict.to_csv("predict.csv",index=None)

#预测结束

你可能感兴趣的:(Kaggle---信用卡客户违约预测(2))