Skip to content Skip to sidebar Skip to footer

Keras Load Model Error Trying To Load A Weight File Containing 17 Layers Into A Model With 0 Layers

I am currently working on vgg16 model with keras. I fine tune vgg model with some of my layer. After fitting my model (training), I save my model with model.save('name.h5'). It can

Solution 1:

It seems that this problem is related with the input_shape parameter of the first layer. I had this problem with a wrapper layer (Bidirectional) which did not have an input_shape parameter set. In code:

model.add(Bidirectional(LSTM(units=units, input_shape=(None, feature_size)), merge_mode='concat'))

did not work for loading my old model because the input_shape is only defined for the LSTM layer not the outer one. Instead

model.add(Bidirectional(LSTM(units=units), input_shape=(None, feature_size), merge_mode='concat'))

worked because the wrapper Birectional layer now has an input_shape parameter. Maybe you should check if the VGG net input_shape parameter is set or not or you should add a single input_layer to your model with the correct input_shape parameter.


Solution 2:

I spent 6 hours looking around for a solution.. to apply me trained model. finally i tried VGG16 as model and using h5 weights i´ve trained on my own and Great!

weights_model='C:/Anaconda/weightsnew2.h5'  # my already trained weights .h5
vgg=applications.vgg16.VGG16()
cnn=Sequential()
for capa in vgg.layers:
   cnn.add(capa)
cnn.layers.pop()
for layer in cnn.layers:
   layer.trainable=False
cnn.add(Dense(2,activation='softmax'))  

cnn.load_weights(weights_model)

def predict(file):
   x = load_img(file, target_size=(longitud, altura)) 
   x = img_to_array(x)                            
   x = np.expand_dims(x, axis=0)
   array = cnn.predict(x)     
   result = array[0]
   respuesta = np.argmax(result) 
   if respuesta == 0:
      print("Gato")
   elif respuesta == 1:
      print("Perro")

Solution 3:

In case anyone is still wondering about this error:

I had the same Problem and spent days figuring out, whats causing it. I have a copy of my whole code and dataset on another system on which it worked. I noticed that it is something about the training, because without training my model, saving and loading was no problem. The only difference between my systems was, that I was using tensorflow-gpu on my main system and for this reason, the tensorflow base version was a little bit lower (1.14.0 instead of 2.2.0). So all I had to do was using

model.fit_generator()

instead of

model.fit()

before saving it. And it works


Post a Comment for "Keras Load Model Error Trying To Load A Weight File Containing 17 Layers Into A Model With 0 Layers"