Migrating from Keras 2 to Keras 3

This content was generated with the assistance of AI and should be verified against the official documentation before being relied on in production.

Keras 3 is a rewrite of Keras as a multi-backend library that runs on TensorFlow, JAX and PyTorch. Since TensorFlow 2.16 it is also what tf.keras resolves to, so code and books written for the Keras 2 era (tf.keras up to TensorFlow 2.15) can break in subtle ways. This page lists what changed, what the fallback package tf_keras is for, and how to port the most common patterns. The overview of the current package layout is on Keras 3 Overview, multi-backend usage on Keras Multi-Backend, and the older TensorFlow 1 history on Migrating from TensorFlow 1.

It targets Python 3.13, TensorFlow 2.21 with Keras 3.15 (TensorFlow 2.22 is labelled upcoming) and scikit-learn 1.9, and was checked against the official documentation on 2026-10-30. Examples were run on Python 3.13 with TensorFlow 2.21, Keras 3.15, tf-keras 2.21.0 and scikit-learn 1.9 (CPU) on 2026-10-31.

Which Keras do you get?

The release notes for TensorFlow 2.16.1 state that Keras 3 became the default Keras version. In practice:

  • import keras gives Keras 3.

  • With TensorFlow 2.16 or later and no special configuration, tf.keras also resolves to Keras 3.

  • tf_keras is a separate package that contains the Keras 2 code (version series 2.16 and later were published alongside TensorFlow) for projects that cannot migrate yet.

Which Keras a TensorFlow 2.21 program imports
Figure 1. Which Keras an import resolves to in a default and in a legacy-configured environment.

To keep Keras 2 behaviour under tf.keras, install tf-keras and set an environment variable before TensorFlow is imported. The release notes warn that the variable applies to every package in the Python process.

pip install tf-keras
export TF_USE_LEGACY_KERAS=1
python -c "import tensorflow as tf; print(tf.keras.__name__)"   # tf_keras.api._v2.keras
import os

os.environ["TF_USE_LEGACY_KERAS"] = "1"   # must be set before importing tensorflow

import tensorflow as tf            # tf.keras now resolves to tf_keras (Keras 2)
import tf_keras as keras           # or import tf_keras directly, which is more explicit

The tf-keras release that matches TensorFlow 2.21 is 2.21.0: its version numbers follow TensorFlow, while its API stays the Keras 2 API. With TF_USE_LEGACY_KERAS=1, tf.keras.__name__ is tf_keras.api._v2.keras and tf.keras.__version__ does not exist (read tf_keras.__version__ instead). Check https://pypi.org/project/tf-keras/ before choosing it for new work. Treat tf_keras as a bridge, not a destination: new features land in Keras 3.

Imports and namespaces

The simplest migration step is to stop writing tf.keras and import Keras directly.

Keras 2 era Keras 3

from tensorflow import keras

import keras

from tensorflow.keras import layers

from keras import layers

tf.keras.Model, tf.keras.layers.Dense

keras.Model, keras.layers.Dense

With TensorFlow installed, tf.keras still works in a default environment and is the same Keras 3, but importing keras makes the dependency explicit and works unchanged on the JAX and PyTorch backends.

Dated table of renames and removals

The table lists items documented in the official migration guide, verified on 2026-10-30 against Keras 3.15. "Port" says what to use instead.

Keras 2 behaviour or API Keras 3 Port

model.save("dir") writes a SavedModel; load_model("dir") reads it

SavedModel is not written by save; the loader does not accept SavedModel directories

Use .keras for models, model.export(...) for serving artifacts, keras.layers.TFSMLayer to call an existing SavedModel

ThresholdedReLU layer

Removed

keras.layers.ReLU(threshold=...)

LocallyConnected1D, LocallyConnected2D

Removed

Copy the implementation into your code base

keras.layers.experimental.RandomFourierFeatures, keras.constraints.RadialConstraint

Removed

Copy the implementation if needed

Symbolic Layer.add_loss() outside call()

Removed; add_loss inside call() still works

Move the call into call()

Layer attributes metrics and dynamic (Model.metrics stays)

Removed

Track metrics explicitly

RNN arguments constants and time_major

Removed

Reshape or restructure the inputs

reset_metrics argument of train_on_batch, test_on_batch

Removed

Call model.reset_metrics() yourself

Autograph active inside Layer.call

Off by default

Use keras.ops control flow or decorate with tf.function

Per-output loss values reported by evaluate() for multi-output models

