I am experiencing a mismatch error when trying to load pre-trained weights into a MobileNetV2 model within a Flask application. I have trained a MobileNetV2 model for a dog breed classification task and saved the weights. Now, I'm trying to load these weights into an identical MobileNetV2 model architecture in a Flask app but encountering an error.

ValueError: Layer count mismatch when loading weights from file. Model expected 107 layers, found 0 saved layers.

Here's a brief overview of my situation:

Training Environment: I trained the MobileNetV2 model using TensorFlow and Keras, applied some custom layers on top, and saved the weights. Deployment Environment: In my Flask app (app3.py), I'm recreating the same MobileNetV2 model architecture and attempting to load the weights for inference. However, despite ensuring the model architectures in the training script and the Flask app are identical, loading the weights throws a mismatch error. Training Model Summary (Key Points):

base_model = MobileNetV2(weights='imagenet', include_top=False, input_shape=(224, 224, 3))
base_model.trainable = False  # Start by freezing base layers

# Custom layers on top of MobileNetV2
x = base_model.output
x = GlobalAveragePooling2D()(x)
x = Dense(2048, activation='relu')(x)
x = BatchNormalization()(x)
x = Dropout(0.85)(x)
predictions = Dense(train_generator.num_classes, activation='softmax')(x)

model = Model(inputs=base_model.input, outputs=predictions)

Flask App Model Summary (Key Points):

Reconstructed the same MobileNetV2 architecture with the custom layers. Checked the layer-by-layer summary, and it matches the training model.

Question: What could be causing this mismatch error when the architectures appear to be the same? How can I ensure the weights load correctly into the Flask app's model?

What I've Tried:

Verified the model architecture line by line between the training script and the Flask app. Ensured the number of classes in the final dense layer matches. Checked the paths and confirmed that the correct weights file is being accessed. Any insights or suggestions would be greatly appreciated!

Here is the error message:

File "/env/lib/python3.7/site-packages/keras/utils/traceback_utils.py", line 70, in error_handler raise e.with_traceback(filtered_tb) from None File "/env/lib/python3.7/site-packages/keras/saving/legacy/hdf5_format.py", line 813, in load_weights_from_hdf5_group "Layer count mismatch when loading weights from file. " ValueError: Layer count mismatch when loading weights from file. Model expected 107 layers, found 0 saved layers.

0

There are 0 best solutions below