https://blog.csdn.net/arsenal0435/article/details/80446829(原文连接)算法
1.本项目需解决的问题
本项目经过利用P2P平台Lending Club的贷款数据,进行机器学习,构建贷款违约预测模型,对新增贷款申请人进行预测是否会违约,从而决定是否放款。数组
2.建模思路
如下为本次项目的工做流程。app
3.场景解析
贷款申请人向Lending Club平台申请贷款时,Lending Club平台经过线上或线下让客户填写贷款申请表,收集客户的基本信息,这里包括申请人的年龄、性别、婚姻情况、学历、贷款金额、申请人财产状况等信息,一般来讲还会借助第三方平台如征信机构或FICO等机构的信息。经过这些信息属性来作线性回归 ,生成预测模型,Lending Club平台能够经过预测判断贷款申请是否会违约,从而决定是否向申请人发放贷款。dom
1)首先,咱们的场景是经过用户的历史行为(如历史数据的多维特征和贷款状态是否违约)来训练模型,经过这个模型对新增的贷款人“是否具备偿还能力,是否具备偿债意愿”进行分析,预测贷款申请人是否会发生违约贷款。这是一个监督学习的场景,由于已知了特征以及贷款状态是否违约(目标列),咱们断定贷款申请人是否违约是一个二元分类问题,能够经过一个分类算法来处理,这里选用逻辑斯蒂回归(Logistic Regression)。机器学习
2)观察数据集发现部分数据是半结构化数据,须要进行特征抽象。ide
现对该业务场景进行总结以下:性能
根据历史记录数据学习并对贷款是否违约进行预测,监督学习场景,选择逻辑斯蒂回归(Logistic Regression)算法。
数据为半结构化数据,须要进行特征抽象。学习
4.数据预处理(Pre-Processing Data)
本次项目数据集来源于Lending Club Statistics,具体为2018年第一季Lending Club平台发生借贷的业务数据。
数据预览测试
查看每列属性缺失值的比例
check_null = data.isnull().sum().sort_values(ascending=False)/float(len(data))
print(check_null[check_null > 0.2]) # 查看缺失比例大于20%的属性。
从上面信息能够发现,本次数据集缺失值较多的属性对咱们模型预测意义不大,例如id和member_id以及url等。所以,咱们直接删除这些没有意义且缺失值较多的属性。此外,若是缺失值对属性来讲是有意义的,还得细分缺失值对应的属性是数值型变量或是分类类型变量。
thresh_count = len(data)*0.4 # 设定阀值
data = data.dropna(thresh=thresh_count, axis=1) #若某一列数据缺失的数量超过阀值就会被删除
再将处理后的数据转化为csv
data.to_csv('loans_2018q1_ml.csv', index = False)
loans = pd.read_csv('loans_2018q1_ml.csv')
loans.dtypes.value_counts() # 分类统计数据类型
loans.shape
(107866, 103)
同值化处理
若是一个变量大部分的观测都是相同的特征,那么这个特征或者输入变量就是没法用来区分目标时间。
loans = loans.loc[:,loans.apply(pd.Series.nunique) != 1]
loans.shape
(107866, 96)
缺失值处理——分类变量
objectColumns = loans.select_dtypes(include=["object"]).columns
loans[objectColumns].isnull().sum().sort_values(ascending=False)
loans[objectColumns]
loans['int_rate'] = loans['int_rate'].str.rstrip('%').astype('float')
loans['revol_util'] = loans['revol_util'].str.rstrip('%').astype('float')
objectColumns = loans.select_dtypes(include=["object"]).columns
咱们能够调用missingno库来快速评估数据缺失的状况。
msno.matrix(loans[objectColumns]) # 缺失值可视化
从图中能够直观看出变量“last_pymnt_d”、“emp_title”、“emp_length”缺失值较多。
这里咱们先用‘unknown’来填充。
objectColumns = loans.select_dtypes(include=["object"]).columns
loans[objectColumns] = loans[objectColumns].fillna("Unknown")
缺失值处理——数值变量
numColumns = loans.select_dtypes(include=[np.number]).columns
pd.set_option('display.max_columns', len(numColumns))
loans[numColumns].tail()
loans.drop([107864, 107865], inplace =True)
这里使用可sklearn的Preprocessing模块,参数strategy选用most_frequent,采用众数插补的方法填充缺失值。
imr = Imputer(missing_values='NaN', strategy='most_frequent', axis=0) # axis=0 针对列来处理
imr = imr.fit(loans[numColumns])
loans[numColumns] = imr.transform(loans[numColumns])
这样缺失值就已经处理完。
数据过滤
print(objectColumns)
将以上重复或对构建预测模型没有意义的属性进行删除。
drop_list = ['sub_grade', 'emp_title', 'issue_d', 'title', 'zip_code', 'addr_state', 'earliest_cr_line',
'initial_list_status', 'last_pymnt_d', 'next_pymnt_d', 'last_credit_pull_d', 'disbursement_method']
loans.drop(drop_list, axis=1, inplace=True)
loans.select_dtypes(include = ['object']).shape
(107866, 8)
5.特征工程(Feature Engineering)
特征衍生
Lending Club平台中,"installment"表明贷款每个月分期的金额,咱们将'annual_inc'除以12个月得到贷款申请人的月收入金额,而后再把"installment"(月负债)与('annual_inc'/12)(月收入)相除生成新的特征'installment_feat',新特征'installment_feat'表明客户每个月还款支出占月收入的比,'installment_feat'的值越大,意味着贷款人的偿债压力越大,违约的可能性越大。
loans['installment_feat'] = loans['installment'] / ((loans['annual_inc']+1) / 12)
特征抽象(Feature Abstraction)
def coding(col, codeDict):
colCoded = pd.Series(col, copy=True)
for key, value in codeDict.items():
colCoded.replace(key, value, inplace=True)
return colCoded
#把贷款状态LoanStatus编码为违约=1, 正常=0:
loans["loan_status"] = coding(loans["loan_status"], {'Current':0,'Issued':0,'Fully Paid':0,'In Grace Period':1,'Late (31-120 days)':1,'Late (16-30 days)':1,'Charged Off':1})
print( '\nAfter Coding:')
pd.value_counts(loans["loan_status"])
贷款状态可视化
loans.select_dtypes(include=["object"]).head()
首先,咱们对变量“emp_length”、"grade"进行特征抽象化。
# 有序特征的映射
mapping_dict = {
"emp_length": {
"10+ years": 10,
"9 years": 9,
"8 years": 8,
"7 years": 7,
"6 years": 6,
"5 years": 5,
"4 years": 4,
"3 years": 3,
"2 years": 2,
"1 year": 1,
"< 1 year": 0,
"Unknown": 0
},
"grade":{
"A": 1,
"B": 2,
"C": 3,
"D": 4,
"E": 5,
"F": 6,
"G": 7
}
}
loans = loans.replace(mapping_dict)
loans[['emp_length','grade']].head()
再对剩余特征进行One-hot编码。
n_columns = ["home_ownership", "verification_status", "application_type","purpose", "term"]
dummy_df = pd.get_dummies(loans[n_columns]) # 用get_dummies进行one hot编码
loans = pd.concat([loans, dummy_df], axis=1) #当axis = 1的时候,concat就是行对齐,而后将不一样列名称的两张表合并
再清除掉原来的属性。
loans = loans.drop(n_columns, axis=1)
loans.info()
这样,就已经将全部类型为object的变量做了转化。
col = loans.select_dtypes(include=['int64','float64']).columns
col = col.drop('loan_status') #剔除目标变量
loans_ml_df = loans # 复制数据至变量loans_ml_df
特征缩放(Feature Scaling)
咱们采用的是标准化的方法,调用scikit-learn模块preprocessing的子模块StandardScaler。
sc =StandardScaler() # 初始化缩放器
loans_ml_df[col] =sc.fit_transform(loans_ml_df[col]) #对数据进行标准化
特征选择(Feature Selecting)
目的:首先,优先选择与目标相关性较高的特征;其次,去除不相关特征能够下降学习的难度。
#构建X特征变量和Y目标变量
x_feature = list(loans_ml_df.columns)
x_feature.remove('loan_status')
x_val = loans_ml_df[x_feature]
y_val = loans_ml_df['loan_status']
len(x_feature) # 查看初始特征集合的数量
103
首先,选出与目标变量相关性较高的特征。这里采用的是Wrapper方法,经过暴力的递归特征消除 (Recursive Feature Elimination)方法筛选30个与目标变量相关性最强的特征,逐步剔除特征从而达到首次降维,自变量从103个降到30个。
# 创建逻辑回归分类器
model = LogisticRegression()
# 创建递归特征消除筛选器
rfe = RFE(model, 30) #经过递归选择特征,选择30个特征
rfe = rfe.fit(x_val, y_val)
# 打印筛选结果
print(rfe.n_features_)
print(rfe.estimator_ )
print(rfe.support_)
print(rfe.ranking_) #ranking 为 1表明被选中,其余则未被表明未被选中
col_filter = x_val.columns[rfe.support_] #经过布尔值筛选首次降维后的变量
col_filter
Filter
在第一次降维的基础上,经过皮尔森相关性图谱找出冗余特征并将其剔除;同时,能够经过相关性图谱进一步引导咱们选择特征的方向。
colormap = plt.cm.viridis
plt.figure(figsize=(12,12))
plt.title('Pearson Correlation of Features', y=1.05, size=15)
sns.heatmap(loans_ml_df[col_filter].corr(),linewidths=0.1,vmax=1.0, square=True, cmap=colormap, linecolor='white', annot=True)
drop_col = ['funded_amnt', 'funded_amnt_inv', 'out_prncp', 'out_prncp_inv', 'total_pymnt_inv', 'total_rec_prncp',
'num_actv_rev_tl', 'num_rev_tl_bal_gt_0', 'home_ownership_RENT', 'application_type_Joint App',
'term_ 60 months', 'purpose_debt_consolidation', 'verification_status_Source Verified', 'home_ownership_OWN',
'verification_status_Verified',]
col_new = col_filter.drop(drop_col) #剔除冗余特征
len(col_new) # 特征子集包含的变量从30个降维至15个。
15
Embedded
下面须要对特征的权重有一个正确的评判和排序,能够经过特征重要性排序来挖掘哪些变量是比较重要的,下降学习难度,最终达到优化模型计算的目的。这里,咱们采用的是随机森林算法断定特征的重要性,工程实现方式采用scikit-learn的featureimportances 的方法。
names = loans_ml_df[col_new].columns
clf=RandomForestClassifier(n_estimators=10,random_state=123) #构建分类随机森林分类器
clf.fit(x_val[col_new], y_val) #对自变量和因变量进行拟合
for feature in zip(names, clf.feature_importances_):
print(feature)
plt.style.use('ggplot')
## feature importances 可视化##
importances = clf.feature_importances_
feat_names = names
indices = np.argsort(importances)[::-1]
fig = plt.figure(figsize=(20,6))
plt.title("Feature importances by RandomTreeClassifier")
plt.bar(range(len(indices)), importances[indices], color='lightblue', align="center")
plt.step(range(len(indices)), np.cumsum(importances[indices]), where='mid', label='Cumulative')
plt.xticks(range(len(indices)), feat_names[indices], rotation='vertical',fontsize=14)
plt.xlim([-1, len(indices)])
plt.show()
# 下图是根据特征在特征子集中的相对重要性绘制的排序图,这些特征通过特征缩放后,其特征重要性的和为1.0。
# 由下图咱们能够得出的结论:基于决策树的计算,特征子集上最具判别效果的特征是“total_pymnt”。
6.模型训练
处理样本不均衡
前面已提到,目标变量“loans_status”正常和违约两种类别的数量差异较大,会对模型学习形成困扰。咱们采用过采样的方法来处理样本不均衡问题,具体操做使用的是SMOTE(Synthetic Minority Oversampling Technique),SMOET的基本原理是:采样最邻近算法,计算出每一个少数类样本的K个近邻,从K个近邻中随机挑选N个样本进行随机线性插值,构造新的少数样本,同时将新样本与原数据合成,产生新的训练集。
# 构建自变量和因变量
X = loans_ml_df[col_new]
y = loans_ml_df["loan_status"]
n_sample = y.shape[0]
n_pos_sample = y[y == 0].shape[0]
n_neg_sample = y[y == 1].shape[0]
print('样本个数:{}; 正样本占{:.2%}; 负样本占{:.2%}'.format(n_sample,
n_pos_sample / n_sample,
n_neg_sample / n_sample))
print('特征维数:', X.shape[1])
# 处理不平衡数据
sm = SMOTE(random_state=42) # 处理过采样的方法
X, y = sm.fit_sample(X, y)
print('经过SMOTE方法平衡正负样本后')
n_sample = y.shape[0]
n_pos_sample = y[y == 0].shape[0]
n_neg_sample = y[y == 1].shape[0]
print('样本个数:{}; 正样本占{:.2%}; 负样本占{:.2%}'.format(n_sample,
n_pos_sample / n_sample,
n_neg_sample / n_sample))
构建分类器训练
本次项目咱们采用交叉验证法划分数据集,将数据划分为3部分:训练集(training set)、验证集(validation set)和测试集(test set)。让模型在训练集进行学习,在验证集上进行参数调优,最后使用测试集数据评估模型的性能。
模型调优咱们采用网格搜索调优参数(grid search),经过构建参数候选集合,而后网格搜索会穷举各类参数组合,根据设定评定的评分机制找到最好的那一组设置。
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.3, random_state = 0) # random_state = 0 每次切分的数据都同样
# 构建参数组合
param_grid = {'C': [0.01,0.1, 1, 10, 100, 1000,],
'penalty': [ 'l1', 'l2']}
# C:Inverse of regularization strength; must be a positive float. Like in support vector machines, smaller values specify stronger regularization.
grid_search = GridSearchCV(LogisticRegression(), param_grid, cv=10) # 肯定模型LogisticRegression,和参数组合param_grid ,cv指定10折
grid_search.fit(X_train, y_train) # 使用训练集学习算法
print("Best parameters: {}".format(grid_search.best_params_))
print("Best cross-validation score: {:.5f}".format(grid_search.best_score_))
print("Best estimator:\n{}".format(grid_search.best_estimator_)) # grid_search.best_estimator_ 返回模型以及他的全部参数(包含最优参数)
如今使用通过训练和调优后的模型在测试集上测试。
y_pred = grid_search.predict(X_test)
print("Test set accuracy score: {:.5f}".format(accuracy_score(y_test, y_pred,)))
Test set accuracy score: 0.66064
print(classification_report(y_test, y_pred))
roc_auc = roc_auc_score(y_test, y_pred)
print("Area under the ROC curve : %f" % roc_auc)
Area under the ROC curve : 0.660654
总结
最后结果不太理想,实际工做中还要作特征分箱处理,计算IV值和WOE编码也是须要的。模型评估方面也有不足,这为之后的工做提供了些经验。
https://study.163.com/course/courseMain.htm?courseId=1005988013&share=2&shareId=400000000398149(博主录制)