實(shí)戰(zhàn)案例:使用機(jī)器學(xué)習(xí)算法預(yù)測(cè)用戶貸款是否違約!
大家好,最近一張"因疫情希望延緩房貸"的截圖在網(wǎng)上流傳,隨即引起網(wǎng)友們的熱議!
當(dāng)借款人從貸款機(jī)構(gòu)借錢(qián)而不能如期還貸款時(shí),就可能會(huì)發(fā)生貸款違約。拖欠貸款不僅會(huì)上報(bào)征信,還可能有被起訴的風(fēng)險(xiǎn)。
為更好的管控風(fēng)險(xiǎn),貸款機(jī)構(gòu)通常會(huì)基于用戶信息來(lái)預(yù)測(cè)用戶貸款是否違約,今天我將使用示例數(shù)據(jù)集來(lái)給大家講解預(yù)測(cè)貸款違約的工作原理,完整版數(shù)據(jù)和代碼文末獲取。
數(shù)據(jù)
數(shù)據(jù)中包含每個(gè)客戶的人口統(tǒng)計(jì)特征和顯示他們是否會(huì)拖欠貸款的目標(biāo)變量。
首先,我們導(dǎo)入庫(kù)并加載數(shù)據(jù)集。
import numpy as np # linear algebra
import pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)
import matplotlib.pyplot as plt
import seaborn as sns
%matplotlib inline
sns.set_theme(style = "darkgrid")
data = pd.read_csv("/kaggle/input/loan-prediction-based-on-customer-behavior/Training Data.csv")
data.head()

探索數(shù)據(jù)集
首先,我們從了解數(shù)據(jù)及數(shù)據(jù)分布開(kāi)始
rows, columns = data.shape
print('Rows:', rows)
print('Columns:', columns)
輸出
Rows: 252000
Columns: 13
我們看到數(shù)據(jù)有252000行和 13 個(gè)特征,其中 12 個(gè)是輸入特征,1 個(gè)是輸出特征。
現(xiàn)在我們檢查數(shù)據(jù)類型和其他信息。
data.info()
輸出
RangeIndex: 252000 entries, 0 to 251999
Data columns (total 13 columns)
# Column Non-Null Count Dtype
--- ------ -------------- -----
0 Id 252000 non-null int64
1 Income 252000 non-null int64
2 Age 252000 non-null int64
3 Experience 252000 non-null int64
4 Married/Single 252000 non-null object
5 House_Ownership 252000 non-null object
6 Car_Ownership 252000 non-null object
7 Profession 252000 non-null object
8 CITY 252000 non-null object
9 STATE 252000 non-null object
10 CURRENT_JOB_YRS 252000 non-null int64
11 CURRENT_HOUSE_YRS 252000 non-null int64
12 Risk_Flag 252000 non-null int64
dtypes: int64(7), object(6)
memory usage: 25.0+ MB
我們看到一半特征是數(shù)值型,一半是字符串,所以它們可能是類別特征。
在數(shù)據(jù)科學(xué)中將數(shù)值數(shù)據(jù)稱為"定量數(shù)據(jù)",類別數(shù)據(jù)被稱為"定性數(shù)據(jù)"
讓我們檢查數(shù)據(jù)中是否存在任何缺失值。
data.isnull().sum()
輸出
Id 0
Income 0
Age 0
Experience 0
Married/Single 0
House_Ownership 0
Car_Ownership 0
Profession 0
CITY 0
STATE 0
CURRENT_JOB_YRS 0
CURRENT_HOUSE_YRS 0
Risk_Flag 0
dtype: int64
讓我們檢查數(shù)據(jù)列名稱。
data.columns
輸出
Index(['Id', 'Income', 'Age', 'Experience', 'Married/Single',
'House_Ownership', 'Car_Ownership', 'Profession', 'CITY', 'STATE',
'CURRENT_JOB_YRS', 'CURRENT_HOUSE_YRS', 'Risk_Flag'],
dtype='object')
我們得到了數(shù)據(jù)特征的名稱。
分析數(shù)值列
首先,我們從數(shù)值數(shù)據(jù)開(kāi)始分析。
data.describe()
輸出
現(xiàn)在,我們檢查數(shù)據(jù)分布。
data.hist( figsize = (22, 20) )
plt.show()

現(xiàn)在,我們檢查目標(biāo)變量的計(jì)數(shù)。
data["Risk_Flag"].value_counts()
輸出
0 221004
1 30996
Name: Risk_Flag, dtype: int64
只有一小部分目標(biāo)變量由拖欠貸款的人組成。
現(xiàn)在,我們繪制相關(guān)圖。
fig, ax = plt.subplots( figsize = (12,8) )
corr_matrix = data.corr()
corr_heatmap = sns.heatmap( corr_matrix, cmap = "flare", annot=True, ax=ax, annot_kws={"size": 14})
plt.show()

