Lending Club—構建貸款違約預測模型

python信用評分卡(附代碼,博主錄製)

 

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(博主錄製)

相關文章
相關標籤/搜索