5

I ran into some trouble when trying to save a Keras model:

Here is my code:

import h5py
from keras.models import load_model

try:
    import h5py
    print ('import fine')
except ImportError:
    h5py = None

left.save('left.h5')  # creates a HDF5 file 'my_model.h5'
left_load = load_model('left.h5')

But I got the following errors even though the code print 'import fine':

import fine
---------------------------------------------------------------------------
ImportError                               Traceback (most recent call last)
<ipython-input-145-b641e79036fa> in <module>()
      8     h5py = None
      9 
---> 10 left.save('left.h5')  # creates a HDF5 file 'my_model.h5'

/usr/local/lib/python3.4/dist-packages/keras/engine/topology.py in save(self, filepath, overwrite, include_optimizer)
   2504         """
   2505         from ..models import save_model
-> 2506         save_model(self, filepath, overwrite, include_optimizer)
   2507 
   2508     def save_weights(self, filepath, overwrite=True):

/usr/local/lib/python3.4/dist-packages/keras/models.py in save_model(model, filepath, overwrite, include_optimizer)
     53 
     54     if h5py is None:
---> 55         raise ImportError('`save_model` requires h5py.')
     56 
     57     def get_json_type(obj):

ImportError: `save_model` requires h5py.
Edamame
  • 23,718
  • 73
  • 186
  • 320
  • What's the error message if you remove the "try-except" around `import h5py` in `/usr/local/lib/python3.4/dist-packages/keras/models.py`? – Yu-Yang Nov 22 '17 at 03:38

4 Answers4

5

Make sure you use the latest version of Keras.

Also, this error has been reported here in the keras github: https://github.com/fchollet/keras/issues/3426

on linux:

sudo apt-get install libhdf5
sudo pip install h5py
Nickpick
  • 6,163
  • 16
  • 65
  • 116
1

Have you tried directly installing h5py? http://docs.h5py.org/en/latest/build.html

Try running pip install h5py

1
save_model() using h5 format requires h5py. Could not import h5py

This error occurs when the h5py and keras versions are not aligned. I was having the same problem using:

  • Windows 11
  • Tensorflow 2.10
  • Keras 2.10
  • h5py 3.8

I had to do the following for it to work:

pip uninstall h5py
conda install -c conda-forge h5py=3.4

If you have the latest version of tensorflow you can do the following to align the keras and h5py versions with the latest:

pip uninstall h5py
pip uninstall keras
pip install keras
MD Mushfirat Mohaimin
  • 1,966
  • 3
  • 10
  • 22
0

For windows 10

tensorflow - 2.10
keras - 2.10

I was facing the same issue. I tried several methods and different h5py versions. finally this worked for me - uninstall the current h5py then

pip install h5py==3.7.0

And restart the kernel once.