TF-Keras (Legacy Keras 2)
TF-Keras is a deep learning API written in Python, running on top of the TensorFlow machine learning platform. It represents the legacy Keras 2, which was the TensorFlow-specific implementation of the Keras API and the default Keras from 2019 to 2023. Version 2.21.0 is current. This package is in maintenance mode, receiving bug fixes and regular releases, but no new features or performance improvements, as development has shifted to Keras 3 (the multi-backend Keras).
Warnings
- breaking TF-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.
- breaking Python 3.9 support has been removed as of `tf-keras` version 2.21.0.
- deprecated The Keras Scikit-learn API wrappers (`KerasClassifier` and `KerasRegressor`) were removed starting with TensorFlow 2.13 and compatible `tf-keras` versions.
- gotcha The 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.
Install
-
pip install tf-keras
Imports
- keras
import tf_keras as keras
- Model, layers
from tf_keras import models, layers
Quickstart
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]}")