分析類別特征
現(xiàn)在,我們繼續(xù)分析類別特征。
首先,我們定義一個(gè)函數(shù)來(lái)創(chuàng)建繪圖。
def categorical_valcount_hist(feature):
print(data[feature].value_counts())
fig, ax = plt.subplots( figsize = (6,6) )
sns.countplot(x=feature, ax=ax, data=data)
plt.show()
首先,我們檢查已婚人數(shù)與單身人數(shù)。
categorical_valcount_hist("Married/Single")

所以,大部分人都是單身。
現(xiàn)在,我們檢查房屋所有權(quán)的數(shù)量。
categorical_valcount_hist("House_Ownership")

現(xiàn)在,讓我們檢查 states 數(shù)。
print( "Total categories in STATE:", len( data["STATE"].unique() ) )
print()
print( data["STATE"].value_counts() )
輸出
Total categories in STATE: 29
Uttar_Pradesh 28400
Maharashtra 25562
Andhra_Pradesh 25297
West_Bengal 23483
Bihar 19780
Tamil_Nadu 16537
Madhya_Pradesh 14122
Karnataka 11855
Gujarat 11408
Rajasthan 9174
Jharkhand 8965
Haryana 7890
Telangana 7524
Assam 7062
Kerala 5805
Delhi 5490
Punjab 4720
Odisha 4658
Chhattisgarh 3834
Uttarakhand 1874
Jammu_and_Kashmir 1780
Puducherry 1433
Mizoram 849
Manipur 849
Himachal_Pradesh 833
Tripura 809
Uttar_Pradesh[5] 743
Chandigarh 656
Sikkim 608
Name: STATE
dtype: int64
現(xiàn)在,我們檢查職業(yè)(Profession)的數(shù)量。
print( "Total categories in Profession:", len( data["Profession"].unique() ) )
print()
data["Profession"].value_counts()
輸出
Total categories in Profession: 51
Physician 5957
Statistician 5806
Web_designer 5397
Psychologist 5390
Computer_hardware_engineer 5372
Drafter 5359
Magistrate 5357
Fashion_Designer 5304
Air_traffic_controller 5281
Comedian 5259
Industrial_Engineer 5250
Mechanical_engineer 5217
Chemical_engineer 5205
Technical_writer 5195
Hotel_Manager 5178
Financial_Analyst 5167
Graphic_Designer 5166
Flight_attendant 5128
Biomedical_Engineer 5127
Secretary 5061
Software_Developer 5053
Petroleum_Engineer 5041
Police_officer 5035
Computer_operator 4990
Politician 4944
Microbiologist 4881
Technician 4864
Artist 4861
Lawyer 4818
Consultant 4808
Dentist 4782
Scientist 4781
Surgeon 4772
Aviator 4758
Technology_specialist 4737
Design_Engineer 4729
Surveyor 4714
Geologist 4672
Analyst 4668
Army_officer 4661
Architect 4657
Chef 4635
Librarian 4628
Civil_engineer 4616
Designer 4598
Economist 4573
Firefighter 4507
Chartered_Accountant 4493
Civil_servant 4413
Official 4087
Engineer 4048
Name: Profession
dtype: int64
數(shù)據(jù)分析
現(xiàn)在,我們從了解不同數(shù)據(jù)特征之間的關(guān)系開(kāi)始。
sns.boxplot(x ="Risk_Flag",y="Income" ,data = data)
現(xiàn)在,我們看到了標(biāo)志變量和年齡之間的關(guān)系。
sns.boxplot(x ="Risk_Flag",y="Age" ,data = data)

sns.boxplot(x ="Risk_Flag",y="Experience" ,data = data)

sns.boxplot(x ="Risk_Flag",y="CURRENT_JOB_YRS" ,data = data)

sns.boxplot(x ="Risk_Flag",y="CURRENT_HOUSE_YRS" ,data = data)

fig, ax = plt.subplots( figsize = (8,6) )
sns.countplot(x='Car_Ownership', hue='Risk_Flag', ax=ax, data=data)

fig, ax = plt.subplots( figsize = (8,6) )
sns.countplot( x='Married/Single', hue='Risk_Flag', data=data )

fig, ax = plt.subplots( figsize = (10,8) )
sns.boxplot(x = "Risk_Flag", y = "CURRENT_JOB_YRS", hue='House_Ownership', data = data)

