在keras中添加两层的输出

时间:2018-01-11 06:10:43

标签: python-2.7 deep-learning keras keras-layer

我有一个似乎在Keras没有直接解决方案的问题。 我的服务器在ubuntu 14.04上运行,keras使用后端tensorflow。

问题在于:

我有两个形状的输入缩量:Input(shape=(30,125,1)),每个都输入下面三层的级联:

CNN1 = Conv2D(filters = 8, kernel_size = (1,64) , padding = "same" , activation = "relu" )
CNN2 = Conv2D(filters = 8, kernel_size = (8,1) , padding = "same" , activation = "relu" )
pool = MaxPooling2D((2, 2))

用于各个输入的每个获得的输出张量具有形状(None, 15, 62, 8)。现在,我希望为每个过滤器的两个输入添加每个(15,62)矩阵,并再次获得维度输出(None, 15, 62, 8)

我尝试使用Lambda图层使用以下代码行,但它会抛出错误。

from keras import backend as K
from keras.layers import Lambda

def myadd(x):
    increment = x[1]
    result = K.update_add(x[0], increment)
    return result

in_1 = Input(shape=(30,125,1))
in_1CNN1 = CNN1(in_1)
in_1CNN2 = CNN2(in_1CNN1)
in_1pool = pool(in_1CNN2)

in_2 = Input(shape=(30,125,1))
in_2CNN1 = CNN1(in_2)
in_2CNN2 = CNN2(in_2CNN1)
in_2pool = pool(in_2CNN2)

y1 =y1.astype(np.float32) # an input regression label array of shape (numsamples,1) loaded from a mat file

out1 = Lambda(myadd, output_shape=(None, 15, 62, 8))([in_1pool,in_2pool])
a= keras.layers.Flatten()(out1)

pre1 = Dense(1000, activation='sigmoid')(a)
pre2 =Dropout(0.2)(pre1)
predictions = Dense(1, activation='sigmoid')(pre2)

model = Model(inputs=[in_1,in_2], outputs=predictions)
model.compile(optimizer='sgd',loss='mean_squared_error')
model.fit([inputdata1,inputdata2], y1, epochs=20, validation_split=0.5)
#inputdata1, inputdata2 are arrays loaded from a mat file and are each of shape (5169, 30, 125, 1)

错误突出显示如下:

Traceback (most recent call last):
  File "keras_workshop/keras_multipleinputs_multiple CNN.py", line 225, in <module>
    out1 = Lambda(myadd, output_shape=(None, 15, 62, 8))([in_1pool,in_2pool])
  File "/home/tharun/anaconda2/lib/python2.7/site-packages/keras/engine/topology.py", line 603, in __call__
    output = self.call(inputs, **kwargs)
  File "/home/tharun/anaconda2/lib/python2.7/site-packages/keras/layers/core.py", line 651, in call
    return self.function(inputs, **arguments)
  File "keras_workshop/keras_multipleinputs_multiple CNN.py", line 75, in myadd
    result = K.update_add(x[0], increment)
  File "/home/tharun/anaconda2/lib/python2.7/site-packages/keras/backend/tensorflow_backend.py", line 958, in update_add
    return tf.assign_add(x, increment)
  File "/home/tharun/anaconda2/lib/python2.7/site-packages/tensorflow/python/ops/state_ops.py", line 245, in assign_add
    return ref.assign_add(value)
AttributeError: 'Tensor' object has no attribute 'assign_add'

1 个答案:

答案 0 :(得分:1)

尝试使用Keras提供的Add() layeradd() function

  

添加

keras.layers.Add()  
     

添加输入列表的图层。

     

它将张量列表作为输入,所有张量都相同,并返回单个张量(也是相同的形状)。

  

添加

keras.layers.add(inputs)
     

添加图层的功能界面。

     

参数

     

输入:输入张量列表(至少2个)    ** kwargs :标准图层关键字参数。

     

返回

     

张量,即输入的总和。