如何在keras中连接两层?


93

我有一个具有两层的神经网络的示例。第一层有两个参数,并有一个输出。第二个参数应接受一个参数作为第一层的结果,并附加一个参数。它看起来应该像这样:

x1  x2  x3
 \  /   /
  y1   /
   \  /
    y2

因此,我创建了一个具有两层的模型,并尝试将它们合并,但它返回一个错误:The first layer in a Sequential model must get an "input_shape" or "batch_input_shape" argument.在line上result.add(merged)

模型:

first = Sequential()
first.add(Dense(1, input_shape=(2,), activation='sigmoid'))

second = Sequential()
second.add(Dense(1, input_shape=(1,), activation='sigmoid'))

result = Sequential()
merged = Concatenate([first, second])
ada_grad = Adagrad(lr=0.1, epsilon=1e-08, decay=0.0)
result.add(merged)
result.compile(optimizer=ada_grad, loss=_loss_tensor, metrics=['accuracy'])

Answers:


120

之所以会出现错误resultSequential()是因为定义为只是模型的容器,而尚未定义输入。

给定您要构建的集合,result以接受第三个输入x3

first = Sequential()
first.add(Dense(1, input_shape=(2,), activation='sigmoid'))

second = Sequential()
second.add(Dense(1, input_shape=(1,), activation='sigmoid'))

third = Sequential()
# of course you must provide the input to result with will be your x3
third.add(Dense(1, input_shape=(1,), activation='sigmoid'))

# lets say you add a few more layers to first and second.
# concatenate them
merged = Concatenate([first, second])

# then concatenate the two outputs

result = Concatenate([merged,  third])

ada_grad = Adagrad(lr=0.1, epsilon=1e-08, decay=0.0)

result.compile(optimizer=ada_grad, loss='binary_crossentropy',
               metrics=['accuracy'])

但是,构建具有这种输入结构类型的模型的首选方法是使用功能性api

这是您的入门要求的实现:

from keras.models import Model
from keras.layers import Concatenate, Dense, LSTM, Input, concatenate
from keras.optimizers import Adagrad

first_input = Input(shape=(2, ))
first_dense = Dense(1, )(first_input)

second_input = Input(shape=(2, ))
second_dense = Dense(1, )(second_input)

merge_one = concatenate([first_dense, second_dense])

third_input = Input(shape=(1, ))
merge_two = concatenate([merge_one, third_input])

model = Model(inputs=[first_input, second_input, third_input], outputs=merge_two)
ada_grad = Adagrad(lr=0.1, epsilon=1e-08, decay=0.0)
model.compile(optimizer=ada_grad, loss='binary_crossentropy',
               metrics=['accuracy'])

要在评论中回答问题:

1)结果和合并如何连接?假设您是说它们如何连接。

串联的工作方式如下:

  a        b         c
a b c   g h i    a b c g h i
d e f   j k l    d e f j k l

即行只是连接在一起。

2)现在,x1输入到第一,x2输入到第二,x3输入到第三。


resultmerged(或merged2)层在答案的第一部分如何相互连接?
rdo

第二个问题。按照我的理解x1,并x2为输入first_inputx3third_input。什么事second_input
rdo

1
second_input通过 Dense层并与之相连,first_inputDense层也通过层。 third_input穿过密集层,并与之前的串联结果(merged)串联
-parsethis

2
@putonspectacles使用功能性API的第二种方法有效,但是,在Keras 2.0.2中,使用序列模型的第一种方法不适用于我。我已经粗略地检查了实现,并且调用“ Concatenate([...])”并没有多大作用,此外,您不能将其添加到顺序模型中。我实际上认为,在更新Keras之前,仍然需要使用已描述的方法“ Merge([...],'concat')”。你怎么看?
LFish

2
Keras中的Concatenate()concatenate()layer有什么区别?
Leevo

8

添加到上面接受的答案,以便对正在使用的人有所帮助 tensorflow 2.0


import tensorflow as tf

# some data
c1 = tf.constant([[1, 1, 1], [2, 2, 2]], dtype=tf.float32)
c2 = tf.constant([[2, 2, 2], [3, 3, 3]], dtype=tf.float32)
c3 = tf.constant([[3, 3, 3], [4, 4, 4]], dtype=tf.float32)

# bake layers x1, x2, x3
x1 = tf.keras.layers.Dense(10)(c1)
x2 = tf.keras.layers.Dense(10)(c2)
x3 = tf.keras.layers.Dense(10)(c3)

# merged layer y1
y1 = tf.keras.layers.Concatenate(axis=1)([x1, x2])

# merged layer y2
y2 = tf.keras.layers.Concatenate(axis=1)([y1, x3])

# print info
print("-"*30)
print("x1", x1.shape, "x2", x2.shape, "x3", x3.shape)
print("y1", y1.shape)
print("y2", y2.shape)
print("-"*30)

结果:

------------------------------
x1 (2, 10) x2 (2, 10) x3 (2, 10)
y1 (2, 20)
y2 (2, 30)
------------------------------

7

您可以尝试 model.summary()(请注意concatenate_XX(连接)层的大小)

# merge samples, two input must be same shape
inp1 = Input(shape=(10,32))
inp2 = Input(shape=(10,32))
cc1 = concatenate([inp1, inp2],axis=0) # Merge data must same row column
output = Dense(30, activation='relu')(cc1)
model = Model(inputs=[inp1, inp2], outputs=output)
model.summary()

# merge row must same column size
inp1 = Input(shape=(20,10))
inp2 = Input(shape=(32,10))
cc1 = concatenate([inp1, inp2],axis=1)
output = Dense(30, activation='relu')(cc1)
model = Model(inputs=[inp1, inp2], outputs=output)
model.summary()

# merge column must same row size
inp1 = Input(shape=(10,20))
inp2 = Input(shape=(10,32))
cc1 = concatenate([inp1, inp2],axis=1)
output = Dense(30, activation='relu')(cc1)
model = Model(inputs=[inp1, inp2], outputs=output)
model.summary()

您可以在此处查看笔记本的详细信息:https : //nbviewer.jupyter.org/github/anhhh11/DeepLearning/blob/master/Concanate_two_layer_keras.ipynb


3
Keras中的Concatenate()concatenate()layer有什么区别?
Leevo

1
您是否知道差异,一种是Keras类,另一种是张量流方法
abacusreader
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.