1. 程式人生 > >Kaggle八門神器(一):競賽神器之XGBoost介紹

Kaggle八門神器(一):競賽神器之XGBoost介紹

Xgboost為一個十分有效的機器學習模型,在各種競賽中均可以看到它的身影,同時Xgboost在工業屆也有著廣泛的應用,本文以Titanic資料集為研究物件,簡單地探究Xgboost模型建模過程,同時對資料清理以及特徵工程的內容作簡單的介紹,以此作為Xgboost模型的學習筆記,錯誤和不足之處還請各位看官指出。

資料集

本文資料集源自於競賽Titanic: Machine Learning from Disaster,競賽中我們要求根據資料集提供的乘客編號、姓名性別等資訊,運用機器學習模型預測船上乘客的存活與否

泰坦尼克號沉沒事故(英語:Sinking of the RMS Titanic)是1912年4月14日深夜至15日凌晨在北大西洋發生的著名船難,事發時是泰坦尼克號從英國南安普敦港至美國紐約港首航的第5天,該船當時是世界最大的郵輪。1912年4月14日星期天23時40分[a]與一座冰山擦撞前,已經收到6次海冰警告,但當瞭望員看到冰山時,該船的行駛速度正接近最高速。由於無法快速轉向,該船右舷側面遭受了一次撞擊,部分船體出現縫隙,使16個水密隔艙中的5個進水。泰坦尼克號的設計僅能夠承受4個水密隔艙進水,因此沉沒。 --Wikipedia

import pandas as pd
pd.options.mode.chained_assignment = None
titanic = pd.read_csv('Titanic/train.csv')
titanic.head(5)
PassengerId Survived Pclass Name Sex Age SibSp Parch Ticket Fare Cabin Embarked
0 1 0 3 Braund, Mr. Owen Harris male 22.0 1 0 A/5 21171 7.2500 NaN S
1 2 1 1 Cumings, Mrs. John Bradley (Florence Briggs Th... female 38.0 1 0 PC 17599 71.2833 C85 C
2 3 1 3 Heikkinen, Miss. Laina female 26.0 0 0 STON/O2. 3101282 7.9250 NaN S
3 4 1 1 Futrelle, Mrs. Jacques Heath (Lily May Peel) female 35.0 1 0 113803 53.1000 C123 S
4 5 0 3 Allen, Mr. William Henry male 35.0 0 0 373450 8.0500 NaN S

資料清理

資料分析中維持一個乾淨的資料集對建模十分關鍵,可靠的資料集主要由以下幾個方面來評估:

  • 資料的可靠性,這個方面由原始資料集保證
  • 資料的版本控制, 輸入資料對機器學習建模影響很大,如果模型訓練輸入資料不斷髮生變化的話很可能無法生成正確的模型,即上游的輸入資料供給程序突然發生變化會波及到模型建立的過程
  • 特徵的必要性,建模特徵數量和模型精度並不呈現嚴格的正相關
  • 特徵的相關性,建模過程中我們儘可能減少相關特徵的數量

在本例子,NameTicket和存活條件相關性較低,我們可以考慮將這些特徵剔除

X = titanic[['Pclass', 'Age', 'Sex']]
y = titanic['Survived']
# 對於年齡空缺的乘客我們使用平均年齡進行填充
X['Age'] = X['Age'].fillna(X['Age'].mean())
from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.25, random_state=33)
X_train.head(5)
Pclass Age Sex
110 1 47.000000 male
360 3 40.000000 male
364 3 29.699118 male
320 3 22.000000 male
296 3 23.500000 male

特徵工程

傳統編碼工作的關注點在於程式碼編碼的過程,而機器學習和資料分析工作者則是著力於資料特徵的表示過程,開發者通過特徵工程(新特徵可以來源於資料濟原始特徵的邏輯運算)建立一個良好的資料特徵原型。特徵工程的主要工作有

  • 對映字串字元為整型
  • 採用One-Hot編碼方式對映列舉值

在本例中,我們將Titanic資料集的Sex一列的男性和女性對映為整型值0和1

X_train['Sex'] = X_train['Sex'].map({'male':0,'female':1})
X_test['Sex'] = X_test['Sex'].map({'male':0,'female':1})
# 檢視對映處理結果
X_train.head(5)
Pclass Age Sex
110 1 47.000000 0
360 3 40.000000 0
364 3 29.699118 0
320 3 22.000000 0
296 3 23.500000 0
from sklearn.ensemble import RandomForestClassifier
titanic_rf = RandomForestClassifier()
titanic_rf.fit(X_train, y_train)
print('The accuracy of Random Forest Classifier on testing set:', titanic_rf.score(X_test, y_test))
The accuracy of Random Forest Classifier on testing set: 0.8026905829596412
from xgboost import XGBClassifier

titanic_xgb = XGBClassifier()
titanic_xgb.fit(X_train, y_train)
print('The accuracy of eXtreme Gradient Boosting Classifier on testing set:', titanic_xgb.score(X_test, y_test))
The accuracy of eXtreme Gradient Boosting Classifier on testing set: 0.8385650224215246

分類結果報告

目標分類中常用的指標有精確率、召回率以及F1均值,公式如下:

  • 精確率 \(Precision = \frac{T_P}{(T_P + F_P)}\)
  • 召回率 \(Recall = \frac{T_P}{(T_P + F_N)}\)
  • F1值 \(F1 = 2 \times \frac{Precision \times Recall}{(Precision + Recall)}\)
from sklearn.metrics import classification_report, precision_recall_curve
from sklearn.metrics import f1_score

rf_result = titanic_rf.predict(X_test)
xgb_result = titanic_xgb.predict(X_test)

print('隨機森林模型: \n ' + classification_report(rf_result, y_test, digits=4))
print('XGBoost模型: \n ' + classification_report(xgb_result, y_test, digits=4))
隨機森林模型: 
               precision    recall  f1-score   support

           0     0.8731    0.8125    0.8417       144
           1     0.6966    0.7848    0.7381        79

   micro avg     0.8027    0.8027    0.8027       223
   macro avg     0.7849    0.7987    0.7899       223
weighted avg     0.8106    0.8027    0.8050       223

XGBoost模型: 
               precision    recall  f1-score   support

           0     0.9179    0.8311    0.8723       148
           1     0.7191    0.8533    0.7805        75

   micro avg     0.8386    0.8386    0.8386       223
   macro avg     0.8185    0.8422    0.8264       223
weighted avg     0.8510    0.8386    0.8414       223

可以看到隨機森林模型和XGBoost的F1均值分別為0.8050和0.8414,XGBoost在Titanic資料集中略勝一