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数据集中略胜一筹

猜你喜欢

转载自www.cnblogs.com/chdee/p/10940380.html