定義模型
現在你要在 Keras 中實作第一個模型,並且立刻能在更大的資料集上執行更複雜的神經網路,比前兩章更進一步。
一開始,你會從神經網路的骨架出發,加入一個隱藏層與一個輸出層。接著你會訓練這個模型,看到 Keras 進行最佳化,讓模型持續變好。
作為起點,你要根據產業別、受教育程度與年資等特徵來預測工人的時薪。你可以在名為 df 的 pandas DataFrame 中找到資料集。為了方便起見,df 中除了目標變數以外的所有內容,都已轉成名為 predictors 的 NumPy 陣列。目標變數 wage_per_hour 則已提供為名為 target 的 NumPy 陣列。
在本章所有練習中,我們都已匯入 Sequential 模型建構子、Dense 層建構子,以及 pandas。
本練習屬於課程
Python 深度學習入門
練習說明
- 將
predictors資料的欄數存到n_cols。這已替你完成。 - 先建立一個名為
model的Sequential模型。 - 在
model上使用.add()方法加入一個Dense層。- 加入
50個單元,指定activation='relu',並將input_shape參數設為元組(n_cols,),代表每列資料有n_cols個項目,而可接受任意列數作為輸入。
- 加入
- 再加入另一個
Dense層。這一層應有32個單元,啟用函式為'relu'。 - 最後加入輸出層,亦即只有單一節點的
Dense層。此處不要使用任何啟用函式。
動手互動練習
試著完成這個範例程式碼,體驗一下這個練習。
# Import necessary modules
from tensorflow.keras.layers import Dense
from tensorflow.keras.models import Sequential
# Save the number of columns in predictors: n_cols
n_cols = predictors.shape[1]
# Set up the model: model
model = ____
# Add the first layer
____.____(____(____, ____=____, ____=(____)))
# Add the second layer
____
# Add the output layer
____