是否可以使用两个输入的相同模型进行训练?

时间:2017-12-12 12:53:34

标签: keras

你好我对keras有一些疑问。

目前我想实现一些网络

使用相同的cnn模型,并使用两个图像作为cnn模型的输入

并使用两个cnn模型的结果,提供给Dense模型

例如

def cnn_model():
   input = Input(shape=(None, None, 3))
   x = Conv2D(8, (3, 3), strides=(1, 1))(input)
   x = GlobalAvgPool2D()(x)
   model = Model(input, x)

   return model

def fc_model(cnn1, cnn2):
   input_1 = cnn1.output
   input_2 = cnn2.output
   input = concatenate([input_1, input_2])
   x = Dense(1, input_shape=(None, 16))(input)
   x = Activation('sigmoid')(x)
   model = Model([cnn1.input, cnn2.input], x)

   return model

def main():
   cnn1 = cnn_model()
   cnn2 = cnn_model()
   model = fc_model(cnn1, cnn2)
   model.compile(optimizer='adam', loss='mean_squared_error')
   model.fit(x=[image1, image2], y=[1.0, 1.0], batch_size=1, ecpochs=1)

我想实现这样的模型,并训练模型

但我收到如下错误消息:

'所有图层名称都应该是唯一的'

实际上我只想使用一个CNN模型作为特征提取器,最后使用两个特征来预测一个浮点值为0.0~1.0

所以整个系统 - >> 使用两个图像并从同一CNN模型中提取特征,并向Dense模型提供特征以获得一个浮动值

请帮助我实施这个系统以及如何训练..

谢谢

1 个答案:

答案 0 :(得分:0)

请参阅Keras文档中有关共享层的部分:

https://keras.io/getting-started/functional-api-guide/

上述文档中的代码段演示了这一点:

# This layer can take as input a matrix
# and will return a vector of size 64
shared_lstm = LSTM(64)

# When we reuse the same layer instance
# multiple times, the weights of the layer
# are also being reused
# (it is effectively *the same* layer)
encoded_a = shared_lstm(tweet_a)
encoded_b = shared_lstm(tweet_b)

# We can then concatenate the two vectors:
merged_vector = keras.layers.concatenate([encoded_a, encoded_b], axis=-1)

# And add a logistic regression on top
predictions = Dense(1, activation='sigmoid')(merged_vector)

# We define a trainable model linking the
# tweet inputs to the predictions
model = Model(inputs=[tweet_a, tweet_b], outputs=predictions)

model.compile(optimizer='rmsprop',
              loss='binary_crossentropy',
              metrics=['accuracy'])
model.fit([data_a, data_b], labels, epochs=10)
相关问题