keras Lambda 層

Lambda層

keras.layers.core.Lambda(function, output_shape=None, mask=None, arguments=None)

本函數用以對上一層的輸出施以任何Theano/TensorFlow表達式函數

若是你只是想對流經該層的數據作個變換,而這個變換自己沒有什麼須要學習的參數,那麼直接用Lambda Layer是最合適的了。學習

導入的方法是 spa

from keras.layers.core import Lambda

 Lambda函數接受兩個參數,第一個是輸入張量對輸出張量的映射函數,第二個是輸入的shape對輸出的shape的映射函數。.net

參數

  • function:要實現的函數,該函數僅接受一個變量,即上一層的輸出code

  • output_shape:函數應該返回的值的shape,能夠是一個tuple,也能夠是一個根據輸入shape計算輸出shape的函數orm

  • mask: 掩膜blog

  • arguments:可選,字典,用來記錄向函數中傳遞的其餘關鍵字參數rem

例子

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

def antirectifier_output_shape(input_shape):
    shape = list(input_shape)
    assert len(shape) == 2  # only valid for 2D tensors
    shape[-1] *= 2
    return tuple(shape)

model.add(Lambda(antirectifier,
         output_shape=antirectifier_output_shape))

輸入shape

任意,當使用該層做爲第一層時,要指定input_shapeget

輸出shape

output_shape參數指定的輸出shape,當使用tensorflow時可自動推斷input

================================================

keras Lambda自定義層實現數據的切片,Lambda傳參數

一、代碼以下:

import numpy as np
from keras.models import Sequential
from keras.layers import Dense, Activation,Reshape
from keras.layers import merge
from keras.utils.visualize_util import plot
from keras.layers import Input, Lambda
from keras.models import Model

def slice(x,index):
  return x[:,:,index]

a = Input(shape=(4,2))
x1 = Lambda(slice,output_shape=(4,1),arguments={'index':0})(a)
x2 = Lambda(slice,output_shape=(4,1),arguments={'index':1})(a)
x1 = Reshape((4,1,1))(x1)
x2 = Reshape((4,1,1))(x2)
output = merge([x1,x2],mode='concat')
model
= Model(a, output) x_test = np.array([[[1,2],[2,3],[3,4],[4,5]]]) print model.predict(x_test) plot(model, to_file='lambda.png',show_shapes=True)

二、注意Lambda 是能夠進行參數傳遞的,傳遞的方式以下代碼所述:

def slice(x,index):
    return x[:,:,index]

 如上,index是參數,經過字典將參數傳遞進去.

x1 = Lambda(slice,output_shape=(4,1),arguments={'index':0})(a)
x2 = Lambda(slice,output_shape=(4,1),arguments={'index':1})(a)

三、上述代碼實現的是,將矩陣的每一列提取出來,而後單獨進行操做,最後在拼在一塊兒。可視化的圖以下所示。

 

 
 

 

參考:

https://blog.csdn.net/hewb14/article/details/53414068

https://blog.csdn.net/lujiandong1/article/details/54936185

https://keras-cn.readthedocs.io/en/latest/layers/core_layer/

來自爲知筆記(Wiz)

相關文章
相關標籤/搜索