Skip to content

Instantly share code, notes, and snippets.

@planetceres
Last active December 4, 2019 02:12
Show Gist options
  • Save planetceres/1f0c0ba8ad2ba139cf35714ebae431d9 to your computer and use it in GitHub Desktop.
Save planetceres/1f0c0ba8ad2ba139cf35714ebae431d9 to your computer and use it in GitHub Desktop.
Read .hdf5 as dict
#!/usr/bin/python
'''
Source
https://gitlab.kuberlab.io/lsheiba/keras/blob/fbe7873fc0f43090e2df52b85867b8b6179516ca/keras/models.py
'''
from keras.models import load_model
from keras import layers as layer_module
import h5py, json, pprint
def model_from_config(config, custom_objects=None):
"""Instantiates a Keras model from its config.
# Arguments
config: Configuration dictionary.
custom_objects: Optional dictionary mapping names
(strings) to custom classes or functions to be
considered during deserialization.
# Returns
A Keras model instance (uncompiled).
"""
if isinstance(config, list):
raise TypeError('`model_fom_config` expects a dictionary, not a list. '
'Maybe you meant to use '
'`Sequential.from_config(config)`?')
return layer_module.deserialize(config, custom_objects=custom_objects)
f = h5py.File(weight_fn, 'r')
print(list(f.keys()))
# instantiate model
custom_objects = {}
model_config = f.attrs.get('model_config')
if model_config is None:
raise ValueError('No model found in config file.')
model_config = json.loads(model_config.decode('utf-8'))
model = model_from_config(model_config, custom_objects=custom_objects)
pprint(model)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment