Read only mode in keras

Viewed 43271

I have cloned human pose estimation keras model from this link human pose estimation keras

When I try to load the model on google colab, I get the following error

code

from keras.models import load_model
model = load_model('model.h5')

error

ValueError                                Traceback (most recent call 

last)
<ipython-input-29-bdcc7d8d338b> in <module>()
      1 from keras.models import load_model
----> 2 model = load_model('model.h5')

/usr/local/lib/python3.6/dist-packages/keras/engine/saving.py in load_model(filepath, custom_objects, compile)
    417     f = h5dict(filepath, 'r')
    418     try:
--> 419         model = _deserialize_model(f, custom_objects, compile)
    420     finally:
    421         if opened_new_file:

/usr/local/lib/python3.6/dist-packages/keras/engine/saving.py in _deserialize_model(f, custom_objects, compile)
    219         return obj
    220 
--> 221     model_config = f['model_config']
    222     if model_config is None:
    223         raise ValueError('No model found in config.')

/usr/local/lib/python3.6/dist-packages/keras/utils/io_utils.py in __getitem__(self, attr)
    300             else:
    301                 if self.read_only:
--> 302                     raise ValueError('Cannot create group in read only mode.')
    303                 val = H5Dict(self.data.create_group(attr))
    304         return val

ValueError: Cannot create group in read only mode.

Can someone please help me understand this read-only mode? How do I load this model?

5 Answers

I had a similar issue and solved this way

store the graph\architecture in JSON format and weights in h5 format

import json

# lets assume `model` is main model 
model_json = model.to_json()
with open("model_in_json.json", "w") as json_file:
    json.dump(model_json, json_file)

model.save_weights("model_weights.h5")

then need to load model first to create graph\architecture and load_weights in model

from keras.models import load_model
from keras.models import model_from_json
import json

with open('model_in_json.json','r') as f:
    model_json = json.load(f)

model = model_from_json(model_json)
model.load_weights('model_weights.h5')

I used callbacks.ModelCheckpoint to save the weights and I had a similar error. I found out that there is a parameter called save_weights_only

If I set save_weights_only=True, then when I use load_model() to load the model in another process, it will raise the 'Cannot create group in read only mode.' error.

If I set save_weights_only=False(which is the default), then I can use load_model() to load the model and use it to do prediction, without compiling the model first.

you can use model.save(model_path+'Model.h5') and then keras.models.load_model(model_path+'Model.h5'), this way, you will not need to build and compile the model before load the weights, as model.save creates the architecture in dict inside the .h5 file.

Easy solution is you have to load the save model in the same way it is saved

for example you had created a model like this

# Build the model

model = Sequential()
model.add(Dense(100, input_shape=(10,)))
model.add(Activation('relu'))

model.add(Dense(10))
model.add(Activation('softmax'))

model.compile(loss='categorical_crossentropy',
              optimizer='adam',
              metrics=['accuracy'])

#fit the model
model.fit(x_train, y_train,
                    batch_size=10,
                    epochs=5,
                    verbose=1,
                    validation_split=0.1)

#save model
model.save("model.h5")

so if you want to load this model for prediction you have to follow the same steps

from keras.models import load_model
# Build the model

model = Sequential()
model.add(Dense(100, input_shape=(10,)))
model.add(Activation('relu'))

model.add(Dense(10))
model.add(Activation('softmax'))

model.compile(loss='categorical_crossentropy',
              optimizer='adam',
              metrics=['accuracy'])

# load model
model.load_weights('model.h5')

prediction = model.predict( ''' data to predict ''')

Related