python - 如何在 keras 中使用 lambda 层?

标签 python lambda keras-layer

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

enter image description here

测试模型_1,得到128维形式密集,使用pywt得到两个 64 维特征(cA,cD),然后返回 cA*cD//当然我想组合两个模型,但先尝试模型_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 这样的数组?

最佳答案

我可能会复制密集层。不是有 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]

关于python - 如何在 keras 中使用 lambda 层?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44886195/

相关文章:

python - PyPDF2 无法读取非英文字符,在 extractText() 上返回空字符串

python - 当数据库值更改时,Django 发送推送通知

java - 为什么 Java 8 Stream forEach 方法的行为不同?

c# - 用于从列表中删除某些对象的 Lambda 或 LinQ 表达式

machine-learning - 我应该为 Keras 使用哪些层?

python - 如何用python方式在一行中写这个?

python - Django:从数据库中获取一个对象,如果没有匹配项,则为 'None'

c++ - 将 lambda 传递给 void 指定模板失败

python - Keras 'load_model' 与自定义图层对象

machine-learning - ValueError : Error when checking model target: expected dense_4 to have shape (None, 4) 但得到形状为 (13252, 1) 的数组