Not reported automatically

Add the losses to metrics explicitly

Nested dictionaries as functional-model inputs or outputs

Rejected beyond one level

Flatten to a list, tuple or single-level dict

None in nested arguments of call()

Not allowed

Use an optional argument with a default of None

jit_compile default

True on GPU in Keras 3

Pass jit_compile=False to compile if XLA fails, for example with tf.strings ops

tf.Variable assigned as a layer attribute is tracked

Not tracked

Use self.add_weight(...) or keras.Variable

Two further items matter but are explained in more depth below: the optimizer and the train_step rewrite. For the current layer, loss and metric catalogues see Core Keras Layers, Losses and Metrics.

From TensorFlow ops to keras.ops

A Keras 3 layer that must run on any backend cannot call tf.* functions on symbolic tensors during functional model construction. Replace them with keras.ops, which mirrors a large part of NumPy plus neural-network operations.

TensorFlow keras.ops

tf.reduce_sum, tf.reduce_mean, tf.reduce_max, tf.reduce_min

keras.ops.sum, mean, max, min

tf.reduce_prod, tf.reduce_all, tf.reduce_any

keras.ops.prod, all, any

tf.math.reduce_variance, tf.math.reduce_std

keras.ops.var, keras.ops.std

tf.abs, tf.clip_by_value, tf.math.pow

keras.ops.absolute, clip, power

tf.concat, tf.range, tf.rank, tf.reverse

keras.ops.concatenate, arange, ndim, flip

tf.gather, tf.nn.embedding_lookup

keras.ops.take

tf.nn.sparse_softmax_cross_entropy_with_logits

keras.ops.sparse_categorical_crossentropy (mind from_logits)

tf.nn.sigmoid_cross_entropy_with_logits

keras.ops.binary_crossentropy (mind from_logits)

tf.nn.conv1d, conv2d, conv3d, tf.nn.convolution

keras.ops.conv

tf.nn.dropout

keras.random.dropout

tf.convert_to_tensor, x.numpy()

keras.ops.convert_to_tensor, keras.ops.convert_to_numpy(x)

import keras
from keras import layers, ops


class SquaredNorm(layers.Layer):
    """Backend-agnostic: only keras.ops inside call."""

    def call(self, x):
        return ops.sum(ops.square(x), axis=-1, keepdims=True)


inputs = keras.Input(shape=(8,))
outputs = SquaredNorm()(inputs)        # works with symbolic tensors on any backend
model = keras.Model(inputs, outputs)
print(model.output_shape)               # (None, 1)

Code that stays inside TensorFlow can keep using tf.* in a layer’s call when run on the TensorFlow backend, but it will not work on JAX or PyTorch, and symbolic construction can fail. The wider backend story is on Keras Multi-Backend.

Model saving and export

This is the change that breaks the most scripts. The Keras 3 native format is a zip archive with the extension .keras containing a JSON configuration, a weights file and metadata (including the Keras version). Full-model saving to a SavedModel directory is no longer what model.save does; serving artifacts come from model.export.

Older books and Keras 2 tutorials Keras 3.15

model.save("my_model") creates a SavedModel directory

model.save("my_model.keras") writes the native format; model.export("export_dir") writes a SavedModel (inference artifact) for TensorFlow Serving

model.save("model.h5") as the default

.h5 is the legacy format; use .keras for new work

model.save_weights("ckpt") in the TensorFlow checkpoint format

model.save_weights("name.weights.h5"); the file name must end with .weights.h5

load_model("my_model") on a SavedModel directory

Wrap it: keras.layers.TFSMLayer("my_model", call_endpoint="serving_default")

import keras

model = keras.Sequential([keras.Input(shape=(4,)), keras.layers.Dense(2)])

model.save("my_model.keras")                       # architecture + weights + compile + optimizer state
restored = keras.models.load_model("my_model.keras")

model.save_weights("my_model.weights.h5")          # weights only
model.load_weights("my_model.weights.h5")

model.export("exported_model")                     # SavedModel for serving (TensorFlow backend)

# Reload a SavedModel as an inference-only layer
layer = keras.layers.TFSMLayer("exported_model", call_endpoint="serving_default")

Custom classes must be findable at load time because the .keras file stores their configuration but not their Python code. Register them with @keras.saving.register_keras_serializable(package="MyPkg"), pass custom_objects= to load_model, or use keras.saving.custom_object_scope. A custom layer with non-primitive constructor arguments (for example sublayers) needs get_config and a from_config class method. The complete walk-through is on Saving Keras Models, with SavedModel details on SavedModel and Signatures, checkpoints on Training Checkpoints, and an interchange view on ONNX and Interoperability.