特征工程
在進(jìn)行建模之前,數(shù)據(jù)準(zhǔn)備是數(shù)據(jù)科學(xué)領(lǐng)域的必需過(guò)程。在數(shù)據(jù)準(zhǔn)備過(guò)程中,我們必須完成多項(xiàng)任務(wù),這些關(guān)鍵職責(zé)之一是類別數(shù)據(jù)的編碼。
眾所周知,在日常工作中的大多數(shù)數(shù)據(jù)都有分類字符串值,而大多數(shù)機(jī)器學(xué)習(xí)模型只處理數(shù)值類別。
編碼類別數(shù)據(jù)是將分類數(shù)據(jù)轉(zhuǎn)換為整數(shù)格式的過(guò)程,以便將數(shù)據(jù)輸入模型以提高預(yù)測(cè)準(zhǔn)確性。
我們將對(duì)類別特征應(yīng)用編碼。
from sklearn.preprocessing import LabelEncoder
from sklearn.preprocessing import OneHotEncoder
import category_encoders as ce
label_encoder = LabelEncoder()
for col in ['Married/Single','Car_Ownership']:
data[col] = label_encoder.fit_transform( data[col] )
onehot_encoder = OneHotEncoder(sparse = False)
data['House_Ownership'] = onehot_encoder.fit_transform(data['House_Ownership'].values.reshape(-1, 1) )
high_card_features = ['Profession', 'CITY', 'STATE']
count_encoder = ce.CountEncoder()
# Transform the features, rename the columns with the _count suffix, and join to dataframe
count_encoded = count_encoder.fit_transform( data[high_card_features] )
data = data.join(count_encoded.add_suffix("_count"))
data= data.drop(labels=['Profession', 'CITY', 'STATE'], axis=1)
data.head()
特征工程部分完成后,我們將數(shù)據(jù)拆分為訓(xùn)練集和測(cè)試集。
將數(shù)據(jù)拆分為訓(xùn)練和測(cè)試集
為了評(píng)估我們的機(jī)器學(xué)習(xí)模型的工作效率,我們必須將數(shù)據(jù)集劃分為訓(xùn)練集和測(cè)試集。訓(xùn)練集用于訓(xùn)練機(jī)器學(xué)習(xí)模型,其統(tǒng)計(jì)數(shù)據(jù)是已知的,測(cè)試數(shù)據(jù)集用于預(yù)測(cè)。
x = data.drop("Risk_Flag", axis=1)
y = data["Risk_Flag"]
from sklearn.model_selection import train_test_split
x_train, x_test, y_train, y_test = train_test_split(x, y, test_size = 0.2, stratify = y, random_state = 7)
我們將測(cè)試集規(guī)模設(shè)為整個(gè)數(shù)據(jù)的 20%。
隨機(jī)森林分類器
基于樹(shù)的算法在機(jī)器學(xué)習(xí)中被廣泛用于處理監(jiān)督學(xué)習(xí)挑戰(zhàn)。這些算法適應(yīng)性強(qiáng),幾乎可以解決任何問(wèn)題(分類或回歸)。
此外它們具有高度準(zhǔn)確性、穩(wěn)定性和可解釋性的預(yù)測(cè)。
隨機(jī)森林是一種常見(jiàn)的基于樹(shù)的有監(jiān)督學(xué)習(xí)技術(shù),該方法可用于解決分類和回歸問(wèn)題。隨機(jī)森林通常結(jié)合數(shù)百個(gè)決策樹(shù),然后在不同的數(shù)據(jù)樣本上訓(xùn)練每個(gè)決策樹(shù)。
在本文中我采用隨機(jī)森林算法,有興趣的小伙伴可以選取其他算法進(jìn)行嘗試。
現(xiàn)在,我們訓(xùn)練模型并執(zhí)行預(yù)測(cè)。
from sklearn.ensemble import RandomForestClassifier
from imblearn.over_sampling import SMOTE
from imblearn.pipeline import Pipeline
rf_clf = RandomForestClassifier(criterion='gini', bootstrap=True, random_state=100)
smote_sampler = SMOTE(random_state=9)
pipeline = Pipeline(steps = [['smote', smote_sampler],['classifier', rf_clf]])
pipeline.fit(x_train, y_train)
y_pred = pipeline.predict(x_test)
現(xiàn)在,我們檢查準(zhǔn)確性分?jǐn)?shù)。
from sklearn.metrics import confusion_matrix, precision_score, recall_score, f1_score, accuracy_score, roc_auc_score
print("-------------------------TEST SCORES-----------------------")
print(f"Recall: { round(recall_score(y_test, y_pred)*100, 4) }")
print(f"Precision: { round(precision_score(y_test, y_pred)*100, 4) }")
print(f"F1-Score: { round(f1_score(y_test, y_pred)*100, 4) }")
print(f"Accuracy score: { round(accuracy_score(y_test, y_pred)*100, 4) }")
print(f"AUC Score: { round(roc_auc_score(y_test, y_pred)*100, 4) }")
輸出
-------------------------TEST SCORES-----------------------
Recall: 54.1378
Precision: 54.3306
F1-Score: 54.234
Accuracy score: 88.7619
AUC Score: 73.8778
結(jié)論
今天我將預(yù)測(cè)用戶貸款是否違約整個(gè)流程都講解了一遍,有幾點(diǎn)值得關(guān)注:
當(dāng)我們需要高準(zhǔn)確同時(shí)避免過(guò)擬合時(shí),隨機(jī)森林方法適用于具有許多條目和特征的數(shù)據(jù)集上的分類和回歸任務(wù),這些條目和特征可能具有缺失值 隨機(jī)森林提供特征重要性,能夠選擇最重要的特征。它比神經(jīng)網(wǎng)絡(luò)模型更易解釋,但比決策樹(shù)更難解釋 在分類特征的情況下,我們需要執(zhí)行編碼,以便算法可以處理它們
1. 長(zhǎng)按下方公眾號(hào),點(diǎn)擊右上角;
2. 在下方后臺(tái)回復(fù)關(guān)鍵詞:信貸違約,即可快速下載
