0
$\begingroup$

I have two CNN models, both of them are trained on the same dataset.

How do I combine/ensemble both to make predictions on test data?

# Load Keras Models

model1 = tf.keras.models.load_model('/kaggle/input/models/model1.h5')
model2 = tf.keras.models.load_model('/kaggle/input/models/basic_cnn.h5')

How to combine these 2 models to make model3 ?

I have to use predict_generator function to predict from the ensembled model3.

$\endgroup$
1
$\begingroup$

You can put a dense layer combining both outputs.

model1 = tf.keras.models.load_model('/kaggle/input/models/model1.h5')
model2 = tf.keras.models.load_model('/kaggle/input/models/basic_cnn.h5')

inputs = tf.keras.layers.Input(shape=input_shape)
combined = tf.keras.layers.Concatenate()([model1(inputs), model2(inputs)])
outputs = tf.keras.layers.Dense(n_outputs)(combined)

model3 = tf.keras.models.Model(inputs, outputs)

Set input_shape and n_output accordingly to your data and targets.

You should then freeze your pre-trained weights and train the final dense layer to correctly choose which weight to assign to outputs of your models.

model1.trainable = False
model2.trainable = False

model3.fit(your_data)
$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.