Lambda layers and safe_mode

Keras 2 tutorials often wrap arbitrary Python in keras.layers.Lambda. A Lambda layer serializes Python bytecode, which makes loading an untrusted model file equivalent to running untrusted code. Keras 3 therefore loads models in a safe mode by default that refuses to deserialize such code. The migration guide itself does not discuss this; the behaviour below follows the load_model documentation, and with Keras 3.15 loading a saved Lambda model with the default safe_mode=True raises a ValueError.

  • Prefer replacing a Lambda with a small subclassed layer that implements call and get_config; it is portable and loads under the default safety settings.

  • Only when you fully trust the file and cannot rewrite the layer, load with the safe_mode=False argument of load_model, or enable unsafe deserialization through the Keras saving utilities. Never do this with files from the internet.

import keras
from keras import ops


@keras.saving.register_keras_serializable(package="demo")
class Scale(keras.layers.Layer):
    """Replaces keras.layers.Lambda(lambda x: x * factor)."""

    def __init__(self, factor=2.0, **kwargs):
        super().__init__(**kwargs)
        self.factor = factor

    def call(self, x):
        return ops.multiply(x, self.factor)

    def get_config(self):
        return {**super().get_config(), "factor": self.factor}


model = keras.Sequential([keras.Input(shape=(3,)), Scale(3.0)])
model.save("scaled.keras")
reloaded = keras.models.load_model("scaled.keras")   # no safe_mode override needed

Optimizers

Keras 3 ships a new optimizer implementation. The optimizers listed in the API reference include SGD, RMSprop, Adam, AdamW, Adadelta, Adagrad, Adamax, Adafactor, Nadam, Ftrl, Lion, Lamb, Muon, plus wrappers such as LossScaleOptimizer. Learning-rate schedules live in keras.optimizers.schedules and are passed as the learning_rate.

Things to check when porting:

  • The Keras 2 tf.keras.optimizers.legacy namespace has no counterpart: in Keras 3.15, creating keras.optimizers.legacy.Adam() (or tf.keras.optimizers.legacy.Adam()) raises an ImportError that points to tf_keras and TF_USE_LEGACY_KERAS. Scripts that selected legacy optimizers for speed on Apple silicon or for exact old semantics must drop that import or stay on tf_keras.

  • Custom optimizers written against the Keras 2 _resource_apply_dense style must be rewritten to the Keras 3 base class, which defines build, update_step and get_config and has no _resource_apply_dense.

  • Optimizer state saved in Keras 2 checkpoints does not transfer to Keras 3 optimizers; plan to restart the optimizer state.

  • Gradient clipping, weight decay, exponential moving averages and gradient accumulation are constructor options of the optimizer base class in Keras 3.15: weight_decay, clipnorm, clipvalue, global_clipnorm, use_ema, ema_momentum, ema_overwrite_frequency, loss_scale_factor and gradient_accumulation_steps (see Optimizers and Learning-Rate Schedules).

import keras

schedule = keras.optimizers.schedules.ExponentialDecay(
    initial_learning_rate=1e-2, decay_steps=10_000, decay_rate=0.9
)
optimizer = keras.optimizers.SGD(learning_rate=schedule, momentum=0.9)

model = keras.Sequential([keras.Input(shape=(4,)), keras.layers.Dense(1)])
model.compile(optimizer=optimizer, loss="mse", jit_compile=False)

For how the optimizer family relates to the theory, see Optimizers and Learning-Rate Schedules.

Custom train_step and training loops

TensorFlow-specific training code does not run on other backends. The migration guide recommends:

  • If you only change how the loss is computed, override compute_loss(self, x=None, y=None, y_pred=None, sample_weight=None), which is backend-agnostic, instead of train_step.

  • If you need the gradient step, write one version per backend and choose it from the active backend; the TensorFlow version uses tf.GradientTape, the JAX version a stateless jax.value_and_grad, the PyTorch version loss.backward().

import keras


class WeightedMSE(keras.Model):
    def compute_loss(self, x=None, y=None, y_pred=None, sample_weight=None, **kwargs):
        errors = keras.ops.square(y - y_pred)
        return keras.ops.mean(errors * 2.0)      # same code on TensorFlow, JAX and PyTorch


