層是 Keras 中神經網路的基本建構區塊。一個層包含一個張量輸入、張量輸出的計算函數 (層的 call
方法) 和一些狀態,這些狀態保存在 TensorFlow 變數中 (層的權重)。
Layer 實例是可呼叫的,很像函數
import keras
from keras import layers
layer = layers.Dense(32, activation='relu')
inputs = keras.random.uniform(shape=(10, 20))
outputs = layer(inputs)
但與函數不同,層會維護狀態,當層在訓練期間接收到資料時會更新狀態,並儲存在 layer.weights
中
>>> layer.weights
[<KerasVariable shape=(20, 32), dtype=float32, path=dense/kernel>,
<KerasVariable shape=(32,), dtype=float32, path=dense/bias>]
雖然 Keras 提供了廣泛的內建層,但它們無法涵蓋所有可能的使用案例。建立自訂層非常常見,而且非常容易。
請參閱指南 透過子類別化建立新的層和模型 以獲得全面的概述,並參考 基礎 Layer
類別 的文件。