Older TensorFlow applications can stop at training setup after a framework upgrade because the Estimator API has been removed. Replacing the Estimator pipeline with Keras restores training and evaluation while allowing the model's held-out metrics to be compared against the original implementation.
An Estimator input function becomes a tf.data.Dataset passed to Keras, while the model function's layers, loss, optimizer, and metrics move into a Keras model and its compile configuration. Matching those definitions and the number of training updates matters more than matching method names; changing the data split or optimization settings would make a metric comparison ambiguous.
A CPU regression model provides a small migration case with a fixed training split and separate Estimator and Keras environments. Retraining starts from the same initialization rather than reusing Estimator checkpoints, and the legacy source, environment, and checkpoints remain available for rollback. Existing checkpoint reuse requires a separate checkpoint compatibility assessment.
Steps to migrate TensorFlow Estimator code to Keras:
- Refresh the Ubuntu package index for the Python environment prerequisites.
$ sudo apt-get update
Tested on Ubuntu 26.04 with Linux ARM64 CPU builds, TensorFlow 2.15.1 for Estimator, and TensorFlow 2.21.0 for Keras. Python 3.11 works with both versions; Ubuntu 26.04's default Python 3.14 has no wheel for this Estimator baseline. The user-local Python installation below leaves the system interpreter unchanged.
- Install Ubuntu's virtual-environment support.
$ sudo apt-get install --yes python3-venv
- Create a separate environment for the Python download tool.
$ python3 -m venv .python-tools
The working directory holds the source files and environments for this migration case.
Related: How to create a virtual environment in Python - Install uv into the tool environment.
$ .python-tools/bin/python -m pip install uv
uv's managed Python installations supply Python 3.11 without replacing Ubuntu's Python.
- Download a user-local Python 3.11 interpreter.
$ .python-tools/bin/uv python install 3.11
- Create the legacy environment with that interpreter.
$ "$(.python-tools/bin/uv python find 3.11)" \ -m venv .venv-estimator - Activate the Estimator environment.
$ source .venv-estimator/bin/activate
- Install the compatible Estimator runtime.
$ python -m pip install tensorflow==2.15.1
TensorFlow 2.16.1 removed tf.estimator. Installing legacy Keras in a newer TensorFlow environment does not restore that API.
- Create inputs.py in your text editor with the fixed data split and input pipeline.
- inputs.py
import numpy as np import tensorflow as tf x = np.linspace( -1, 1, 128, dtype=np.float32 ).reshape(-1, 1) y = 3 * x + 2 def dataset(training): indices = np.arange(0 if training else 1, 128, 2) data = tf.data.Dataset.from_tensor_slices( (x[indices], y[indices]) ) data = data.batch(64) return data.repeat() if training else data
Even-indexed rows supply one 64-row training batch; odd-indexed rows supply one held-out batch. Only training repeats. Both implementations import this unchanged file, so feature shape, labels, batching, and split stay identical.
Related: How to split a dataset into train, validation, and test sets in TensorFlow - Save inputs.py.
- Create estimator_train.py in your text editor with the legacy imports.
- estimator_train.py
import json import tensorflow as tf import tensorflow.compat.v1 as tf1 from inputs import dataset
- Append the Estimator model function after the imports in estimator_train.py.
def model_fn(features, labels, mode): kernel = tf1.get_variable( "kernel", [1, 1], initializer=tf.zeros_initializer() ) bias = tf1.get_variable( "bias", [1], initializer=tf.zeros_initializer() ) predictions = tf.matmul(features, kernel) + bias if mode == tf.estimator.ModeKeys.PREDICT: return tf.estimator.EstimatorSpec( mode, predictions=predictions ) loss = tf.reduce_mean(tf.square(labels - predictions)) if mode == tf.estimator.ModeKeys.TRAIN: optimizer = tf1.train.GradientDescentOptimizer(0.1) train_op = optimizer.minimize( loss, global_step=tf1.train.get_or_create_global_step(), ) return tf.estimator.EstimatorSpec( mode, loss=loss, train_op=train_op ) return tf.estimator.EstimatorSpec( mode, loss=loss, eval_metric_ops={ "mse": tf1.metrics.mean_squared_error( labels, predictions ), "mae": tf1.metrics.mean_absolute_error( labels, predictions ), }, )
The model is one linear output with a bias, zero-initialized parameters, mean squared error loss, and SGD at a learning rate of 0.1. Evaluation reports mean squared error and mean absolute error.
- Append the training and baseline export after the model function in estimator_train.py.
estimator = tf.estimator.Estimator( model_fn=model_fn, model_dir="estimator-checkpoints" ) estimator.train(lambda: dataset(True), max_steps=60) metrics = estimator.evaluate(lambda: dataset(False)) baseline = { name: float(metrics[name]) for name in ("mse", "mae") } with open("baseline.json", "w") as output: json.dump(baseline, output) print(baseline)
The first execution uses a new checkpoint directory. Estimator resumes from that directory on later executions, and max_steps=60 caps its total global step at 60.
- Save estimator_train.py.
- Run the legacy model to record its held-out metrics.
$ python estimator_train.py
Estimator emits deprecation warnings under TensorFlow 2.15.1. They are expected for the legacy API; training must still finish and create baseline.json.
- Record the legacy environment's installed packages for rollback.
$ python -m pip freeze > requirements-estimator.txt
The Keras rewrite uses a new source file and a new model file. Keeping the legacy source, checkpoint directory, baseline metrics, and environment avoids overwriting the working Estimator application. For an existing application, a source-control commit or backup must also cover its own code and training artifacts before migration.
- Deactivate the legacy environment.
$ deactivate
- Create a separate Keras environment with Python 3.11.
$ "$(.python-tools/bin/uv python find 3.11)" \ -m venv .venv-keras - Activate the Keras environment.
$ source .venv-keras/bin/activate
- Install the target TensorFlow runtime.
$ python -m pip install tensorflow==2.21.0
NumPy is installed as a TensorFlow dependency in both environments. An existing application's other dependencies also need to be installed in the Keras environment, with versions compatible with the target runtime.
Related: How to install TensorFlow with pip - Confirm that the target runtime no longer exposes Estimator. Example output:
$ python -c "import tensorflow as tf; print(tf.estimator)" ##### snipped ##### AttributeError: module 'tensorflow' has no attribute 'estimator'
This expected error identifies the removed API; it is not a reason to downgrade the new Keras environment.
- Create keras_train.py in your text editor with the shared input pipeline and equivalent Keras layers.
- keras_train.py
import json import math import tensorflow as tf from inputs import dataset model = tf.keras.Sequential([ tf.keras.Input(shape=(1,)), tf.keras.layers.Dense( 1, kernel_initializer="zeros", bias_initializer="zeros" ), ])
The Dense layer replaces the model function's matrix multiplication and bias. It retains one output, no activation, and the same initial weights.
- Append the matching optimizer, loss, and metric configuration to keras_train.py.
model.compile( optimizer=tf.keras.optimizers.SGD(learning_rate=0.1), loss=tf.keras.losses.MeanSquaredError(), metrics=[ tf.keras.metrics.MeanSquaredError(name="mse"), tf.keras.metrics.MeanAbsoluteError(name="mae"), ], )
Keras owns gradient application and metric updates. A custom Estimator training operation that cannot be expressed by compile needs a custom Keras train_step instead. Loss reduction, sample weights, and optimizer settings need to retain their original meaning when adapting a different model.
- Append the training section to keras_train.py.
model.fit( dataset(True), epochs=1, steps_per_epoch=60, shuffle=False, verbose=0, ) model.save("regressor.keras") restored = tf.keras.models.load_model("regressor.keras") metrics = restored.evaluate( dataset(False), return_dict=True, verbose=0 )
One epoch of 60 repeated batches matches the baseline's 60 gradient updates. Evaluation consumes the finite held-out dataset once. The new Keras file contains the retrained model; the Estimator checkpoint directory is not passed to load_model.
- Append the held-out metric comparison to keras_train.py.
with open("baseline.json") as source: baseline = json.load(source) accepted = True tolerances = {"mse": 0.00001, "mae": 0.00001} for name, tolerance in tolerances.items(): delta = abs(metrics[name] - baseline[name]) accepted &= math.isfinite(delta) and delta <= tolerance print(f"{name}:") print(f" Estimator: {baseline[name]:.8f}") print(f" Keras: {metrics[name]:.8f}") print(f" Difference: {delta:.8f}") print(f" Tolerance: {tolerance:.5f}") print(f"Within tolerance: {accepted}") if not accepted: raise SystemExit("Metric drift exceeds tolerance")
The absolute tolerance is 0.00001 for each metric in this deterministic regression case. A different application needs tolerances chosen before migration, using its held-out baseline and acceptable quality change. A failure calls for checking the split, preprocessing, architecture, loss reduction, optimizer, and update count before loosening the threshold.
- Save keras_train.py.
- Run the Keras replacement to compare the reloaded model against the Estimator baseline. Example output:
$ python keras_train.py mse: Estimator: 0.00068845 Keras: 0.00068846 Difference: 0.00000001 Tolerance: 0.00001 mae: Estimator: 0.02271842 Keras: 0.02271853 Difference: 0.00000012 Tolerance: 0.00001 Within tolerance: True
A passing comparison reports Within tolerance: True and leaves regressor.keras available for use. Returning to the legacy environment and estimator_train.py preserves the rollback path while differences are investigated.