question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

load_model() with custom layers, and custom layers in general

See original GitHub issue
  1. What should I do to make my custom layers available to be loaded using load_model()?

I used my custom layers in this repo both Spectrogram and Melspectrogram didn’t work for load_model().

Error message:

>>> keras.models.load_model('model_best.hdf5')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/Users/gnu/anaconda/lib/python2.7/site-packages/keras/models.py", line 140, in load_model
    model = model_from_config(model_config, custom_objects=custom_objects)
  File "/Users/gnu/anaconda/lib/python2.7/site-packages/keras/models.py", line 189, in model_from_config
    return layer_from_config(config, custom_objects=custom_objects)
  File "/Users/gnu/anaconda/lib/python2.7/site-packages/keras/utils/layer_utils.py", line 34, in layer_from_config
    return layer_class.from_config(config['config'])
  File "/Users/gnu/anaconda/lib/python2.7/site-packages/keras/models.py", line 1055, in from_config
    layer = get_or_create_layer(first_layer)
  File "/Users/gnu/anaconda/lib/python2.7/site-packages/keras/models.py", line 1039, in get_or_create_layer
    layer = layer_from_config(layer_data)
  File "/Users/gnu/anaconda/lib/python2.7/site-packages/keras/utils/layer_utils.py", line 33, in layer_from_config
    instantiate=False)
  File "/Users/gnu/anaconda/lib/python2.7/site-packages/keras/utils/generic_utils.py", line 16, in get_from_module
    str(identifier))
Exception: Invalid layer: Melspectrogram
>>>
  1. In the same manner, I think we should update layer customising documentation. My questions would be
  • if I have to use self.add_weight() method? or just appending them in self.trainable_weights is fine?
  • What do I have to do with get_config() method? When and how are they used?
  • How self.built is used?

Issue Analytics

  • State:closed
  • Created 7 years ago
  • Reactions:22
  • Comments:16 (4 by maintainers)

github_iconTop GitHub Comments

112reactions
NumesSanguiscommented, Sep 14, 2017

For the people landing here by a Google search, the code we should use:

model = keras.models.load_model('temp_model.h5',
              custom_objects={'Melspectrogram':kapre.time_frequency.Melspectrogram})

as can be found on kapre’s Github page: https://github.com/keunwoochoi/kapre

36reactions
bstrinercommented, Dec 30, 2016

Models.py saves the layer configuration and the class name.

for layer in self.layers[0].layers:
                layer_config = {'class_name': layer.__class__.__name__,
                                'config': layer.get_config()}
                layers.append(layer_config)

layer_from_config instantiates the class given the name.

layer_class = get_from_module(class_name, globals(), 'layer',
                                      instantiate=False)

Custom objects are added to the globals.

  if custom_objects:
       for cls_key in custom_objects:
           globals()[cls_key] = custom_objects[cls_key]

So, if you’re crashing on get_from_module, pass in a dictionary from the string of the class name to the actual class so get_from_module can find your class. {"MyClass":MyClass}

In terms of what to put into get_config, that same information is sent to your constructor. So the keywords in your get_config should match the kwargs of your constructor.

def from_config(cls, config):
      '''This method is the reverse of get_config,
      capable of instantiating the same layer from the config
      dictionary. It does not handle layer connectivity
      (handled by Container), nor weights (handled by `set_weights`).
      # Arguments
          config: A Python dictionary, typically the
              output of get_config.
      '''
      return cls(**config)

https://github.com/fchollet/keras/blob/master/keras/utils/layer_utils.py

Read more comments on GitHub >

github_iconTop Results From Across the Web

Saving Keras models with Custom Layers
I am trying to save a Keras model in a H5 file. The Keras model has a custom layer. When ...
Read more >
About my new blog on muratkarakaya.net
In this newsletter, you will find new Deep Learning Tutorials with Keras Take a look.
Read more >
Making new Layers and Models via subclassing
You can optionally enable serialization on your layers. If you need your custom layers to be serializable as part of a Functional model,...
Read more >
How to Save and Load Your Keras Deep Learning Model
The weights are saved directly from the model using the save_weights() function and later loaded using the symmetrical load_weights() function.
Read more >
Saving and Loading Models
A state_dict is simply a Python dictionary object that maps each layer to its ... Saving the model's state_dict with the torch.save() function...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found