機器學習實戰:Kaggle泰坦尼克號生存預測 利用決策樹進行預測

語言: CN / TW / HK

本文已參與新人創作禮活動,一起開啟掘金創作之路。

決策樹分類的應用場景非常廣泛,在各行各業都有應用,比如在金融行業可以用決策樹做貸款風險評估,醫療行業可以用決策樹生成輔助診斷,電商行業可以用決策樹對銷售額進行預測等。 我們利用 sklearn 工具中的決策樹分類器解決一個實際的問題:泰坦尼克號乘客的生存預測。

問題描述

泰坦尼克海難是著名的十大災難之一,究竟多少人遇難,各方統計的結果不一。專案全部內容可以到我的github下載:http://github.com/Richard88888/Titanic_competition

具體流程分為以下幾個步驟:在這裡插入圖片描述

  1. 準備階段:我們首先需要對訓練集、測試集的資料進行探索,分析資料質量,並對資料進行清洗,然後通過特徵選擇對資料進行降維,方便後續分類運算;
  2. 分類階段:首先通過訓練集的特徵矩陣、分類結果得到決策樹分類器,然後將分類器應用於測試集。然後我們對決策樹分類器的準確性進行分析,並對決策樹模型進行視覺化。 接下來我們進行一一講解。

首先載入資料

```python

載入資料

train_data = pd.read_csv('train.csv') test_data = pd.read_csv('test.csv') ```

  • 第一步:資料探索

python import pandas as pd print(train_data.info()) # 瞭解資料表的基本情況:行數、列數、每列的資料型別、資料完整度 print('-'*30) print(train_data.describe()) # 瞭解資料表的統計情況:總數、平均值、標準差、最小值、最大值等 print('-'*30) print(train_data.describe(include=['O'])) # 檢視字串型別(非數字)的整體情況 print('-'*30) print(train_data.head()) # 檢視前幾行資料(預設是前5行) print('-'*30) print(train_data.tail()) # 檢視後幾行資料(預設是最後5行) 執行結果

```python

RangeIndex: 891 entries, 0 to 890 Data columns (total 12 columns): PassengerId 891 non-null int64 Survived 891 non-null int64 Pclass 891 non-null int64 Name 891 non-null object Sex 891 non-null object Age 714 non-null float64 SibSp 891 non-null int64 Parch 891 non-null int64 Ticket 891 non-null object Fare 891 non-null float64 Cabin 204 non-null object Embarked 889 non-null object dtypes: float64(2), int64(5), object(5) memory usage: 83.6+ KB None


   PassengerId    Survived     ...           Parch        Fare

count 891.000000 891.000000 ... 891.000000 891.000000 mean 446.000000 0.383838 ... 0.381594 32.204208 std 257.353842 0.486592 ... 0.806057 49.693429 min 1.000000 0.000000 ... 0.000000 0.000000 25% 223.500000 0.000000 ... 0.000000 7.910400 50% 446.000000 0.000000 ... 0.000000 14.454200 75% 668.500000 1.000000 ... 0.000000 31.000000 max 891.000000 1.000000 ... 6.000000 512.329200

[8 rows x 7 columns]

                                      Name   Sex   ...       Cabin Embarked

count 891 891 ... 204 889 unique 891 2 ... 147 3 top Peter, Mrs. Catherine (Catherine Rizk) male ... B96 B98 S freq 1 577 ... 4 644

[4 rows x 5 columns]

PassengerId Survived Pclass ... Fare Cabin Embarked 0 1 0 3 ... 7.2500 NaN S 1 2 1 1 ... 71.2833 C85 C 2 3 1 3 ... 7.9250 NaN S 3 4 1 1 ... 53.1000 C123 S 4 5 0 3 ... 8.0500 NaN S

[5 rows x 12 columns]

 PassengerId  Survived  Pclass    ...      Fare Cabin  Embarked

886 887 0 2 ... 13.00 NaN S 887 888 1 1 ... 30.00 B42 S 888 889 0 3 ... 23.45 NaN S 889 890 1 1 ... 30.00 C148 C 890 891 0 3 ... 7.75 NaN Q

[5 rows x 12 columns] ```

  • 第二步:資料清洗

