1. 程式人生 > 程式設計 >keras Lambda自定義層實現資料的切片方式,Lambda傳引數

keras Lambda自定義層實現資料的切片方式,Lambda傳引數

1、程式碼如下:

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,arguments={'index':1})(a)
x1 = Reshape((4,1,1))(x1)
x2 = Reshape((4,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)

2、注意Lambda 是可以進行引數傳遞的,傳遞的方式如下程式碼所述:

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

如上,index是引數,通過字典將引數傳遞進去.

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

3、上述程式碼實現的是,將矩陣的每一列提取出來,然後單獨進行操作,最後在拼在一起。視覺化的圖如下所示。

keras Lambda自定義層實現資料的切片方式,Lambda傳引數

補充知識:tf.keras.layers.Lambda()——匿名函式層解析

1. 引數列表

keras Lambda自定義層實現資料的切片方式,Lambda傳引數

2. 作用

keras Lambda自定義層實現資料的切片方式,Lambda傳引數

可以把任意的一個表示式作為一個“Layer”物件

Lambda層之所以存在是因為它可以在構建Squential時使用任意的函式或者說tensorflow 函式。

在我們需要完成一些簡單的操作(例如VAE中的重取樣)的情況下,Lambda層再適合不過了。

3. 舉個栗子(VAE)

可以看到通過在encoder和decoder中間加入一個Lambda層使得encoder和decoder連線起來,很方便

def sampling(agrs):
  mean,logvar = agrs[0],agrs[1]
  eps = tf.random.normal(tf.shape(mean))
  return mean + eps*tf.exp(logvar * 0.5)

# 編碼階段
  
x = layers.Input(shape=(784,)) # 輸入層
  
h1 = layers.Dense(200,activation='softplus')(x)
h2 = layers.Dense(200,activation='softplus')(h1)
# 均值和方差層不需要啟用函式
mean = layers.Dense(latent_dimension)(h2)
log_var = layers.Dense(latent_dimension)(h2)
  
# 將取樣過程看成一個Lambda層,這裡利用自定義的sampling函式
z = layers.Lambda(sampling,output_shape=(latent_dimension,))([mean,log_var])
  
# 解碼階段
h3 = layers.Dense(200,activation='softplus')
h4 = layers.Dense(200,activation='softplus')
h5 = layers.Dense(200,activation='softplus')
# No activation
end = layers.Dense(784)
z1 = h3(z)
z2 = h4(z1)
z3 = h5(z2)
out = end(z3)
  
# 建立模型
model = tf.keras.Model(x,out)

4. Lambda層的缺點

Lambda層雖然很好用,但是它不能去更新我們模型的配置資訊,就是不能重寫'model.get_config()'方法

所以tensorflow提議,儘量使用自定義層(即tf.keras.layers的子類)

關於自定義層,我的部落格有一期會專門講

總結

當網路需要完成一些簡單的操作時,可以考慮使用Lambda層。

以上這篇keras Lambda自定義層實現資料的切片方式,Lambda傳引數就是小編分享給大家的全部內容了,希望能給大家一個參考,也希望大家多多支援我們。