Install & Compatibility
Where this runs
tested against v2.15.0 · pip install
no network on importno background threads
Install × environment matrix
Each cell = how many times install + import succeeded across repeated harness runs. Partial = flaky.
glibc = Debian/Ubuntu slim · musl = Alpine Linux
muslpy 3.10–3.95 runs
installs and imports cleanly · install 0.0s · import 0.000s · 33.5MB
glibcpy 3.10–3.95 runs
installs and imports cleanly · install 32.5s · import 12.522s · 2150.4MB
1091MB installed
● package 1091MB
Code
Verified usage
Verified import paths — ran on the pinned version, not inferred.
keras
✓ import tf_keras as keras
✗ import keras
Direct `import keras` (without installing tf_keras and setting TF_USE_LEGACY_KERAS=1) will import Keras 3, which is multi-backend and has potential API differences. `tf_keras` is the dedicated legacy Keras 2 package.
Model, layers
✓ from tf_keras import models, layers
✗ from tensorflow.keras import models, layers
While `from tensorflow.keras` used to be the standard for Keras 2, with TensorFlow 2.16+ it now defaults to Keras 3. For explicit Keras 2 usage, import directly from the `tf_keras` package.
This quickstart demonstrates how to build, compile, train, and evaluate a simple neural network for classifying MNIST handwritten digits using the `tf_keras` library. It showcases the Sequential API, common layers like Dense and Dropout, and standard training procedures. It also includes a crucial environment variable setting for compatibility with newer TensorFlow versions.
import os
import numpy as np
import tf_keras as keras
from tf_keras import layers
# Set environment variable to ensure Keras 2 is used if TensorFlow >= 2.16 is also installed
os.environ['TF_USE_LEGACY_KERAS'] = '1'
# Load a dataset (MNIST handwritten digits)
(x_train, y_train), (x_test, y_test) = keras.datasets.mnist.load_data()
# Preprocess the data
x_train = x_train.reshape(-1, 28 * 28).astype('float32') / 255.0
x_test = x_test.reshape(-1, 28 * 28).astype('float32') / 255.0
# Define the model using the Sequential API
model = keras.Sequential([
layers.Dense(128, activation='relu', input_shape=(784,)),
layers.Dropout(0.2),
layers.Dense(10, activation='softmax')
])
# Compile the model
model.compile(
optimizer='adam',
loss='sparse_categorical_crossentropy',
metrics=['accuracy']
)
# Train the model
print("\nTraining the model...")
history = model.fit(x_train, y_train, epochs=5, batch_size=32, validation_split=0.1)
# Evaluate the model
print("\nEvaluating the model...")
loss, accuracy = model.evaluate(x_test, y_test)
print(f"Test Loss: {loss:.4f}, Test Accuracy: {accuracy:.4f}")
# Make predictions
predictions = model.predict(x_test[:5])
predicted_classes = np.argmax(predictions, axis=1)
print(f"\nFirst 5 test samples predictions: {predicted_classes}")
print(f"True labels: {y_test[:5]}")
Debug
Known issues
breakingTF-Keras (Keras 2) is in maintenance mode. New features are developed in Keras 3. If you install TensorFlow >= 2.16, `tf.keras` will default to Keras 3, which has a different API and multi-backend support. This can cause compatibility issues with code expecting Keras 2 behavior.fixFor new projects, consider migrating to Keras 3 (`pip install keras`). To explicitly use TF-Keras (Keras 2) with TensorFlow >= 2.16, install `tf-keras` and set the environment variable `TF_USE_LEGACY_KERAS=1` before importing TensorFlow or Keras. Alternatively, import directly from `tf_keras` as shown in the imports section.
affects: TensorFlow >= 2.16.0
breakingPython 3.9 support has been removed as of `tf-keras` version 2.21.0.fixUpgrade your Python environment to Python 3.10 or newer.
affects: tf-keras == 2.21.0 and later
deprecatedThe Keras Scikit-learn API wrappers (`KerasClassifier` and `KerasRegressor`) were removed starting with TensorFlow 2.13 and compatible `tf-keras` versions.fixMigrate to `SciKeras` for Scikit-learn compatible Keras models.
affects: tf-keras compatible with TensorFlow >= 2.13.0
gotchaThe default model saving format (`.keras` extension) in Keras 2 is now the Keras v3 format, not the H5 format. This might break workflows that manually inspected or modified H5 files saved with a `.keras` extension.fixWhen saving models, explicitly specify `save_format="h5"` if you need to retain the H5 format for a `.keras` file: `model.save('my_model.keras', save_format='h5')`. For general use, consider adopting the Keras v3 saving format or `model.export()` for inference. affects: tf-keras compatible with TensorFlow >= 2.13.0
Errors
Common errors & fixes
ModuleNotFoundError: No module named 'tf_keras'
The `tf-keras` library, which provides Keras 2 functionality, has not been installed in your Python environment.
fixInstall the package using pip: `pip install tf-keras`.
ModuleNotFoundError: No module named 'keras'
Even with `tf-keras` installed, trying to `import keras` will fail unless the standalone `keras` package is also installed. The `tf-keras` library provides its functionality under the `tf_keras` namespace.
fixChange your import statements from `import keras` or `from keras.models import Model` to `import tf_keras as keras` or `from tf_keras.models import Model`.
AttributeError: module 'tf_keras' has no attribute 'Dense'
Keras components like layers (`Dense`, `Input`), models (`Model`, `Sequential`), and optimizers (`Adam`) are located within specific submodules (e.g., `tf_keras.layers`, `tf_keras.models`, `tf_keras.optimizers`), not directly under the top-level `tf_keras` module.
fixImport the components from their correct submodules, for example: `from tf_keras.layers import Dense`, `from tf_keras.models import Model`, `from tf_keras.optimizers import Adam`.
TypeError: 'KerasTensor' object is not callable
This error typically occurs when you accidentally treat a Keras layer or tensor object as a function call without providing an input tensor, or when you attempt to call a KerasTensor object directly.
fixEnsure you are correctly applying layers to tensors by calling the layer instance with an input tensor, e.g., `output = Dense(units=10)(input_tensor)`. Do not attempt to call a KerasTensor object itself.
Upgrade
Version history
2.21.0latest on PyPI · released Mar 18, 2026
Audit
Dependencies
tensorflowrequiredTF-Keras is the TensorFlow-specific implementation of Keras, requiring TensorFlow to run.