```python

使用平均年齡來填充年齡中的nan值

train_data['Age'].fillna(train_data['Age'].mean(), inplace=True) test_data['Age'].fillna(test_data['Age'].mean(),inplace=True)

使用票價的均值填充票價中的nan值

train_data['Fare'].fillna(train_data['Fare'].mean(), inplace=True) test_data['Fare'].fillna(test_data['Fare'].mean(),inplace=True) print('-'*30) print(train_data['Embarked'].value_counts())

使用登陸最多的港口來填充港口的nan值

train_data['Embarked'].fillna('S',inplace=True) test_data['Embarked'].fillna('S',inplace=True) ``` 執行結果

```python

S 644 C 168 Q 77 ```

  • 第三步:特徵選擇

```python from sklearn.feature_extraction import DictVectorizer

PassengerId 為乘客編號,對分類沒有作用,可以放棄;Name 為乘客姓名,對分類沒有作用,可以放棄;Cabin 欄位缺失值太多,可以放棄;Ticket 欄位為船票號碼,雜亂無章且無規律,可以放棄。

其餘的欄位包括:Pclass、Sex、Age、SibSp、Parch 和 Fare,這些屬性分別表示了乘客的船票等級、性別、年齡、親戚數量以及船票價格,可能會和乘客的生存預測分類有關係。

features = ['Pclass','Sex','Age','SibSp','Parch','Fare','Embarked'] train_features = train_data[features] train_labels = train_data['Survived'] test_features = test_data[features]

將特徵值中字串表示為0.1表示

dvec = DictVectorizer(sparse=False)

fit_transform() 將特徵向量轉化為特徵值矩陣

train_features = dvec.fit_transform(train_features.to_dict(orient='record'))

檢視dvec轉化後的特徵屬性

print(dvec.feature_names_) ``` 執行結果

python ['Age', 'Embarked=C', 'Embarked=Q', 'Embarked=S', 'Fare', 'Parch', 'Pclass', 'Sex=female', 'Sex=male', 'SibSp']

  • 第四步:構建決策樹模型

```python from sklearn.tree import DecisionTreeClassifier clf = DecisionTreeClassifier(criterion='entropy')

決策樹訓練

clf.fit(train_features,train_labels) ```

  • 第五步:模型預測

```python test_features = dvec.transform(test_features.to_dict(orient='record'))

決策樹預測

pred_labels = clf.predict(test_features).astype(np.int64) print(pred_labels) 執行結果python [0 0 0 1 1 0 0 0 0 0 0 0 1 0 1 1 0 1 1 0 1 1 1 0 1 0 1 1 1 0 0 0 1 0 1 1 0 0 0 1 0 0 0 1 1 0 0 0 1 1 0 0 1 0 1 0 0 0 0 1 0 0 0 1 1 1 0 0 0 1 1 0 0 0 1 0 0 1 0 1 1 0 0 0 0 0 1 0 0 1 0 0 0 0 0 1 1 1 1 1 1 0 0 0 1 0 0 0 1 0 0 0 1 0 1 0 0 1 1 1 1 0 1 0 0 1 0 1 0 0 1 0 0 0 0 0 0 0 0 0 0 1 1 0 0 0 0 0 0 0 1 0 0 1 0 0 1 0 0 0 0 1 1 0 0 1 1 0 1 0 0 0 0 0 0 1 1 1 1 1 0 0 1 0 1 0 1 0 0 0 0 0 1 1 1 0 1 0 0 0 1 1 0 1 0 0 0 0 1 0 0 0 0 1 0 0 0 0 1 0 1 0 1 1 1 0 0 0 0 0 0 1 1 0 1 0 1 1 1 1 1 1 0 0 0 0 1 0 1 0 1 0 0 0 0 0 0 0 1 0 0 0 1 1 0 0 0 0 0 0 1 0 1 1 0 1 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 1 0 1 0 0 0 1 0 0 1 1 1 0 0 0 0 0 0 1 1 0 1 0 0 0 1 0 0 1 0 0 0 0 0 0 0 0 0 1 0 1 0 0 0 1 1 0 0 0 0 0 1 0 0 1 0 1 1 1 1 0 0 1 1 1 0 1 0 0 1 1 0 0 0 0 0 0 0 1 0 1 0 0 1 0 1 1 1 0 0 1 0 1 0 0 1 0 1 0 0 1 0 0 0 0 0 1 0 0 1 0 0 0] ```

  • 結果寫入submission.csv檔案,提交kaggle

python id = test_data['PassengerId'] sub = {'PassengerId': id, 'Survived': pred_labels} submission = pd.DataFrame(sub) submission.to_csv("submission.csv", index=False) 在這裡插入圖片描述

原文連結:http://blog.csdn.net/weixin_46087812/article/details/118736646?spm=1001.2014.3001.5501