import numpy as np
import pandas as pd
data = pd.read_csv('./cs-training.csv')
data = data.iloc[:,1:]
data.head() #默认显示前五行数据
预览数据
可见,特征量MonthlyIncome有29731个缺失值,NumberOfDependents有3924个缺失值。
为方便理解,将英文字段转换成中文字段
states={'SeriousDlqin2yrs':'好坏客户',
'RevolvingUtilizationOfUnsecuredLines':'可用额度比值',
'age':'年龄',
'NumberOfTime30-59DaysPastDueNotWorse':'逾期30-59天笔数',
'DebtRatio':'负债率',
'MonthlyIncome':'月收入',
'NumberOfOpenCreditLinesAndLoans':'信贷数量',
'NumberOfTimes90DaysLate':'逾期90天笔数',
'NumberRealEstateLoansOrLines':'固定资产贷款量',
'NumberOfTime60-89DaysPastDueNotWorse':'逾期60-89天笔数',
'NumberOfDependents':'家属数量'}
df.rename(columns=states,inplace=True)
df.head() #修改英文字段名为中文字段名
# 0对应好客户,1对应坏客户
print("重复值的数量:", data.shape[0] - data.drop_duplicates().shape[0])
data = data.drop_duplicates()
for var in data.columns:
print("%s缺失值的占比为%.2f%%" % (var, 100*(df[var].isnull().sum()/df.shape[0])))
SeriousDlqin2yrs缺失值的占比为0.00%
RevolvingUtilizationOfUnsecuredLines缺失值的占比为0.00%
age缺失值的占比为0.00%
NumberOfTime30-59DaysPastDueNotWorse缺失值的占比为0.00%
DebtRatio缺失值的占比为0.00%
MonthlyIncome缺失值的占比为19.56%
NumberOfOpenCreditLinesAndLoans缺失值的占比为0.00%
NumberOfTimes90DaysLate缺失值的占比为0.00%
NumberRealEstateLoansOrLines缺失值的占比为0.00%
NumberOfTime60-89DaysPastDueNotWorse缺失值的占比为0.00%
NumberOfDependents缺失值的占比为2.56%
月收入MonthlyIncome的缺失率比较大,所以采用随机森林法进行填补。
def set_missing(df):
# 把已有的数值型特征取出来
process_df = df.ix[:,[5,0,1,2,3,4,6,7,8,9]]
# 分成已知该特征和未知该特征两部分
known = process_df[process_df.MonthlyIncome.notnull()].as_matrix()
unknown = process_df[process_df.MonthlyIncome.isnull()].as_matrix()
# X为特征属性值
X = known[:, 1:]
# y为结果标签值
y = known[:, 0]
# fit到RandomForestRegressor之中
rfr = RandomForestRegressor(random_state=0,
n_estimators=200,max_depth=3,n_jobs=-1)
rfr.fit(X,y)
# 用得到的模型进行未知特征值预测
predicted = rfr.predict(unknown[:, 1:]).round(0)
print(predicted)
# 用得到的预测结果填补原缺失数据
df.loc[(df.MonthlyIncome.isnull()), 'MonthlyIncome'] = predicted
return df
家庭成员NumberOfDependents变量缺失值比较少,可以直接删除,对总体模型不会造成太大影响。
# 缺失值删除
data=data.dropna()
# 选出 3,7,9做箱线图,选出年龄来做图观察
import matplotlib.pyplot as plt#导入图像库
%matplotlib inline
data_box = data.iloc[:,[3,7,9]]
data_box.boxplot()