Loading saved model weight fails showing ValueError: You are trying to load a weight file containing 2 layers into a model with 3 layers.
See original GitHub issueHello, whenever I am trying to load the saved weight it is showing the error: You are trying to load a weight file containing 2 layers into a model with 3 layers.
This is the code:
def predict(image_path):
class_dictionary = np.load('class_indices.npy').item()
num_classes = len(class_dictionary)
#image_path = 'test/cherry/1056.jpg'
orig = cv2.imread(image_path)
print('[INFO] loading and preprocessing image...')
image = load_img(image_path, target_size=(224, 224))
image = img_to_array(image)
image = image / 255
image = np.expand_dims(image, axis=0)
model = applications.VGG16(include_top=False, weights='imagenet')
bottleneck_prediction = model.predict(image)
# build top model
model = Sequential()
model.add(Flatten(input_shape=bottleneck_prediction.shape[1:]))
model.add(BatchNormalization())
model.add(Dense(256, activation='relu'))
model.add(Dropout(0.5))
model.add(Dense(num_classes, activation='sigmoid'))
model.load_weights(top_model_weights_path)
# use the bottleneck prediction on the top model to get the final classification
class_predicted = model.predict_classes(bottleneck_prediction)
# probabilities = model.predict_proba(bottleneck_prediction)
inID = class_predicted[0]
inv_map = {v: k for k, v in class_dictionary.items()}
label = inv_map[inID]
print("Image ID: {}, Label: {}".format(inID, label))
cv2.putText(orig, "Predicted: {}".format(label), (10, 30),
cv2.FONT_HERSHEY_PLAIN, 1.5, (0, 0, 0), 2)
cv2.imshow('Classification', orig)
cv2.imwrite('predicted.jpg', orig)
cv2.waitKey(0)
The error I am getting is:
File "/home/user/PycharmProjects/training_keras/new.py", line 225, in <module>
predict(image_path)
File "/home/user/PycharmProjects/training_keras/new.py", line 198, in predict
model.load_weights(top_model_weights_path)
File "/home/user/PycharmProjects/training_keras/venv/lib/python3.6/site-packages/keras/models.py", line 768, in load_weights
topology.load_weights_from_hdf5_group(f, layers, reshape=reshape)
File "/home/user/PycharmProjects/training_keras/venv/lib/python3.6/site-packages/keras/engine/topology.py", line 3365, in load_weights_from_hdf5_group
str(len(filtered_layers)) + ' layers.')
ValueError: You are trying to load a weight file containing 2 layers into a model with 3 layers.
I’m not quite certain what the cause of the problem is. Is something going wrong in saving the model? Or is something wrong in this logic for loading the weights?
Any help on this issue is highly appreciated.
Issue Analytics
- State:
- Created 5 years ago
- Reactions:1
- Comments:5 (3 by maintainers)
Top Results From Across the Web
Loading saved model fails with ValueError You are trying to ...
Loading saved model fails with ValueError You are trying to load a weight file containing 1 layers into a model with 0 layers...
Read more >Keras you are trying to load a weight file containing 2 layers ...
ValueError : You are trying to load a weight file containing 2 layers into a model with 1 layers. I figure out that...
Read more >Model saving & serialization APIs - Keras
Loads all layer weights, either from a TensorFlow or an HDF5 weight file. If by_name is False weights are loaded based on the...
Read more >You are trying to load a weight file containing 0 layers into a ...
I'am currently using keras 2.1.5 in anaconda(windows). This is the error when I'am trying to load the weights file available online into VGG16...
Read more >Save and load Keras models | TensorFlow Core
When saving the model and its layers, the SavedModel format stores the class name, call function, losses, and weights (and the config, if ......
Read more >
Top Related Medium Post
No results found
Top Related StackOverflow Question
No results found
Troubleshoot Live Code
Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free
Top Related Reddit Thread
No results found
Top Related Hackernoon Post
No results found
Top Related Tweet
No results found
Top Related Dev.to Post
No results found
Top Related Hashnode Post
No results found
The problem is the batchnorm. This layer wasn’t there before, so keras is complaining that the model isn’t the same.
If you really want to load weights into a different model, use
model.load_weights(..., by_name=True)
and ensure that the layers have the same names before and after.This is the code used for training the model:
This is the code i have written for loading the moddel:
The result is all the same still.