层是 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 基类 的文档。