TF2.0—tf.keras.layers.Lambda

文章目录

Lambda

官网

tf.keras.layers.Lambda(
    function, output_shape=None, mask=None, arguments=None, **kwargs
)

描述

将任意表达式包装为Layer对象,Lambda层的存在是为了在构建顺序和函数式API模型时可以使用任意的TensorFlow函数。虽然可以在Lambda层中使用变量,但不鼓励这种做法,因为它很容易导致bug
Inherits From: Layer, Module

参数

function
被评估的function
将输入张量作为第一个参数

output_shape
function预期输出形状,如果未明确提供,则可以推断出该参数。可以是元组或函数。
如果是元组,则仅指定向前的第一维
假定样本维与输入相同:output_shape =(input_shape [0],)+ output_shape,
或者输入为None且样本维也为None:output_shape =(None,)+ output_shape
如果是函数,则指定整个形状作为输入形状的函数:output_shape = f(input_shape)

mask
None
或与compute_mask层方法具有相同签名的可调用对象,
或者将作为输出掩码返回的张量

arguments
要传递给函数的关键字参数的可选字典

Input shape

当使用这一层作为模型的第一层时,使用关键字参数input_shape

Output shape

由output_shape参数指定

官方案例

# 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))

猜你喜欢

转载自blog.csdn.net/weixin_46649052/article/details/112705350