【问题标题】:How to use lambda layer in keras?如何在 keras 中使用 lambda 层?
【发布时间】:2017-12-06 18:13:22
【问题描述】:

我想定义 lambda 层以将特征与叉积相结合,然后合并这些模型,如图所示。 ,我该怎么办?

测试model_1,得到128维形式dense,使用pywt得到两个64维特征(cA,cD),然后返回cA*cD //当然我想合并两个模型,但是先试试model_1。

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

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

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这样的数组呢?

【问题讨论】:

  • 因此,keras lambda 函数需要所有操作才能使用“张量”。常用操作都列在keras.io/backend中。您必须找到一种以张量方式重写 pywt.dwt 的方法。不幸的是,这不是一件容易的事。我认为这个问题很重要,我无法正确回答。
  • lambda 层是否必须使用 keras 后端功能?我可以将张量转换为数组然后使用pywt.dwt,然后将数组转换为张量吗?
  • 有可能,但这会打断“图表”并带来错误。要转换数组中的张量,请使用“tensorVar.eval()”。要从数组创建张量,请使用“K.variable(arrayVar)”,其中 K 是 keras.backend。
  • 非常感谢!我试试看
  • 试试karr = kvar.eval()

标签: python lambda keras-layer


【解决方案1】:

我可能会复制密集层。不是有 2 层有 128 个单元,而是有 4 层有 64 个单元。结果是相同的,但您将能够更好地执行叉积。

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 函数:

import keras.backend as K

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

【讨论】:

  • 非常感谢!当我使用 model.add(Dense(128)) 获得 128 个维度时,我添加了 model.add(Lambda(wavelets,output_shape=input_shape[0])),但我不知道如何使用 lambda 层。我想使用 wavelets(function:(cA, cD) = pywt.dwt(x, 'db1')) 来获得近似系数和细节系数(它们都是 64 维,如图所示)。然后将近似系数与模型 1 和 2 相乘。最后将近似系数和细节系数与模式 concat 合并。你能帮忙写 lambda 层吗?
  • 抱歉不是叉积,是*
  • 更新了我的答案。
  • 抱歉,output_shape=..?我使用 theano 作为后端,它不能自动推断。
  • 是的,您必须将 output_shape 放在 lambda 层中。如果您使用一维向量,密集层将输出(64,),因此 lambda 中的输出形状也将是(64,)
猜你喜欢
  • 2017-08-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-02-25
  • 2019-09-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多