keras-team/keras · error · ImportError

`save_model()` using h5 format requires h5py. Could not impo

Error message

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

What it means

The legacy HDF5 save path requires the optional h5py package. Keras imports h5py lazily; if the import failed, save_model_to_hdf5 raises ImportError at the top rather than crashing deep inside the writer.

Source

Thrown at keras/src/legacy/saving/legacy_h5_format.py:30

from keras.src.legacy.saving import saving_utils
from keras.src.saving import object_registration
from keras.src.saving import serialization_lib
from keras.src.saving.saving_lib import safe_get_h5_dataset
from keras.src.saving.saving_lib import safe_get_h5_group
from keras.src.utils import io_utils

try:
    import h5py
except ImportError:
    h5py = None


HDF5_OBJECT_HEADER_LIMIT = 64512


def save_model_to_hdf5(model, filepath, overwrite=True, include_optimizer=True):
    if h5py is None:
        raise ImportError(
            "`save_model()` using h5 format requires h5py. Could not "
            "import h5py."
        )

    if not isinstance(filepath, h5py.File):
        # If file exists and should not be overwritten.
        if not overwrite and os.path.isfile(filepath):
            proceed = io_utils.ask_to_proceed_with_overwrite(filepath)
            if not proceed:
                return

        dirpath = os.path.dirname(filepath)
        if dirpath and not os.path.exists(dirpath):
            os.makedirs(dirpath, exist_ok=True)

        f = h5py.File(filepath, mode="w")
        opened_new_file = True
    else:

View on GitHub (pinned to 7a34a03db6)

Solutions

  1. pip install h5py (prefer a prebuilt wheel; use a glibc-based image if the source build fails)
  2. Save natively instead: model.save('model.keras') needs no h5py
  3. Verify with python -c 'import h5py'

Example fix

# before
model.save('model.h5')  # ImportError
# after
# pip install h5py, or:
model.save('model.keras')
Defensive patterns

Strategy: fallback

Validate before calling

try:
    import h5py
except ImportError:
    raise SystemExit('pip install h5py or save as .keras')

Try / catch

try:
    model.save('m.h5')
except ImportError:
    model.save('m.keras')

Prevention

When it happens

Trigger: model.save('model.h5') or save_model_to_hdf5 in an environment where h5py is missing or failed to build (fresh venvs, Alpine, or a Python version with no wheel yet).

Common situations: Slim Docker images omitting h5py; Python upgraded before h5py wheels ship; broken h5py builds from HDF5 library mismatches.

Related errors


AI-assisted analysis of keras-team/keras@7a34a03db6 (2026-08-25). Data as JSON: /api/errors/8c02d3124b1b3923. Report an issue: GitHub.