层是 Keras 中神经网络的基本构建块。一个层由张量输入-张量输出计算函数(层的 call
方法)和一些状态组成,这些状态保存在 TensorFlow 变量中(层的权重)。
层实例是可调用的,很像函数
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
类 的文档。