如何从相同的Keras层获得不同的输出,然后将它们组合起来?

时间:2017-04-29 05:24:57

标签: tensorflow neural-network keras conv-neural-network keras-layer

基本上,我正在创建一个使用Keras和Tensorflow后端的CNN。我想要插入两个具有相同输入层的图层,然后将它们连接起来,就像这样:

model = Sequential()

model.add(Convolution1D(128, (4), activation='relu',input_shape=(599,128))
model.add(MaxPooling1D(pool_size=(4)))
model.add(Convolution1D(256, (4), activation='relu')
model.add(MaxPooling1D(pool_size=(2)))
model.add(Convolution1D(256, (4), activation='relu')
model.add(MaxPooling1D(pool_size=(2)))
model.add(Convolution1D(512, (4), activation='relu')

# output 1 = GlobalMaxPooling1D() # from last conv layer
# output 2 = GlobalAveragePooling1D() # from last conv layer
# model.add(Concatenate((output 1, output 2))
# at this point output should have a shape of 1024,1 (from 512 * 2)

model.add(Dense(1024))
model.add(Dense(512))

以简单的方式以图形方式显示:

    ...
    cv4
    / \
   /   \
gMaxP|gAvrgP   (each 512,)
   \   /
    \ /
   dense(1024,)

我觉得我错过了一些愚蠢明显的东西。有人可以叫醒我吗?

1 个答案:

答案 0 :(得分:0)

使用Model class API,它应该是这样的:

inputs = Input(shape=(599,128), name='image_input')

x = Convolution1D(128, (4), activation='relu')(inputs)
x = MaxPooling1D(pool_size=(4))(x)
x = Convolution1D(256, (4), activation='relu')(x)
x = MaxPooling1D(pool_size=(2))(x)
x = Convolution1D(256, (4), activation='relu')(x)
x = MaxPooling1D(pool_size=(2))(x)
x = Convolution1D(512, (4), activation='relu')(x)


output_1 = GlobalMaxPooling1D()(x) # from last conv layer
output_2 = GlobalAveragePooling1D()(x) # from last conv layer
x = concatenate([output_1, output_2])
# at this point output should have a shape of 1024,1 (from 512 * 2)

x = Dense(1024)(x)
x = Dense(512)(x)