1. 程式人生 > 其它 >TF2.0—tf.keras.layers.Lambda

TF2.0—tf.keras.layers.Lambda

技術標籤:TFLambda

文章目錄

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