開始使用免費開始

分類模型的最後一步

你現在要使用泰坦尼克號資料集建立一個分類模型。資料已預先載入為名為 df 的 DataFrame。你會根據乘客的資訊來預測哪些人存活。

預測用的變數已存於 NumPy 陣列 predictors。要預測的目標在 df.survived,不過你需要先把它轉換成 Keras 可用的格式。預測特徵的數量存於 n_cols

在這裡,你會使用 'sgd' 最佳化器,它代表 隨機梯度下降(Stochastic Gradient Descent)。你會在下一章學到更多細節!

本練習屬於課程

Python 深度學習入門

檢視課程

練習說明

  • 使用 to_categorical() 函式將 df.survived 轉換為類別變數。
  • 指定一個名為 modelSequential 模型。
  • 加入一個具有 32 個節點的 Dense 隱藏層。activation 使用 'relu'input_shape 設為 (n_cols,)
  • 加入 Dense 輸出層。因為有兩種可能的結果,單元數設為 2;而且這是分類模型,所以 activation 應為 'softmax'
  • 編譯模型,optimizer 使用 'sgd',損失函式使用 'categorical_crossentropy',並設定 metrics=['accuracy'],以在每個 epoch 結束時顯示正確率(正確預測所佔的比例)。
  • 使用 predictorstarget 來訓練模型(fit)。

動手互動練習

試著完成這個範例程式碼,體驗一下這個練習。

# Import necessary modules
from tensorflow.keras.layers import Dense
from tensorflow.keras.models import Sequential
from tensorflow.keras.utils import to_categorical

# Convert the target to categorical: target
target = ____

# Set up the model
model = ____

# Add the first layer
____

# Add the output layer
____

# Compile the model
____

# Fit the model
____
編輯並執行程式碼