第 1 部分:參加就有機會贏得超棒獎品
在這個練習中,你會認識 Dense 層。我們用一個有趣的情境來學習吧!想像有個遊戲節目,獎品由神經網路決定。參賽者輸入:
- 兄弟姊妹的人數、
- 今天喝了幾杯咖啡,以及
- 喜不喜歡番茄,
模型就會預測這位參賽者會贏得什麼獎品。
要實作這件事,你會使用 Keras。你需要建立一個模型,其輸入層接受 3 個特徵(兄弟姊妹數為整數、咖啡杯數為整數、是否喜歡番茄為 0 或 1)。接著將輸入送入一個 Dense 層,輸出 3 個機率(也就是贏得汽車、禮品券或什麼都沒有的機率)。
Keras 的 Input、Dense 層以及 Model 物件都已經匯入。你也拿到了一個名為 init 的權重初始化器,會用來初始化 Dense 層。
本練習屬於課程
使用 Keras 進行機器翻譯
練習說明
- 定義一個輸入層,只接受 3 位參賽者(批次大小),且每位參賽者有 3 個輸入:兄弟姊妹人數、咖啡杯數、是否喜歡番茄(輸入大小)。
- 定義一個具有 3 個輸出、
softmax作為啟用函式,且以init作為初始化器的Dense層。 - 使用所定義的模型,對
x計算預測結果。 - 取得每位參賽者機率最高的獎品(以整數表示)。
動手互動練習
試著完成這個範例程式碼,體驗一下這個練習。
# Define an input layer with batch size 3 and input size 3
inp = Input(____=(____,____))
# Get the output of the 3 node Dense layer
pred = ____(____, ____=____, kernel_initializer=init, bias_initializer=init)(inp)
model = Model(inputs=inp, outputs=pred)
names = ["Mark", "John", "Kelly"]
prizes = ["Gift voucher", "Car", "Nothing"]
x = np.array([[5, 0, 1], [0, 3, 1], [2, 2, 1]])
# Compute the model prediction for x
y = ____.____(____)
# Get the most probable class for each sample
classes = np.____(____, ____)
print("\n".join(["{} has probabilities {} and wins {}".format(n,p,prizes[c]) \
for n,p,c in zip(names, y, classes)]))