1. 程式人生 > >隨機森林解決kaggle競賽中Titanic問題

隨機森林解決kaggle競賽中Titanic問題

作為一個初學小白,十分清楚實踐才能深入理解內容,所以看過大神們關於隨機森林解決kaggle房價預測問題(House_Prices)的解答以後,照著完成了一個Titanic生還預測

Competition Description 問題描述如下:

The sinking of the RMS Titanic is one of the most infamous shipwrecks in history.  On April 15, 1912, during her maiden voyage, the Titanic sank after colliding with an iceberg, killing 1502 out of 2224 passengers and crew. This sensational tragedy shocked the international community and led to better safety regulations for ships.

One of the reasons that the shipwreck led to such loss of life was that there were not enough lifeboats for the passengers and crew. Although there was some element of luck involved in surviving the sinking, some groups of people were more likely to survive than others, such as women, children, and the upper-class.

In this challenge, we ask you to complete the analysis of what sorts of people were likely to survive. In particular, we ask you to apply the tools of machine learning to predict which passengers survived the tragedy.

我們都知道Titanic與冰山相撞沉船後,因沒有足夠的救生艇給乘客和船員造成大批人員遇難。儘管在沉船事故中倖存下來的運氣有一些因素,但一些群體比其他群體更有可能存活下來,比如婦女、兒童和上層社會。因此我們將應用機器學習的工具來預測哪些乘客可能在這場悲劇中倖存了下來。

首先在kaggle網站上下載三個csv檔案,提交樣本submission.csv,訓練檔案train.csv, 以及測試檔案test.csv

匯入pandas包,pandas可以在python中處理所有資料分析相關工作,儲存資料的物件名稱為DataFrame

我們先來看一下訓練檔案的資料集,用read_csv()讀入train.csv, 使用head()方法(列出表的前五行)觀察資料集


該訓練集一共12列,除去PassengerId 11列,10列為獨立變數,survived為我們的目標變數,即因變數

隨機森林是包含多個決策樹的一種分類器,可以避免決策樹的過擬合,簡單的平均所有樹的預測得出一個更好的預測和泛化結果


將訓練集和測試集分別載入進 DataFrame 之後,儲存目標變數


因為只想保留資料集中的獨立變數和特徵,所以緊接著在DataFrame 中刪除了Survived

訓練集和測試集中添加了一個新的臨時列('training_set'),是為了將兩個資料集連線在一起,放在同一個 DataFrame 中,接下來填充缺失的數值,並通過獨熱編碼(One-Hot Encoding)將分類特徵轉換為數字特徵。


接下來將兩個資料集分開,去掉臨時列,構建一個有 100 個樹的隨機森林(通常,樹越多結果越好,但這也意味著訓練時間的增加),使用計算機的所有 CPU 核心(n_jobs=-1),使用訓練集進行擬合,用擬合的隨機森林來預測測試集的目標變數

這裡的預測結果為小數,而文件中規定,生還為1 遇難為0,我使用了astype將結果轉化為最接近的int值

把結果和它們各自的 Id 放在一個 DataFrame 中,並儲存到 一個csv檔案中

登陸 Kaggle 頁面提交csv檔案即可

本次只是作為隨機森林的一個練習,其實對於這個案例來說,隨機森林並不是一個非常好的解決方法

更多深入學習後可能會對這個案例重新詳細分析~