欢迎来到代码驿站!

Python代码

当前位置:首页 > 软件编程 > Python代码

keras 使用Lambda 快速新建层 添加多个参数操作

时间:2021-03-12 09:52:49|栏目:Python代码|点击:

keras许多简单操作,都需要新建一个层,使用Lambda可以很好完成需求。

# 额外参数
def normal_reshape(x, shape):
 return K.reshape(x,shape)
 
output = Lambda(normal_reshape, arguments={'shape':(-1, image_seq, 1000)})(output)
output = Lambda(lambda inp: K.mean(inp, axis=1), output_shape=(1000,))(output)

更多参考

补充知识:keras 实现包括batch size所在维度的reshape,使用backend新建一层 针对多输入使用不同batch size折衷解决办法

新建层,可以在此层内使用backend完成想要的功能,如包含batch size维度在内的reshpe:

def backend_reshape(x): return backend.reshape(x, (-1, 5, 256))

使用lambda方法调用层:

vision_model.add(Lambda(backend_reshape, output_shape=(5, 256)))

注意指定输出维度

在多输入问题中,有时两个输入具有不同的batch size,但在keras无法直接实现。我所遇到的问题是,我有两个输入分别是图像输入和问题输入,对于图像输入每个样本是一个图像序列。这就要求我们在把图像序列输入到CNN中时是一张一张图像。

我的解决办法是在输入是把图像序列作为一个样本,等输入进去后,通过上述的reshape方法将图像序列重新拆分成一张张图像输入到CNN,然后在后期处理时重新reshape成一个序列样本。

代码:

image_seq = 4
def preprocess_reshape(x):
 return K.reshape(x, (-1, 224, 224,3))
 
def backend_reshape(x):
 return K.reshape(x, (-1, image_seq, 256))
image_input = Input(shape=(image_seq, 224, 224, 3) , name='input_img')
image_re = Lambda(preprocess_reshape, output_shape=(224,224,3))(image_input)
im_pre = Lambda(preprocess_input, name='preprocessing')(image_re)

vision_model.add(Lambda(backend_reshape, output_shape=(image_seq, 256))) vision_model.add(LSTM(256, kernel_regularizer=l2, recurrent_regularizer=l2))

上一篇:python虚拟环境的安装和配置(virtualenv,virtualenvwrapper)

栏    目:Python代码

下一篇:Python排序算法实例代码

本文标题:keras 使用Lambda 快速新建层 添加多个参数操作

本文地址:http://www.codeinn.net/misctech/78940.html

推荐教程

广告投放 | 联系我们 | 版权申明

重要申明:本站所有的文章、图片、评论等,均由网友发表或上传并维护或收集自网络,属个人行为,与本站立场无关。

如果侵犯了您的权利,请与我们联系,我们将在24小时内进行处理、任何非本站因素导致的法律后果,本站均不负任何责任。

联系QQ:914707363 | 邮箱:codeinn#126.com(#换成@)

Copyright © 2020 代码驿站 版权所有