inputs = keras.Input(shape=(4,))
outputs = keras.layers.Dense(1)(inputs)
model = WeightedMSE(inputs, outputs)
model.compile(optimizer="adam")

Random numbers are stateless

keras.random functions are stateless: calling one twice with seed=123 returns the same values twice. TensorFlow’s tf.random functions are stateful. A layer that needs fresh randomness on every call should hold a keras.random.SeedGenerator and pass it as the seed; a plain Python integer that is incremented inside call is frozen into the compiled graph.

import keras


class AddNoise(keras.layers.Layer):
    def __init__(self, scale=0.1, **kwargs):
        super().__init__(**kwargs)
        self.scale = scale
        self.seed_generator = keras.random.SeedGenerator(1337)

    def call(self, x, training=False):
        if not training:
            return x
        noise = keras.random.normal(keras.ops.shape(x), stddev=self.scale, seed=self.seed_generator)
        return x + noise

scikit-learn wrappers: legacy wrappers, SciKeras and keras.wrappers

Keras 2 offered tf.keras.wrappers.scikit_learn.KerasClassifier and KerasRegressor. They were deprecated and are absent from Keras 3. The community project SciKeras (scikeras) took over their role for years; it belongs to the Keras 2 era and is treated as legacy here, so check its repository status before adopting it in new code and prefer the built-in wrappers below.

Keras 3.15 documents its own scikit-learn compatible wrappers in keras.wrappers: SKLearnClassifier, SKLearnRegressor and SKLearnTransformer (a scikit-learn transformer, not a deep-learning Transformer). All share the signature (model, warm_start=False, model_kwargs=None, fit_kwargs=None). The model argument is either a compiled Keras model, which is cloned before fitting unless warm_start=True, or a callable that builds and compiles a model from X and y. The classifier one-hot encodes y before calling a builder, so the builder sees y with shape (n_samples, n_classes) and the model must use categorical_crossentropy. In Keras 3.15 the estimator’s __sklearn_clone__ does not copy fit_kwargs, so any scikit-learn tool that clones it (cross_val_score, GridSearchCV, Pipeline inside them) trains with the fit defaults (one epoch, progress bar on); pass the arguments through params= of the scikit-learn function, or call fit(X, y, epochs=...) directly.

import keras
from keras.wrappers import SKLearnClassifier
from sklearn.datasets import make_classification
from sklearn.model_selection import cross_val_score


def build_model(X, y, hidden=(32, 32)):
    # The wrapper one-hot encodes y before calling the builder, so y has shape (n, n_classes)
    n_classes = y.shape[1] if y.ndim > 1 else 1
    model = keras.Sequential([keras.Input(shape=(X.shape[1],))])
    for units in hidden:
        model.add(keras.layers.Dense(units, activation="relu"))
    model.add(keras.layers.Dense(n_classes, activation="softmax"))
    model.compile(loss="categorical_crossentropy", optimizer="adam", metrics=["accuracy"])
    return model


X, y = make_classification(n_samples=500, n_features=10, n_informative=5, random_state=0)
est = SKLearnClassifier(model=build_model, model_kwargs={"hidden": (16, 16)})
# Keras 3.15 drops fit_kwargs when scikit-learn clones the estimator (cross_val_score does),
# so pass the fit arguments through params instead
print(cross_val_score(est, X, y, cv=3, params={"epochs": 20, "verbose": 0}).mean())   # 0.83 to 0.88, varies between runs

Because the page does not state in which Keras release the wrappers appeared, check the Keras release notes before depending on them in a pinned environment. For pipelines, cross-validation and parameter cloning, see Pipelines, Cross-Validation and Parameters and clone.

A migration checklist

  1. Pin versions: Python 3.13, TensorFlow 2.21, Keras 3.15; decide whether tf_keras is needed temporarily.

  2. Replace tf.keras imports with import keras.

  3. Run the test suite; fix SavedModel saves first (.keras and export).

  4. Replace Lambda layers with subclassed layers.

  5. Replace tf.* calls inside layers by keras.ops.

  6. Rewrite custom train_step code with compute_loss, or keep it TensorFlow-only on purpose.

  7. Revisit optimizers, learning-rate schedules, mixed precision and jit_compile.

  8. Retrain or reload weights; compare metrics against the Keras 2 baseline.

  9. Only then consider running on JAX or PyTorch.

Compare with how PyTorch handles state and serialization in Saving and Loading, and for choosing between stacks see Choosing a Framework.

References