如何在Keras中使用Lambda层? [英] How to use lambda layer in keras?

查看:591
本文介绍了如何在Keras中使用Lambda层?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想定义lambda层以将要素与叉积组合,然后合并这些模型,就像无花果一样. ,我该怎么办?

I want to define lambda layer to combine features with cross product, then merge those models,just like the fig. ,What should I do?

测试model_1,获得密度为128的尺寸,使用pywt获得两个64尺寸的特征(cA,cD),然后返回cA * cD//当然,我想合并两个模型,但首先尝试使用model_1.

Test model_1, get 128 dimensions form dense, use pywt get two 64 dimensions feature(cA,cD), then return cA*cD //of course I want to combine two models ,but try model_1 first.

from keras.models import Sequential,Model
from keras.layers import Input,Convolution2D,MaxPooling2D
from keras.layers.core import Dense,Dropout,Activation,Flatten,Lambda
import pywt

def myFunc(x):
    (cA, cD) = pywt.dwt(x, 'db1')
#    x=x*x
    return cA*cD

batch_size=32
nb_classes=3
nb_epoch=20
img_rows,img_cols=200,200
img_channels=1
nb_filters=32
nb_pool=2
nb_conv=3

inputs=Input(shape=(1,img_rows,img_cols))
x=Convolution2D(nb_filters,nb_conv,nb_conv,border_mode='valid',
                  input_shape=(1,img_rows,img_cols),activation='relu')(inputs)
x=Convolution2D(nb_filters,nb_conv,nb_conv,activation='relu')(x)
x=MaxPooling2D(pool_size=(nb_pool,nb_pool))(x)
x=Dropout(0.25)(x)
x=Flatten()(x)
y=Dense(128,activation='relu')(x)
cross=Lambda(myFunc,output_shape=(64,))(y)   
predictions=Dense(nb_classes,activation='softmax')(cross)
model = Model(input=inputs, output=predictions)
model.compile(loss='categorical_crossentropy',optimizer='adadelta',metrics=['accuracy'])

model.fit(X_train,Y_train,batch_size=batch_size,nb_epoch=nb_epoch,
          verbose=1,validation_data=(X_test,Y_test))

抱歉,我可以问一个关于张量的问题吗?

Sorry, can I ask a question about tensor?

import tensorflow as tf
W1 = tf.Variable(np.array([[1,2],[3,4]]))
init = tf.global_variables_initializer()
sess = tf.Session()
sess.run(init)
array = W1.eval(sess)
print (array)

是的!但是,

from keras import backend as K
import numpy as np
kvar=K.variable(np.array([[1,2],[3,4]]))
K.eval(kvar)
print(kvar)

我得到了<CudaNdarrayType(float32, matrix)>kvar.eval()我得到了b'CudaNdarray([[ 1. 2.]\n [ 3. 4.]])'.我使用keras,那么如何使用keras获得类似tensorflow的数组?

I got <CudaNdarrayType(float32, matrix)> and kvar.eval() I got b'CudaNdarray([[ 1. 2.]\n [ 3. 4.]])'. I use keras, so how can I get array like tensorflow using keras?

推荐答案

我可能会复制密集层.代替具有2个128个单位的层,而具有4个64个单位的层.结果是相同的,但是您将能够更好地执行交叉乘积.

I would probaly duplicate the dense layers. Instead of having 2 layers with 128 units, have 4 layers with 64 units. The result is the same, but you will be able to perform the cross products better.

from keras.models import Model

#create dense layers and store their output tensors, they use the output of models 1 and to as input    
d1 = Dense(64, ....)(Model_1.output)   
d2 = Dense(64, ....)(Model_1.output)   
d3 = Dense(64, ....)(Model_2.output)   
d4 = Dense(64, ....)(Model_2.output)   

cross1 = Lambda(myFunc, output_shape=....)([d1,d4])
cross2 = Lambda(myFunc, output_shape=....)([d2,d3])

#I don't really know what kind of "merge" you want, so I used concatenate, there are Add, Multiply and others....
output = Concatenate()([cross1,cross2])
    #use the "axis" attribute of the concatenate layer to define better which axis will be doubled due to the concatenation    

model = Model([Model_1.input,Model_2.input], output)

现在,使用lambda函数:

Now, for the lambda function:

import keras.backend as K

def myFunc(x):
    return x[0] * x[1]

这篇关于如何在Keras中使用Lambda层?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