背景
Titanic: Machine Learning from Disaster - Kaggle
2 年前就被推薦照着這個比賽做一下,結果我打開這個頁面便蒙了,完全不知道該如何下手。
兩年后,再次打開這個頁面,看到清清楚楚的Titanic Tutorial - Kaggle,完全傻瓜式的照着做就能做下來。當年是什么蒙蔽了我的眼睛~
Target
use machine learning to create a model that predicts which passengers survived the Titanic shipwreck
Data
Titanic: Machine Learning from Disaster - Kaggle
- train.csv
- Survived: 1=yes, 0=No
- test.csv
- gender_submission.csv: for prediction
- PassengerId: those from test.csv
- Survived: final result
Guide to help start and follow
Learning Model
摘抄的網站的解釋,后面具體談。
- random forest model
- constructed of several "trees"
- that will individually consider each passenger's data
- and vote on whether the individual survived.
- Then, the random forest model makes a democratic decision:
- the outcome with the most votes wins!
- constructed of several "trees"
sklearn.ensemble.RandomForestClassifier
Titanic比賽中用到的是 RandomForestClassifier 算法,在了解這個算法前,我注意到 sklearn 中這個算法類是在 ensemble 模塊中,英文不好,不知道 ensemble 是什么意思?所以想先了解一下 ensemble
ensemble
字典的解釋是:a number of things considered as a group
聽起來有組合的意思。
搜索了一下,在 ML 中有 ensemble learning, 翻譯多是“集成學習”,參考集成學習(ensemble learning)應如何入門? - 知乎提到,有三種常見的集成學習框架:bagging,boosting 和 stacking。
從 API Reference — scikit-learn 0.22.1 documentation中也能看出來這幾種框架都有相應的算法。
Random Forest 是 bagging 框架中的一個算法。這里就單先試着理解這個,其他框架等以后遇到了再說。但是了解這個之前,還是得先清楚 Ensemble Learning 到底是什么?
In statistics and machine learning, ensemble methods use multiple learning algorithms to obtain better predictive performance than could be obtained from any of the constituent learning algorithms alone.
這個解釋應和了字面上的意思,組合了多種算法來獲得更好的預測性能,結果優於單用其中的單個算法。
bagging 框架
sklearn.ensemble.BaggingClassifier — scikit-learn 0.22.1 documentation
A Bagging classifier is an ensemble meta-estimator that fits base classifiers each on random subsets of the original dataset and then aggregate their individual predictions (either by voting or by averaging) to form a final prediction.
大意就是:
- 從源數據集中隨機抽樣一部分子集樣本
- 在這個子集樣本上訓練分類器
- 重復多次上述步驟
- 然后將各分類器的預測結果整合 (求平均或投票)
- 形成最終的預測
問題是:
- 抽取多少次子集樣本,即要做多少分類器?
- 隨機抽取的算法用什么?
- 整合各分類器結果的時候,求平均和投票各有什么優劣勢?
- 如何訓練各個分類器?
我都不曉得~
前面提到 Random Forest 是 bagging 框架的一種算法。現在來看看這個算法如何解答我的一些疑問。
Random Forest 算法
1.11. Ensemble methods — scikit-learn 0.22.1 documentation
The prediction of the ensemble is given as the averaged prediction of the individual classifiers.
先明確了一個,這個算法是懟各分類器求平均的。Forest of what? 自然是 forest of trees, 而這里的 tree 指的是 decision trees,所以這個算法其實是 averaging algorithms based on randomized decision trees
random forest builds multiple decision trees and merges them together to get a more accurate and stable prediction.
Random forest對每個分類器都建一個決策樹,然后再合並。
分類器是如何划分的呢?還是以 Titanic 的代碼為例來試着理解下:
from sklearn.ensemble import RandomForestClassifier
y = train_data["Survived"]
features = ["Pclass", "Sex", "SibSp", "Parch"]
X = pd.get_dummies(train_data[features])
model = RandomForestClassifier(n_estimators=100, max_depth=5, random_state=1)
model.fit(X, y)
y:是訓練集中災難中存活的人的集合features: 是這些人的特征值,如性別,幾等艙等- X :生成 dummy 數據,為什么要用
get_dummies而不是直接用train_data[features]呢?
嘗試直接用 train_data[features], 打印 X 的結果是這樣的:
Pclass Sex SibSp Parch
0 3 male 1 0
1 1 female 1 0
如果再繼續用這個 X 建模的話,會報錯:
ValueError: could not convert string to float: 'male'
顯然,因為 Sex 字段是 string 類型,而模型需要的是 float 類型,所以不能直接用 train_data[features]
那 get_dummies() 的作用也清楚了,就是將這些 string 類型的字段轉化成 float 類型。從下面的打印結果也可以看出,Sex 字段被分成了兩個字段,Sex_male, Sex_female, 其值分別是 0 和 1.
Pclass SibSp Parch Sex_female Sex_male
0 3 1 0 0 1
1 1 1 0 1 0
2 3 0 0 1 0
3 1 1 0 1 0
4 3 0 0 0 1
.. ... ... ... ... ...
886 2 0 0 0 1
887 1 0 0 1 0
888 3 1 2 1 0
889 1 0 0 0 1
890 3 0 0 0 1
RandomForestClassifier(n_estimators=100, max_depth=5, random_state=1)- 這幾個參數分別是什么意思?
- n_estimators : 決策樹的數量
- max_depths:決策樹的最大深度
- random_state: 控制隨機數生成器的,(實際沒太明白,這個隨機是不是指隨機抽樣?),可能要和其他參數配合用比如 shuffle。另外還提到,這個數用了控制隨機算法,使得運行多次每次都還是產生相同結果?
- To make a randomized algorithm deterministic (i.e. running it multiple times will produce the same result), an arbitrary integer random_state can be used
- 這幾個參數分別是什么意思?
具體如何調參,參考 parameter tuning guidelines
Random Forest的應用場景
既然是分類器算法,自然很多分類應用的場景都適合了;另外還有回歸問題的場景。
這篇文章The Random Forest Algorithm: A Complete Guide - Built In給出了一個實際例子的類比:
- 你在決定去哪兒旅行,去詢問你的朋友
- 朋友問,你以前的旅行中喜歡和不喜歡的方面都哪些
- 在這個基礎上給出了一些建議
- 這為你的決策提供了素材
- 同樣的步驟,你又去詢問另一個朋友
- 以及另另一個朋友
- ...
同樣,你拿到了幾個 offer,猶豫該接哪個等等;看中了幾套房子,決定選哪個,貌似都可以套用這個算法一試了。
學到的幾個之前不熟悉的代碼
- pandas.DataFrame.head:返回數據集中的頭幾行數據,參數為 n,默認 n=5
test_data = pd.read_csv("/kaggle/input/titanic/test.csv")
test_data.head()
men = train_data.loc[train_data.Sex == 'male']["Survived"]
rate_men = sum(men)/len(men)
Reference
- 集成學習(ensemble learning)應如何入門? - 知乎
- Ensemble Learning》
- The Random Forest Algorithm: A Complete Guide - Built In
本文由博客一文多發平台 OpenWrite 發布!
