tensorflow import_error ai_generated true

ModuleNotFoundError: No module named 'keras' / ImportError: cannot import name 'layers' from 'keras'

ID: tensorflow/module-not-found-keras

Also available as: JSON · Markdown
90%Fix Rate
90%Confidence
3Evidence
2023-01-01First Seen

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
2 active

Root Cause

Keras import fails after TF 2.16+ migration. Keras was unbundled from TensorFlow in 2.16; standalone keras 3.x has a different API.

generic

Workarounds

  1. 92% success Use tf.keras instead of standalone keras imports
    from tensorflow.keras.layers import Dense  # NOT from keras.layers import Dense

    Sources: https://www.tensorflow.org/guide/gpu

  2. 88% success Pin tf-keras for backward compatibility
    pip install tf-keras; import os; os.environ['TF_USE_LEGACY_KERAS'] = '1'
  3. 80% success Pin TensorFlow < 2.16 if you cannot migrate yet
    pip install 'tensorflow>=2.15,<2.16'  # last version with bundled keras 2.x

Dead Ends

Common approaches that don't work:

  1. pip install keras separately alongside tensorflow 82% fail

    TF 2.16+ uses keras 3.x which has breaking API changes. Installing it does not restore tf.keras behavior.

  2. Monkey-patch keras imports with sys.modules 88% fail

    Fragile workaround that breaks with nested imports and keras submodules.