開始使用免費開始

張量的流動

如果你已經建立好一個模型,就可以搭配 model.layerstensorflow.keras.backend 來建立函式。給定一個有效的輸入張量,這些函式會回傳對應的輸出張量。

當我們想取得網路在中間層的輸出時,這會非常實用。

例如,若你取得網路第一層的輸入與輸出,就能建立一個 inp_to_out 函式,只針對給定的輸入張量,執行第一層的前向傳播並回傳結果。

現在就來動手做吧!

Banknote Authentication 資料集的 X_test 與其對應的 model 都已預先載入。到主控台輸入 model.summary() 查看模型結構。

本練習屬於課程

Keras 深度學習入門

檢視課程

練習說明

  • tensorflow.keras.backend 匯入為 K
  • 使用 model.layers 串列,取得第一層的輸入與輸出參照。
  • 使用 K.function() 定義一個將 inp 對應到 out 的函式。
  • 印出將 X_test 傳入第 1 層後的結果。

動手互動練習

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

# Import tensorflow.keras backend
import ____

# Input tensor from the 1st layer of the model
inp = ____.____[____].input

# Output tensor from the 1st layer of the model
out = ____.____

# Define a function from inputs to outputs
inp_to_out = K.function([____], [____])

# Print the results of passing X_test through the 1st layer
print(____([____]))
編輯並執行程式碼