KESCI 遷移學習提供「借貸風險評估」解決方案的baseline改寫,XGBOOST方法+SMOTE

遷移學習提供「借貸風險評估」解決方案

大賽簡介

金融場景是算法落地的重要場景。本次練習賽,我們聚焦於「借貸風險評估」問題。探索機器學習細分領域——遷移學習,在金融場景的更多可能性,以及其實踐落地。

本練習賽所用數據集爲業內開放數據集,我們將其設計爲遷移學習問題:

  • 參賽選手需依據給定的4萬條業務A數據及4千條業務B數據,建立業務B的信用評分模型。其中業務A爲信用貸款, 其特徵是債務人無需提供抵押品,僅憑自己的信譽取得貸款,並以借款人信用程度作爲還款保證;業務B爲現金貸,即發薪日貸款(payday loan),與一般的消費金融產品相比,現金貸主要具有以下五個特點:額度小、週期短、無抵押、流程快、利率高,這也是與其借貸門檻低的特徵相適應的。
  • 由於業務A、B存在關聯性,選手如何將業務A的知識遷移到業務B,以此增強業務B的信用評分模型,是本場練習賽的重點

如果你有一定機器學習基礎,希望擴充自己的能力邊界。那本練習賽便是你最好的賽場,在這裏,你將收穫:

  • 遷移學習領域入門的絕佳機會
  • 結交賽事圈好友,組建你的自有車隊

----------------------------------------------

原baseline沒有數據的上採樣處理處理(SMOTE),然後也沒有調參過程,我稍加改動

數據極度不平衡,對其進行上採樣處理的合適且必要的

運用的XGBOOST算法

改寫的解讀https://www.kesci.com/home/project/5dbe6302080dc300371f3219

很遺憾,得到的模型並沒有很好地在測試集中得到較高的scroe,因爲並沒有如出題方所設想地用到遷移學習,而僅僅是對給到B數據集進行了學習,而B數據集數量較小,模型或多或少欠擬合。

附代碼供個人回顧或其他學習者參考:

from sklearn.model_selection import train_test_split
from sklearn.model_selection import StratifiedKFold
from sklearn.metrics import roc_auc_score
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline
import seaborn as sns
#import lightgbm as lgb
import warnings
warnings.filterwarnings('ignore')
import os
import gc
sns.set(style = 'white', context= 'notebook', palette = 'deep')
sns.set_style('white')
pd.set_option('display.max_columns', 500)
train_A = pd.read_csv('/home/kesci/input/qyxx6708/A_train.csv')
train_B = pd.read_csv('/home/kesci/input/qyxx6708/B_train.csv')
test = pd.read_csv('/home/kesci/input/qyxx6708/B_test.csv')
sample = pd.read_csv('/home/kesci/input/qyxx6708/submit_sample.csv')

#數據描述省略
#.....

#去除完全空的數據列
train_B = train_B.drop('UserInfo_170', axis = 1)
#嚴重缺失值處理
'''嚴重缺失的特徵會給模型帶來極大的噪音,模型在學習的過程中,會被幹擾。爲了增強模型的魯棒性,我們考慮將有很大的噪音的數據進行刪除,此處我們設置閾值爲1%,我們將缺失的特徵大於99%的特徵刪除(閾值可以自己進行調整)'''
train_B_info = train_B.describe()
useful_col = []
for col in train_B_info.columns:
    if train_B_info.ix[0,col] > train_B.shape[0]*0.01:
        useful_col.append(col)
train_B_1 = train_B[useful_col].copy()


#缺失值填充-999
train_B_1 = train_B_1.fillna(-999)

#高線性相關性數據處理
'''
如果兩個特徵是完全線性相關的,這個時候我們只需要保留其中一個即可。因爲第二個特徵包含的信息完全被第一個特徵所包含。此時,如果兩個特徵同時都保留的話,模型的性能很大情況會出現下降的情況。

我們選擇將高線性相關的特徵進行刪除'''
relation = train_B_1.corr()
length = relation.shape[0]
high_corr = list()
final_cols = []
del_cols = []
for i in range(length):
    if relation.columns[i] not in del_cols:
        final_cols.append(relation.columns[i])
        for j in range(i+1, length):
            if (relation.iloc[i,j] > 0.98) and (relation.columns[j] not in del_cols):
                del_cols.append(relation.columns[j])

