# Merge two models

**URL:** <https://discuss.ai.google.dev/t/merge-two-models/18451>\
**Category:** General Discussion\
**Tags:** models\
**Created:** [April 27, 2023, 12:19pm UTC](https://discuss.ai.google.dev/t/merge-two-models/18451 "2023-04-27T12:19:15Z")\
**Posts on this page:** 8\
**Page:** 1

<div class="post-metadata">

**Author:** ![youb](https://d1dlmcr85iqnpo.cloudfront.net/user_avatar/discuss.ai.google.dev/youb/32/14345_2.png) [@youb](https://discuss.ai.google.dev/u/youb)\
**Post date:** [April 27, 2023, 12:19pm UTC](https://discuss.ai.google.dev/t/merge-two-models/18451/1 "2023-04-27T12:19:16Z")

</div>

Hi,  
How can I implement this architecture in image bellow.

 ![schema_](https://d3qe71uytubmmx.cloudfront.net/original/2X/9/9e6b2648e51320e8a91a9a9ff02f17d0daabca5b.png)

I really appreciate your help;  
Thank you

---

<div class="post-metadata">

**Author:** ![Kiran\_Sai\_Ramineni](https://d1dlmcr85iqnpo.cloudfront.net/user_avatar/discuss.ai.google.dev/kiran_sai_ramineni/32/8859_2.png) [@Kiran\_Sai\_Ramineni](https://discuss.ai.google.dev/u/Kiran_Sai_Ramineni)\
**Post date:** [April 27, 2023, 1:00pm UTC](https://discuss.ai.google.dev/t/merge-two-models/18451/3 "2023-04-27T13:00:55Z")

</div>

Hi @youb, Once you have defined your 2 models. For example

```auto
import tensorflow as tf
vgg_model = tf.keras.applications.VGG16(weights='imagenet', include_top=False, input_shape=(224, 224, 3))
resnet = tf.keras.applications.ResNet50(include_top=False, weights='imagenet', input_shape=(224, 224, 3))

model1=tf.keras.Sequential([
    vgg_model,
    tf.keras.layers.GlobalAveragePooling2D(),
    tf.keras.layers.Dense(1024, activation='relu'),
    tf.keras.layers.Dense(512, activation='relu')
])

model2=tf.keras.Sequential([
    resnet,
    tf.keras.layers.Flatten(),
    tf.keras.layers.Dense(512, activation='relu')
])

```

Then to do average of the last layers of 2 models and adding the remaining layers, you can do it by

```auto
merged_model=tf.keras.layers.Average()([model1.output, model2.output])
merged_model=tf.keras.layers.Dense(512,activation='relu')(merged_model)
merged_model=tf.keras.layers.Dropout(0.5)(merged_model)
merged_model=tf.keras.layers.Dense(3,activation='relu')(merged_model)

model = tf.keras.models.Model(inputs=[model1.output, model2.output], outputs=merged_model)

```

Please refer to this [gist](https://colab.research.google.com/gist/kiransair/26c8c2f93f1354084477be7eea6935c0/tf_forum_16466.ipynb) for working code example. Thank You.

---

<div class="post-metadata">

**Author:** ![youb](https://d1dlmcr85iqnpo.cloudfront.net/user_avatar/discuss.ai.google.dev/youb/32/14345_2.png) [@youb](https://discuss.ai.google.dev/u/youb)\
**Post date:** [April 27, 2023, 4:03pm UTC](https://discuss.ai.google.dev/t/merge-two-models/18451/4 "2023-04-27T16:03:15Z")

</div>

Hi @Kiran_Sai_Ramineni  
thank you for code;  
please how to train this model; is I should train each model alone, I mean model1, then model2 and after merged\_model;  
I have tried to compile and train the merged\_model; I got an error  
 ![14589](https://d3qe71uytubmmx.cloudfront.net/optimized/2X/7/71aaf0636246b3985a6302857c659401ad131ec3_2_690x55.png)

Thank you

---

<div class="post-metadata">

**Author:** ![youb](https://d1dlmcr85iqnpo.cloudfront.net/user_avatar/discuss.ai.google.dev/youb/32/14345_2.png) [@youb](https://discuss.ai.google.dev/u/youb)\
**Post date:** [April 27, 2023, 6:51pm UTC](https://discuss.ai.google.dev/t/merge-two-models/18451/5 "2023-04-27T18:51:55Z")

</div>

I have tried this but I’m not sure:  
import tensorflow as tf

from tensorflow.keras.layers import Dense, Dropout, Input, GlobalAveragePooling2D, Average, TimeDistributed, Average, Flatten

from tensorflow.keras.models import Model

from tensorflow.keras.applications.resnet50 import ResNet50

import tensorflow\_hub as hub

# Load the ResNet50 model with pre-trained ImageNet weights

resnet = ResNet50(weights=“imagenet”, include\_top=False, input\_tensor=Input(shape=(224, 224, 3)))

resnet.trainable = False

# Load the ViT-B16 model

vit16 = hub.KerasLayer(“[Sayak | vision\_transformer | Kaggle](https://tfhub.dev/sayakpaul/vit_b16_fe/1)”, trainable=False)

# Define the inputs

inputs = Input(shape=(10, 224, 224, 3))

# Extract features from ResNet50 and ViT-B16 models

resnet\_features = TimeDistributed(resnet)(inputs)

resnet\_features = TimeDistributed(GlobalAveragePooling2D())(resnet\_features)

resnet\_features = Flatten()(resnet\_features)

resnet\_features = Dense(1024)(resnet\_features)

resnet\_features = Dense(512)(resnet\_features)

vit\_features = TimeDistributed(vit16)(inputs)

#vit\_features = TimeDistributed(tf.keras.layers.LayerNormalization())(vit\_features)

vit\_features = Flatten()(vit\_features)

vit\_features = Dense(512)(vit\_features)

# Take the average of the features

averaged\_features = Average()([resnet\_features, vit\_features])

# Add Dense layer with Dropout

x = Dense(512, activation=‘relu’)(averaged\_features)

x = Dropout(0.5)(x)

# Add final Dense layer with sigmoid activation function

outputs = Dense(5, activation=‘sigmoid’)(x)

# Define the model

model = Model(inputs=inputs, outputs=outputs)

# Compile the model

model.compile(optimizer=‘adam’, loss=‘mse’, metrics=[‘mae’])

model.summary()

 ![ouarka_](https://d3qe71uytubmmx.cloudfront.net/original/2X/6/62795d956c92f6489b2402c94ac89f584f2b9daf.png)

---

<div class="post-metadata">

**Author:** ![Kiran\_Sai\_Ramineni](https://d1dlmcr85iqnpo.cloudfront.net/user_avatar/discuss.ai.google.dev/kiran_sai_ramineni/32/8859_2.png) [@Kiran\_Sai\_Ramineni](https://discuss.ai.google.dev/u/Kiran_Sai_Ramineni)\
**Post date:** [April 28, 2023, 10:34am UTC](https://discuss.ai.google.dev/t/merge-two-models/18451/7 "2023-04-28T10:34:50Z")

</div>

> [@youb](#):
>
> please how to train this model; is I should train each model alone, I mean model1, then model2 and after merged\_model;

Hi @youb, first you have to train the vgg16 and resnet50 model then you have to pass the last layers outputs of both models to the merged model for training. You are getting the error because you are passing data to the merged model with shape (224,224,3) but the merged model input shape will be last layer output of vgg and resnet models which is (None,512). Thank You,

---

<div class="post-metadata">

**Author:** ![youb](https://d1dlmcr85iqnpo.cloudfront.net/user_avatar/discuss.ai.google.dev/youb/32/14345_2.png) [@youb](https://discuss.ai.google.dev/u/youb)\
**Post date:** [April 28, 2023, 3:15pm UTC](https://discuss.ai.google.dev/t/merge-two-models/18451/9 "2023-04-28T15:15:42Z")

</div>

@Kiran_Sai_Ramineni  
Thank you so much

---

<div class="post-metadata">

**Author:** ![Mog](https://d1dlmcr85iqnpo.cloudfront.net/user_avatar/discuss.ai.google.dev/mog/32/14347_2.png) [@Mog](https://discuss.ai.google.dev/u/Mog)\
**Post date:** [May 4, 2023, 8:40am UTC](https://discuss.ai.google.dev/t/merge-two-models/18451/11 "2023-05-04T08:40:33Z")

</div>

Remember to freeze everything but the last Dense(3) and Dense(512) when you train the combined model otherwise you will lose any pretraining of the two models and the stretch after them. You can unfreeze and fine-tune once the last two dense layers have converged.

---

<div class="post-metadata">

**Author:** ![youb](https://d1dlmcr85iqnpo.cloudfront.net/user_avatar/discuss.ai.google.dev/youb/32/14345_2.png) [@youb](https://discuss.ai.google.dev/u/youb)\
**Post date:** [May 4, 2023, 10:02pm UTC](https://discuss.ai.google.dev/t/merge-two-models/18451/13 "2023-05-04T22:02:22Z")

</div>

Yes I did; freeze all pretrained layers.  
Thank you so much.
