TFLearn - 快速開始
在這個教學課程中,您將學習使用 TFLearn 和 TensorFlow 使用他們的個人資訊(例如性別、年齡等)估計鐵達尼號乘客的生還機率。為了解決這個經典機器學習任務,我們將建立一個深層神經網路分類器。
先備知識
確認您已安裝 TensorFlow 和 TFLearn。如果您尚未安裝,請依照下列 指示 進行操作。
概述
簡介
1912 年 4 月 15 日,鐵達尼號在與冰山相撞後沉沒,造成 2224 名乘客和船員中 1502 人喪生。雖然生還與否存在一些運氣因素,但某些群體比其他群體更有可能生還,例如婦女、兒童和上層階級。在本教學課程中,我們進行一項分析以找出這些人是誰。
資料集
讓我們來看看資料集(TFLearn 將自動為您下載)。每個乘客提供下列資訊
VARIABLE DESCRIPTIONS:
survived Survived
(0 = No; 1 = Yes)
pclass Passenger Class
(1 = 1st; 2 = 2nd; 3 = 3rd)
name Name
sex Sex
age Age
sibsp Number of Siblings/Spouses Aboard
parch Number of Parents/Children Aboard
ticket Ticket Number
fare Passenger Fare
以下是從資料集中萃取的一些範例
生還 | 艙等 | 姓名 | 性別 | 年齡 | 兄弟姐妹 | 父母子女 | 船票 | 票價 |
---|---|---|---|---|---|---|---|---|
1 | 1 | 歐巴特,萊昂廷·保琳 | 女性 | 24 | 0 | 0 | PC 17477 | 69.3000 |
0 | 2 | 鮑文納,所羅門先生 | 男性 | 42 | 0 | 0 | 211535 | 13.0000 |
1 | 3 | 巴奇尼,瑪麗·凱薩琳小姐 | 女性 | 5 | 2 | 1 | 2666 | 19.2583 |
0 | 3 | 尤塞夫,吉留斯先生 | 男性 | 45.5 | 0 | 0 | 2628 | 7.2250 |
我們的任務有 2 個類別:「未生還」(類別 0)和「生還」(類別 1),而乘客資料有 8 個特徵。
建立分類器
載入資料
資料集儲存在 csv 檔案中,因此我們可以使用 TFLearn 的 load_csv()
函式將資料從檔案載入 Python list
。我們指定「target_column」參數來指出我們的標籤(生還或未生還)位於第一欄(id:0)。此函式將傳回一個元組:(資料, 標籤)。
import numpy as np
import tflearn
# Download the Titanic dataset
from tflearn.datasets import titanic
titanic.download_dataset('titanic_dataset.csv')
# Load CSV file, indicate that the first column represents labels
from tflearn.data_utils import load_csv
data, labels = load_csv('titanic_dataset.csv', target_column=0,
categorical_labels=True, n_classes=2)
前處理資料
資料是『照樣』給出的,而且需要一些預處理才能準備好放入我們的深度神經網路分類器。
首先,我們將捨棄不太可能在我們的分析中有幫助的欄位。例如,我們假設『name』欄位在我們的任務中不會非常有幫助,因為我們評估船客名稱和其存活的機率不具關聯性。基於這樣的想法,我們捨棄『name』和『ticket』欄位。
接下來,我們需要將我們所有的資料轉換為數值,因為神經網路模型只能在數字上執行操作。然而,我們的資料集包含一些非數值,例如『name』或『sex』欄位。由於『name』欄位已經捨棄,我們只需要處理『sex』欄位即可。在這個簡單的範例中,我們將直接將『0』指定給男性,『1』指定給女性。
以下是預處理函數
# Preprocessing function
def preprocess(data, columns_to_ignore):
# Sort by descending id and delete columns
for id in sorted(columns_to_ignore, reverse=True):
[r.pop(id) for r in data]
for i in range(len(data)):
# Converting 'sex' field to float (id is 1 after removing labels column)
data[i][1] = 1. if data[i][1] == 'female' else 0.
return np.array(data, dtype=np.float32)
# Ignore 'name' and 'ticket' columns (id 1 & 6 of data array)
to_ignore=[1, 6]
# Preprocess data
data = preprocess(data, to_ignore)
建立深層神經網路
我們正在使用 TFLearn 建構一個 3 層神經網路。我們需要指定輸入資料的形狀。在我們的範例中,每個範例共有 6 個特徵,並且我們將處理每批範例以儲存記憶體,所以我們的資料輸入形狀為 [None, 6](『None』代表未知維度,所以我們可以變更在批次處理中處理的範例總數)。
# Build neural network
net = tflearn.input_data(shape=[None, 6])
net = tflearn.fully_connected(net, 32)
net = tflearn.fully_connected(net, 32)
net = tflearn.fully_connected(net, 2, activation='softmax')
net = tflearn.regression(net)
訓練
TFLearn 提供一個模型包裝器『DNN』,可以自動執行神經網路分類器任務,例如訓練、預測、儲存/復原等… 我們將執行 10 個 epochs(網路將查看所有資料 10 次)且批次大小為 16。
# Define model
model = tflearn.DNN(net)
# Start training (apply gradient descent algorithm)
model.fit(data, labels, n_epoch=10, batch_size=16, show_metric=True)
輸出
---------------------------------
Run id: MG9PV8
Log directory: /tmp/tflearn_logs/
---------------------------------
Training samples: 1309
Validation samples: 0
--
Training Step: 82 | total loss: 0.64003
| Adam | epoch: 001 | loss: 0.64003 - acc: 0.6620 -- iter: 1309/1309
--
Training Step: 164 | total loss: 0.61915
| Adam | epoch: 002 | loss: 0.61915 - acc: 0.6614 -- iter: 1309/1309
--
Training Step: 246 | total loss: 0.56067
| Adam | epoch: 003 | loss: 0.56067 - acc: 0.7171 -- iter: 1309/1309
--
Training Step: 328 | total loss: 0.51807
| Adam | epoch: 004 | loss: 0.51807 - acc: 0.7799 -- iter: 1309/1309
--
Training Step: 410 | total loss: 0.47475
| Adam | epoch: 005 | loss: 0.47475 - acc: 0.7962 -- iter: 1309/1309
--
Training Step: 492 | total loss: 0.51677
| Adam | epoch: 006 | loss: 0.51677 - acc: 0.7701 -- iter: 1309/1309
--
Training Step: 574 | total loss: 0.48988
| Adam | epoch: 007 | loss: 0.48988 - acc: 0.7891 -- iter: 1309/1309
--
Training Step: 656 | total loss: 0.55073
| Adam | epoch: 008 | loss: 0.55073 - acc: 0.7427 -- iter: 1309/1309
--
Training Step: 738 | total loss: 0.50242
| Adam | epoch: 009 | loss: 0.50242 - acc: 0.7854 -- iter: 1309/1309
--
Training Step: 820 | total loss: 0.41557
| Adam | epoch: 010 | loss: 0.41557 - acc: 0.8110 -- iter: 1309/1309
--
我們的模型完成訓練且整體準確度約為 81%,這表示它可以預測總乘客數中 81% 的正確結果(是否存活)。
測試模型
現在該試試我們的模型了。好玩的是,我們以鐵達尼號電影主角(李奧納多狄卡皮歐和凱特溫絲蕾)為例,並計算他們存活的機率(第 1 類)。
# Let's create some data for DiCaprio and Winslet
dicaprio = [3, 'Jack Dawson', 'male', 19, 0, 0, 'N/A', 5.0000]
winslet = [1, 'Rose DeWitt Bukater', 'female', 17, 1, 2, 'N/A', 100.0000]
# Preprocess data
dicaprio, winslet = preprocess([dicaprio, winslet], to_ignore)
# Predict surviving chances (class 1 results)
pred = model.predict([dicaprio, winslet])
print("DiCaprio Surviving Rate:", pred[0][1])
print("Winslet Surviving Rate:", pred[1][1])
輸出
DiCaprio Surviving Rate: 0.13849584758281708
Winslet Surviving Rate: 0.92201167345047
令人驚艷!我們的模型準確地預測了電影的結局。儘管李奧納多狄卡皮歐的存活機率較低,但凱特溫絲蕾的存活機率卻很高。
更一般來說,透過這個研究可以看出第一等艙的女性和孩童乘客擁有最高的存活機率,而三等艙的男性乘客擁有最低的存活機率。
原始碼
from __future__ import print_function
import numpy as np
import tflearn
# Download the Titanic dataset
from tflearn.datasets import titanic
titanic.download_dataset('titanic_dataset.csv')
# Load CSV file, indicate that the first column represents labels
from tflearn.data_utils import load_csv
data, labels = load_csv('titanic_dataset.csv', target_column=0,
categorical_labels=True, n_classes=2)
# Preprocessing function
def preprocess(data, columns_to_ignore):
# Sort by descending id and delete columns
for id in sorted(columns_to_ignore, reverse=True):
[r.pop(id) for r in data]
for i in range(len(data)):
# Converting 'sex' field to float (id is 1 after removing labels column)
data[i][1] = 1. if data[i][1] == 'female' else 0.
return np.array(data, dtype=np.float32)
# Ignore 'name' and 'ticket' columns (id 1 & 6 of data array)
to_ignore=[1, 6]
# Preprocess data
data = preprocess(data, to_ignore)
# Build neural network
net = tflearn.input_data(shape=[None, 6])
net = tflearn.fully_connected(net, 32)
net = tflearn.fully_connected(net, 32)
net = tflearn.fully_connected(net, 2, activation='softmax')
net = tflearn.regression(net)
# Define model
model = tflearn.DNN(net)
# Start training (apply gradient descent algorithm)
model.fit(data, labels, n_epoch=10, batch_size=16, show_metric=True)
# Let's create some data for DiCaprio and Winslet
dicaprio = [3, 'Jack Dawson', 'male', 19, 0, 0, 'N/A', 5.0000]
winslet = [1, 'Rose DeWitt Bukater', 'female', 17, 1, 2, 'N/A', 100.0000]
# Preprocess data
dicaprio, winslet = preprocess([dicaprio, winslet], to_ignore)
# Predict surviving chances (class 1 results)
pred = model.predict([dicaprio, winslet])
print("DiCaprio Surviving Rate:", pred[0][1])
print("Winslet Surviving Rate:", pred[1][1])