金融贷款逾期的模型构建5——数据预处理
生活随笔
收集整理的這篇文章主要介紹了
金融贷款逾期的模型构建5——数据预处理
小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
文章目錄
- 一、相關(guān)庫
- 二、數(shù)據(jù)讀取
- 三、數(shù)據(jù)清洗——?jiǎng)h除無關(guān)、重復(fù)數(shù)據(jù)
- 四、數(shù)據(jù)清洗——類型轉(zhuǎn)換
- 1、數(shù)據(jù)集劃分
- 2、缺失值處理
- 3、異常值處理
- 4、離散特征編碼
- 5、日期特征處理
- 6、特征組合
- 五、數(shù)據(jù)集劃分
- 六、模型構(gòu)建
- 七、模型評(píng)估
數(shù)據(jù)傳送門(與之前的不同): https://pan.baidu.com/s/1G1b2QJjYkkk7LDfGorbj5Q
目標(biāo):數(shù)據(jù)集是金融數(shù)據(jù)(非脫敏),要預(yù)測(cè)貸款用戶是否會(huì)逾期。表格中 “status” 是結(jié)果標(biāo)簽:0表示未逾期,1表示逾期。
任務(wù):數(shù)據(jù)類型轉(zhuǎn)換和缺失值處理(嘗試不同的填充看效果)以及及其他你能借鑒的數(shù)據(jù)探索。
一、相關(guān)庫
# -*- coding:utf-8 -*- import pandas as pd from sklearn.preprocessing import StandardScaler from sklearn.model_selection import train_test_split from sklearn.linear_model import LogisticRegression from sklearn.svm import SVC from sklearn.tree import DecisionTreeClassifier from sklearn.ensemble import RandomForestClassifier import xgboost as xgb import lightgbm as lgb from sklearn.metrics import accuracy_score, precision_score, recall_score from sklearn.metrics import roc_auc_score import matplotlib.pyplot as plt二、數(shù)據(jù)讀取
file_path = "data.csv" data = pd.read_csv(file_path, encoding='gbk') print(data.head()) print(data.shape)結(jié)果輸出
Unnamed: 0 custid ... latest_query_day loans_latest_day 0 5 2791858 ... 12.0 18.0 1 10 534047 ... 4.0 2.0 2 12 2849787 ... 2.0 6.0 3 13 1809708 ... 2.0 4.0 4 14 2499829 ... 22.0 120.0[5 rows x 90 columns] (4754, 90)遇到的問題:
UnicodeDecodeError: 'utf-8' codec can't decode byte 0xbf in position 0: invalid start byte原因:‘utf-8’不能解碼字節(jié)(0xbf),也就是這個(gè)字節(jié)超出了utf-8的表示范圍了
解決方法:顯式添加編碼方式。親測(cè):encoding=‘gbk’ 或’ISO-8859-1’編碼。
三、數(shù)據(jù)清洗——?jiǎng)h除無關(guān)、重復(fù)數(shù)據(jù)
## 刪除與個(gè)人身份相關(guān)的列 data.drop(['custid', 'trade_no', 'bank_card_no', 'id_name'], axis=1, inplace=True)## 刪除列中數(shù)據(jù)均相同的列 X = data.drop(labels='status',axis=1) L = [] for col in X:if len(X[col].unique()) == 1:L.append(col) for col in L:X.drop(col, axis=1, inplace=True)四、數(shù)據(jù)清洗——類型轉(zhuǎn)換
1、數(shù)據(jù)集劃分
劃分不同數(shù)據(jù)類型:數(shù)值型、非數(shù)值型、標(biāo)簽
使用:Pandas對(duì)象有 select_dtypes() 方法可以篩選出特定數(shù)據(jù)類型的特征
參數(shù):include 包括(默認(rèn));exclude 不包括
2、缺失值處理
發(fā)現(xiàn)缺失值方法:缺失個(gè)數(shù)、缺失率
# 使用缺失率(可以了解比重)并按照值降序排序 ascending=False X_num_miss = (X_num.isnull().sum() / len(X_num)).sort_values(ascending=False) print(X_num_miss.head()) print('----------' * 5) X_str_miss = (X_str.isnull().sum() / len(X_str)).sort_values(ascending=False) print(X_str_miss.head())輸出結(jié)果
student_feature 0.630627 cross_consume_count_last_1_month 0.089609 latest_one_month_apply 0.063946 query_finance_count 0.063946 latest_six_month_apply 0.063946 dtype: float64 -------------------------------------------------- latest_query_time 0.063946 loans_latest_time 0.062474 reg_preference_for_trad 0.000421 dtype: float64分析:缺失率最高的特征是student_feature,為 63.0627% > 50% ,其他的特征缺失率都在10%以下。
- 高缺失率特征處理:EM插補(bǔ)、多重插補(bǔ)。
==》由于兩種方法比較復(fù)雜,這里先將缺失值歸為一類,用0填充。 - 其他特征:平均數(shù)、中位數(shù)、眾數(shù)…
3、異常值處理
- 箱型圖的四分位距(IQR)
4、離散特征編碼
- 序號(hào)編碼:用于有大小關(guān)系的數(shù)據(jù)
- one-hot編碼:用于無序關(guān)系的數(shù)據(jù)
5、日期特征處理
X_date = pd.DataFrame() X_date['latest_query_time_year'] = pd.to_datetime(X_str['latest_query_time']).dt.year X_date['latest_query_time_month'] = pd.to_datetime(X_str['latest_query_time']).dt.month X_date['latest_query_time_weekday'] = pd.to_datetime(X_str['latest_query_time']).dt.weekday X_date['loans_latest_time_year'] = pd.to_datetime(X_str['loans_latest_time']).dt.year X_date['loans_latest_time_month'] = pd.to_datetime(X_str['loans_latest_time']).dt.month X_date['loans_latest_time_weekday'] = pd.to_datetime(X_str['loans_latest_time']).dt.weekday6、特征組合
X = pd.concat([X_num, X_str_oh, X_date], axis=1, sort=False) print(X.shape)五、數(shù)據(jù)集劃分
## 預(yù)處理:標(biāo)準(zhǔn)化 # X_std = StandardScaler().fit(X)## 劃分?jǐn)?shù)據(jù)集 X_std_train, X_std_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=2019)六、模型構(gòu)建
## 模型1:Logistic Regression lr = LogisticRegression() lr.fit(X_std_train, y_train)## 模型2:Decision Tree dtc = DecisionTreeClassifier(max_depth=8) dtc.fit(X_std_train,y_train)# ## 模型3:SVM # svm = SVC(kernel='linear',probability=True) # svm.fit(X_std_train,y_train)## 模型4:Random Forest rfc = RandomForestClassifier() rfc.fit(X_std_train,y_train)## 模型5:XGBoost xgbc = xgb.XGBClassifier() xgbc.fit(X_std_train,y_train)## 模型6:LightGBM lgbc = lgb.LGBMClassifier() lgbc.fit(X_std_train,y_train)七、模型評(píng)估
## 模型評(píng)估 def model_metrics(clf, X_test, y_test):y_test_pred = clf.predict(X_test)y_test_prob = clf.predict_proba(X_test)[:, 1]accuracy = accuracy_score(y_test, y_test_pred)print('The accuracy: ', accuracy)precision = precision_score(y_test, y_test_pred)print('The precision: ', precision)recall = recall_score(y_test, y_test_pred)print('The recall: ', recall)f1_score = recall_score(y_test, y_test_pred)print('The F1 score: ', f1_score)print('----------------------------------')# roc_auc_score = roc_auc_score(y_test, y_test_prob)# print('The AUC of: ', roc_auc_score)model_metrics(lr,X_std_test,y_test) model_metrics(dtc,X_std_test,y_test) model_metrics(rfc,X_std_test,y_test) model_metrics(xgbc,X_std_test,y_test) model_metrics(lgbc,X_std_test,y_test)總結(jié)
以上是生活随笔為你收集整理的金融贷款逾期的模型构建5——数据预处理的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 《笨办法学python》(《learn
- 下一篇: 【Numpy】学习笔记1