ImportError: cannot import name 'keras' from 'tensorflow'
Resolves `from tensorflow import keras` failing on TF 2.16+ by switching to the standalone keras package. Use when the traceback says cannot import name 'keras' from 'tensorflow'. Not for plain tensorflow install failures.
TL;DR: Use import keras (the standalone Keras 3 package) instead, or tf.keras for the bundled API. In TF 2.16+, Keras 3 moved out of the tensorflow package, so from tensorflow import keras breaks. Install the standalone keras package and change the import.
The error:
ImportError: cannot import name 'keras' from 'tensorflow' (.../tensorflow/__init__.py)Fix
Run
python -c "import tensorflow as tf; print(tf.__version__)"Expected: prints 2.16 or newer, confirming Keras 3 splitInstall it:
pip install kerasExpected: Successfully installed kerasChange
from tensorflow import kerastoimport keras(or keeptf.kerasif you want the bundled API) Expected: import works, no ImportError
When this applies
from tensorflow import kerasfails on TF 2.16+- you want the standalone Keras 3 API
When this does not apply
import tensorflowitself fails (different problem)- you are on TF 2.15 or older, where
from tensorflow import kerasstill works
Version compatibility
TensorFlow 2.16+. Keras 3 lives in its own keras package; tf.keras remains as a compatibility shim.
Why it happens
Starting with TF 2.16, Keras 3 became a separate package. tensorflow/__init__.py no longer exports the keras name the way older versions did, so the from-import fails while attribute-style tf.keras keeps working.
Edge cases
tf.kerasand standalonekerascan behave differently on saving/loading models; pick one and stay consistent.- If a library does
from tensorflow import kerasinternally, pin tensorflow<2.16 or patch the library. - Check
pip show kerasvspip show tf-keras; mixing them causes subtle bugs.