train_B_1 = train_B_1[final_cols]
train_B_flag = train_B_1['flag']
train_B_1.drop('no', axis = 1, inplace = True)
train_B_1.drop('flag', axis = 1, inplace = True)


#數據模型數據準備,解決非平衡數據
#通過鏡像pip安裝xgboost
!pip install -i https://pypi.tuna.tsinghua.edu.cn/simple xgboost

import xgboost as xgb
dtrain_B = xgb.DMatrix(data = train_B_1, label = train_B_flag)
#安裝imblearn包,處理上採樣
!pip install imblearn

from imblearn.over_sampling import SMOTE
# 對訓練集進行上採樣處理
smote = SMOTE(random_state=2)
X_train_os,y_train_os = smote.fit_sample(train_B_1, train_B_flag) # ravel(): change the shape of y to (n_samples, )

print('上採樣後,訓練集的交易記錄條數:', len(X_train_os))
print('其中,訓練集X的shape:',X_train_os.shape,',y的shape:',y_train_os.shape)
print('交易記錄總數:',X_train_os.shape[0])
print('上採樣後,類別爲‘1’的共有{}個,類別爲‘0’的共有{}個。'.format(sum(y_train_os==1),sum(y_train_os==0)))

X_train_os=pd.DataFrame(X_train_os)
X_train_os.columns = train_B_1.columns
dtrain_B_caiyang = xgb.DMatrix(data = X_train_os, label = y_train_os)


-----------
#調參過程
from sklearn.model_selection import GridSearchCV
cv_params={'eta':[0.1,0.01]}    #0.1
param_test1 = {
  'max_depth':range(3,10,1),
 'min_child_weight':range(1,6,1)
}     



#參數最佳取值:{'max_depth': 9, 'min_child_weight': 1}
param_test2 = {
  'lambda':range(3,10,1),
          'alpha':range(3,10,1),
          
}     

#參數最佳取值:{'lambda': 3, 'alpha': 3}


#gbm = xgb.XGBClassifier(**params)
#opt_clf = GridSearchCV(estimator=gbm,param_grid=cv_params,cv=5)
gsearch3 = GridSearchCV(  
    estimator=xgb.XGBClassifier(learning_rate=0.1, gamma=0,  
                            subsample=0.8, colsample_bytree=0.8,max_depth=9,min_child_weight=1, objective='binary:logistic', nthread=8,  
                            scale_pos_weight=1, seed=27), param_grid=param_test2, scoring='roc_auc',  
    iid=False, cv=5)  


gsearch3.fit(X_train_os,y_train_os.ravel())
print('參數最佳取值:{0}'.format(gsearch3.best_params_))
print('最佳模型得分:{0}'.format(gsearch3.best_score_))
-------------

#上採樣後訓練模型

Trate = 0.25
params = {'booster':'gbtree',
          'eta':0.1,
          'max_depth':9,
          'max_delta_step':0,
          'subsample':0.9,
          'colsample_bytree':0.9,
          'base_score':Trate,
          'objective':'binary:logistic',
          'lambda':3,
          'alpha':3,
          'random_seed':100,
          'min_child_weight':1
}
params['eval_metric'] ='auc'
xgb_model2 = xgb.train(params, dtrain_B_caiyang, num_boost_round=200, maximize = True,
                      verbose_eval= True )

#看上採樣後的訓練集的訓練score
from sklearn.metrics import roc_auc_score
y_pred = xgb_model2.predict(xgb.DMatrix(train_B_1))
auc_score = roc_auc_score(train_B_flag,y_pred)
auc_score

#結果爲0.8564752128867918

--------
#輸出預測結果爲CSV文件
prediction = xgb_model2.predict(xgb.DMatrix(test[train_B_1.columns].fillna(-999)))
test['pred'] = prediction
test[['no','pred']].to_csv('submission2.csv', index = None)

 

 

 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章