keras 使用Lambda 快速新建层 添加多个参数操作
keras许多简单操作,都需要新建一个层,使用Lambda可以很好完成需求。
#额外参数 defnormal_reshape(x,shape): returnK.reshape(x,shape) output=Lambda(normal_reshape,arguments={'shape':(-1,image_seq,1000)})(output) output=Lambda(lambdainp:K.mean(inp,axis=1),output_shape=(1000,))(output)
更多参考
补充知识:keras实现包括batchsize所在维度的reshape,使用backend新建一层针对多输入使用不同batchsize折衷解决办法
新建层,可以在此层内使用backend完成想要的功能,如包含batchsize维度在内的reshpe:
defbackend_reshape(x):returnbackend.reshape(x,(-1,5,256))
使用lambda方法调用层:
vision_model.add(Lambda(backend_reshape,output_shape=(5,256)))
注意指定输出维度
在多输入问题中,有时两个输入具有不同的batchsize,但在keras无法直接实现。我所遇到的问题是,我有两个输入分别是图像输入和问题输入,对于图像输入每个样本是一个图像序列。这就要求我们在把图像序列输入到CNN中时是一张一张图像。
我的解决办法是在输入是把图像序列作为一个样本,等输入进去后,通过上述的reshape方法将图像序列重新拆分成一张张图像输入到CNN,然后在后期处理时重新reshape成一个序列样本。
代码:
image_seq=4 defpreprocess_reshape(x): returnK.reshape(x,(-1,224,224,3)) defbackend_reshape(x): returnK.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))
以上这篇keras使用Lambda快速新建层添加多个参数操作就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持毛票票。