Keras
Keras 3 is a multi-backend deep learning framework providing a high-level API for building and training neural networks. It supports JAX, TensorFlow, PyTorch, and OpenVINO (for inference-only) as computational backends, allowing users to leverage the same codebase across different frameworks. Focused on fast experimentation and user experience, Keras 3 enables efficient development and deployment of deep learning models across various domains. The current version is 3.13.2, and the library maintains an active release cadence with frequent updates.
Warnings
- breaking Keras 3.13.0 introduced a breaking change by requiring Python 3.11 or higher. Earlier Python versions are not supported.
- gotcha The Keras backend (TensorFlow, JAX, or PyTorch) must be configured *before* importing Keras. Attempting to change it after import will not work.
- breaking Model saving in Keras 3.x has changed. The `model.save()` method now expects the native Keras `.keras` format. Saving to the TensorFlow SavedModel format directly via `model.save()` is no longer supported and will raise a ValueError.
- gotcha When using TensorFlow versions 2.0 through 2.15, `pip install tensorflow` would install Keras 2.x and make it available via `import keras` and `tf.keras`. If you install TensorFlow 2.15, it will overwrite a Keras 3 installation with Keras 2.15.
- deprecated Setting a `tf.Variable` directly as an attribute of a Keras 3 layer or model will no longer automatically track that variable as a trainable weight, unlike in Keras 2.
- gotcha Security hardening was introduced to disallow `TFSMLayer` deserialization in `safe_mode`, preventing potential execution of attacker-controlled graphs during model loading from external TensorFlow SavedModels.
Install
-
pip install keras --upgrade -
pip install tensorflow # for TensorFlow backend pip install jax jaxlib # for JAX backend pip install torch torchvision torchaudio # for PyTorch backend
Imports
- Model
from keras import Model
- layers
from keras import layers
Quickstart
import os
os.environ["KERAS_BACKEND"] = os.environ.get("KERAS_BACKEND", "tensorflow") # Set backend before importing keras
import keras
from keras import layers
import numpy as np
# Load example data (e.g., MNIST for a simple classification task)
(x_train, y_train), (x_test, y_test) = keras.datasets.mnist.load_data()
x_train = x_train.reshape(-1, 28, 28, 1).astype("float32") / 255.0
x_test = x_test.reshape(-1, 28, 28, 1).astype("float32") / 255.0
# Define a simple Sequential model
model = keras.Sequential([
keras.Input(shape=(28, 28, 1)),
layers.Conv2D(32, kernel_size=(3, 3), activation="relu"),
layers.MaxPooling2D(pool_size=(2, 2)),
layers.Conv2D(64, kernel_size=(3, 3), activation="relu"),
layers.MaxPooling2D(pool_size=(2, 2)),
layers.Flatten(),
layers.Dropout(0.5),
layers.Dense(10, activation="softmax"),
])
# Compile the model
model.compile(
loss=keras.losses.SparseCategoricalCrossentropy(),
optimizer=keras.optimizers.Adam(learning_rate=1e-3),
metrics=["accuracy"],
)
# Train the model
print("\nTraining model...")
model.fit(x_train, y_train, batch_size=128, epochs=3, validation_split=0.1)
# Evaluate the model
print("\nEvaluating model...")
loss, accuracy = model.evaluate(x_test, y_test)
print(f"Test Loss: {loss:.4f}, Test Accuracy: {accuracy:.4f}")