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

2、注意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)

3、上述代码实现的是,将矩阵的每一列提取出来,然后单独进行操作,最后在拼在一起。可视化的图如下所示。

2. 作用

可以把任意的一个表达式作为一个“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传参数就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持来客网。