Lambda
类tf_keras.layers.Lambda(
function, output_shape=None, mask=None, arguments=None, **kwargs
)
将任意表达式封装为 Layer
对象。
引入 Lambda
层是为了在构建 Sequential 模型和 Functional API 模型时,可以将任意表达式用作 Layer
。Lambda
层最适合简单的操作或快速实验。对于更高级的用例,请遵循此指南来子类化 tf.keras.layers.Layer
。
警告:tf.keras.layers.Lambda
层存在(反)序列化限制!
子类化 tf.keras.layers.Layer
而非使用 Lambda
层的主要原因在于模型的保存和检查。Lambda
层通过序列化 Python 字节码进行保存,这从根本上来说是不可移植的。它们只能在其保存时的相同环境中加载。通过重写 get_config()
方法,可以以更可移植的方式保存子类化层。依赖于子类化层的模型也通常更容易可视化和理解。
示例
# add a x -> x^2 layer
model.add(Lambda(lambda x: x ** 2))
# add a layer that returns the concatenation
# of the positive part of the input and
# the opposite of the negative part
def antirectifier(x):
x -= K.mean(x, axis=1, keepdims=True)
x = K.l2_normalize(x, axis=1)
pos = K.relu(x)
neg = K.relu(-x)
return K.concatenate([pos, neg], axis=1)
model.add(Lambda(antirectifier))
关于变量的注意事项
虽然可以在 Lambda 层中使用变量,但不鼓励这种做法,因为它很容易导致错误。例如,考虑以下层
scale = tf.Variable(1.)
scale_layer = tf.keras.layers.Lambda(lambda x: x * scale)
因为 scale_layer
不直接跟踪 scale
变量,它不会出现在 scale_layer.trainable_weights
中,因此如果 scale_layer
在模型中使用,将不会被训练。
更好的模式是编写一个子类化的 Layer
class ScaleLayer(tf.keras.layers.Layer):
def __init__(self, **kwargs):
super().__init__(**kwargs)
self.scale = tf.Variable(1.)
def call(self, inputs):
return inputs * self.scale
总的来说,Lambda
层对于简单的无状态计算非常方便,但任何更复杂的逻辑都应该使用子类化的 Layer。
参数
output_shape = (input_shape[0], ) + output_shape
或者,如果输入是 None
,样本维度也为 None
:output_shape = (None, ) + output_shape
如果是函数,它以输入形状为函数指定整个形状:output_shape = f(input_shape)
compute_mask
层方法签名相同的可调用对象,或者是一个张量,无论输入是什么,该张量都将作为输出掩码返回。输入形状 任意。将此层用作模型中的第一层时,请使用 input_shape 关键字参数(由
整数组成的元组,不包含样本轴)。
输出形状 由 output_shape
参数指定