在Keras合并两种不同的深度学习模型

时间:2017-10-31 12:24:55

标签: python deep-learning keras

我有两种不同类型的数据(图像体积和坐标),我想在图像体数据上使用卷积神经网络,然后在此之后我想附加一些额外的信息(即,坐标体积)。

独立地,这应该为我的功能创建一个非常可靠的预测器。我如何使用Keras实现这一点。

我在网上找到的唯一答案要么含糊不清,要么使用我必须使用的弃用方法。但我真的想使用当前的API实现这一点,这样我可以更轻松地保存模型供以后使用。

model = Sequential()
model.add(Conv3D(32, kernel_size=(3, 3, 3),
                 activation='relu',
                 input_shape=input_shape))
model.add(Conv3D(64, (3, 3, 3), activation='relu'))
model.add(MaxPooling3D(pool_size=(2, 2, 2)))
model.add(Dropout(0.25))
model.add(Flatten())
print(model.output_shape)

# The additional data (the coordinates x,y,z)
extra = Sequential()
extra.add(Activation('sigmoid', input_shape=(3,)))
print(extra.output_shape)

merged = Concatenate([model, extra])

# New model should encompass the outputs of the convolutional network and the coordinates that have been merged.
# But how?
new_model = Sequential()
new_model.add(Dense(128, activation='relu'))
new_model.add(Dropout(0.8))
new_model.add(Dense(32, activation='sigmoid'))
new_model.add(Dense(num_classes, activation='softmax'))

new_model.compile(loss=keras.losses.categorical_crossentropy,
              optimizer=keras.optimizers.Adadelta(),
              metrics=['accuracy'])

2 个答案:

答案 0 :(得分:4)

顺序模型不适合创建带分支的模型。

您可以将两个独立模型作为Sequential模型,但是从Concatenate开始,您应该开始使用功能模型API。

我们的想法是获得两个模型的输出张量,并将它们输入其他层以获得新的输出张量。

所以,考虑到你有modelextra

mergedOutput = Concatenate()([model.output, extra.output])

mergetOutput是一个张量。您可以使用此张量创建模型的最后一部分,也可以单独创建最后一部分,并在此张量上调用它。如果你想分别训练每个模型(第二种方法似乎不是你的情况),第二种方法可能会很好。

现在,将新模型创建为功能API模型:

out = Dense(128, activation='relu')(mergetOutput)
out = Dropout(0.8)(out)
out = Dense(32, activation='sigmoid')(out)
out = Dense(num_classes, activation='softmax')(out)

new_model = Model(
    [model.input, extra.input], #model with two input tensors
    out                         #and one output tensor
) 

更简单的方法是获取您已创建的所有三个模型,并使用它们来创建组合模型:

model = Sequential() #your first model
extra = Sequential() #your second model    
new_model = Sequential() #all these three exactly as you did   

#in this case, you just need to add an input shape to new_model, compatible with the concatenated output of the previous models. 
new_model.add(FirstNewModelLayer(...,input_shape=(someValue,)))

像这样加入他们:

mergedOutput = Concatenate()([model.output, extra.output])
finalOutput = new_model(mergedOutput)    

fullModel = Model([model.input,extra.input],finalOutput)

答案 1 :(得分:0)

使用Keras的功能API(https://keras.io/models/model/)。您只需将图层应用于Keras中的合并图层即可。功能API的工作原理如下。你有一个张量,你将一个函数应用于此Tensor。然后递归评估。因为在Keras中几乎所有东西都是张量的,所以效果非常好。

这方面的一个例子是:

activation = Dense(128, activation='relu')(merged)