Migrating from TensorFlow 1, where older books and tutorials are outdated

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

Much of the printed and online material about TensorFlow was written for TensorFlow 1, where a program first built a static graph and then ran it inside a Session. That programming model, and a large part of the API that went with it, no longer exists in current releases. This page lists the TensorFlow 1 idioms you will meet in older books, forum answers and research repositories, says what replaced each one, and shows how to port code mechanically with tf_upgrade_v2 and by hand. The modern equivalents are explained in depth on Graphs and tf.function, Variables, Modules, Automatic Differentiation and A Training Loop with TF Core. The Keras side of the story (Keras 2 versus Keras 3) is on Migrating from Keras 2 to Keras 3.

It targets Python 3.13 and TensorFlow 2.21 with Keras 3.15 (TensorFlow 2.22 is labelled upcoming) and was checked against the official documentation and the TensorFlow RELEASE.md on 2026-10-30. Examples were run on Python 3.13 with TensorFlow 2.21 and Keras 3.15 (CPU) on 2026-10-31, including tf_upgrade_v2 on a small TensorFlow 1 file.

How the programming model changed

In TensorFlow 1 a call such as tf.matmul(a, b) did not compute anything: it added a node to a global default graph and returned a symbolic handle. Values only appeared when a Session ran the graph with a feed_dict supplying the placeholders. TensorFlow 2 executes operations eagerly, like NumPy, and uses tf.function to compile an ordinary Python function into a graph only when you ask for it. Variables are ordinary Python objects that you keep track of yourself (usually as attributes of a tf.Module or a Keras layer), not entries in global collections.

TensorFlow 1 graph and session versus TensorFlow 2 eager and tf.function
Figure 1. TensorFlow 1 builds a graph and runs it in a session; TensorFlow 2 runs eagerly and traces a graph only on request.

The figure is an original drawing based on the explanations in the official TF1 versus TF2 guide.

Consequences you will notice when porting:

  • There is no Session, no tf.placeholder and no variable initializer step.

  • Variables, losses and weight updates are no longer discovered through global collections; you hold them yourself.

  • Python side effects inside a tf.function (appending to a list, printing) run only while tracing, not on each call.

  • Tensors compare by value with == in TensorFlow 2, so they are no longer hashable; use .ref() when a tensor must be a dictionary key or set member.

  • TensorShape entries are plain integers or None, so shape[0].value becomes shape[0].

A dated table of removed and replaced idioms

The table is dated 2026-10-30 and refers to TensorFlow 2.21. "Removed" means the symbol is not in the main tf namespace any more; many of the same names survive in tf.compat.v1, which exists only to help you migrate (see below).

TensorFlow 1 idiom (old books) TensorFlow 2.21 replacement Remarks

sess = tf.Session() and sess.run(fetches, feed_dict=...)

Call the function directly; wrap hot code in @tf.function

tf.compat.v1.Session remains only in the compat namespace

tf.placeholder(...)

A Python argument to a function, tf.TensorSpec in an input_signature, or keras.Input for functional models

Shapes and dtypes come from the real values

tf.global_variables_initializer()

Not needed

Variables are initialised when created

tf.get_variable, tf.variable_scope

tf.Variable held by a tf.Module or a Keras layer, created in __init__ or build

Naming through scopes is replaced by object attributes

Global collections such as tf.GraphKeys.TRAINABLE_VARIABLES

module.trainable_variables, model.trainable_variables

Collection APIs are unavailable under eager execution

tf.contrib.* (anything)

Removed with TensorFlow 2.0; use the mainline tf or keras API, a maintained community package, or copy the needed code

Not converted automatically by tf_upgrade_v2

tf.layers.* (for example tf.layers.dense)

keras.layers.* (for example keras.layers.Dense)

Keras layers are objects, not functions that create variables on each call

tf.train.AdamOptimizer, tf.train.GradientDescentOptimizer

keras.optimizers.Adam, keras.optimizers.SGD

Names and arguments differ; see Optimizers

optimizer.minimize(loss) building a graph op

tf.GradientTape plus optimizer.apply_gradients, or Model.fit

See GradientTape

tf.train.Saver, saver.save(sess, path)

tf.train.Checkpoint, keras.Model.save, Model.save_weights, Model.export

See Checkpoints and Saving Keras Models

tf.estimator.* (Estimator, train_and_evaluate, canned estimators)

Keras Model.fit with a tf.data input pipeline

The Estimator API was removed in TensorFlow 2.16

tf.feature_column.*

Keras preprocessing layers

See Preprocessing Layers

tf.data.Dataset.make_one_shot_iterator() and make_initializable_iterator()

Iterate the dataset in a for loop, or pass it to fit

See tf.data

tf.losses.*, tf.metrics.* (v1 graph versions)

keras.losses.*, keras.metrics.*

Metrics are stateful objects with update_state and result

tf.summary.FileWriter, tf.summary.merge_all

tf.summary.create_file_writer and tf.summary.scalar(name, value, step=...)

See TensorBoard

tf.app.run, tf.flags, tf.logging

absl.app, absl.flags, absl.logging or the standard logging module

Removed from the TensorFlow namespace

tf.control_dependencies

Usually unnecessary

Eager execution and tf.function run stateful operations in program order

tf.cond, tf.while_loop written with graph-time tensors

Plain Python if, for, while inside tf.function, converted by AutoGraph

Control flow v2 is function-based

tf.nn.dropout(x, keep_prob)

tf.nn.dropout(x, rate) or keras.layers.Dropout(rate)

Argument changed meaning: rate is the drop probability

tf.random_normal, tf.to_float, tf.log, tf.div

tf.random.normal, tf.cast, tf.math.log, tf.math.divide

Many top-level aliases moved into submodules

Two caveats about the table. First, the exact list of renamed top-level aliases is long and is generated, not memorised: let tf_upgrade_v2 rewrite them rather than editing by hand. Second, the script’s choices are conservative. Run on TensorFlow 2.21, it rewrites tf.random_normal to tf.random.normal, tf.log to tf.math.log and tf.to_float(x) to tf.cast(x, dtype=tf.float32), but tf.div only to tf.compat.v1.div and tf.train.Saver to tf.compat.v1.train.Saver, and it leaves tf.layers.dense untouched. The old names are gone from the top-level tf namespace and survive only under tf.compat.v1, and tf.compat.v1.layers.dense raises an AttributeError saying that dense is not available with Keras 3, so tf.layers code must be rewritten with keras.layers by hand.

tf.contrib is gone

tf.contrib was a staging area for experimental and community-contributed code. It was not shipped with TensorFlow 2.0, and the upgrade script reports uses of it as errors that it cannot fix. What replaced it depends on what you used:

  • Layers, RNN cells and learning utilities migrated into Keras (keras.layers, keras.layers.RNN with cell classes) or into the mainline tf.data, tf.distribute and tf.image modules.

  • Some projects moved to the separate TensorFlow Addons package. That package has since been archived, so new code should not depend on it; see Ecosystem and Project Status.

  • The remainder has to be replaced by a maintained library or by copying and maintaining the needed source yourself.

Treat any book chapter built around tf.contrib.slim, tf.contrib.learn, tf.contrib.rnn or tf.contrib.layers as historical. The concepts (convolutions, LSTMs, batch normalisation) still apply, but the code does not run.

tf.estimator is removed

Estimators were the high-level API of TensorFlow 1.x and early 2.x releases. They build graphs and sessions internally, so they never fitted the TensorFlow 2 execution model, and the official migration guide called them (together with tf.feature_column) "false friends" that live in the tf namespace but ignore TensorFlow 2 behaviour. The TensorFlow 2.16.1 release notes list the tf.estimator API as removed, so tf.estimator.Estimator, tf.estimator.train_and_evaluate, the canned estimators and Model.model_to_estimator are not available in TensorFlow 2.21. Port Estimator code to a Keras model trained with fit and a tf.data pipeline.

import keras
import tensorflow as tf


def make_dataset(features, labels, batch_size=32, training=True):
    """Replaces an Estimator input_fn."""
    ds = tf.data.Dataset.from_tensor_slices((features, labels))
    if training:
        ds = ds.shuffle(buffer_size=1024)
    return ds.batch(batch_size).prefetch(tf.data.AUTOTUNE)


def build_model(n_features):
    """Replaces model_fn: a Keras model instead of a function returning EstimatorSpec."""
    return keras.Sequential(
        [
            keras.Input(shape=(n_features,)),
            keras.layers.Dense(64, activation="relu"),
            keras.layers.Dense(1),
        ]
    )


model = build_model(10)
model.compile(optimizer="adam", loss="mse", metrics=["mae"])
# train_and_evaluate becomes fit with validation_data; predict stays predict.
# model.fit(make_dataset(x_train, y_train), validation_data=make_dataset(x_val, y_val, training=False), epochs=5)

Sessions and placeholders in practice

The classic TensorFlow 1 pattern and its TensorFlow 2 translation, side by side. The old version is shown only as prose: it declared a placeholder, built the expression, created a session, initialised variables and called run with a feed_dict. In TensorFlow 2 the same idea is a function.

import tensorflow as tf


@tf.function(input_signature=[tf.TensorSpec(shape=[None, 3], dtype=tf.float32)])
def affine(x):
    # w and b would normally live on a tf.Module or a Keras layer (see the Modules page)
    return tf.matmul(x, tf.ones([3, 2])) + 0.5


print(affine(tf.constant([[1.0, 2.0, 3.0]])))   # tf.Tensor([[6.5 6.5]], shape=(1, 2), dtype=float32)

Differences worth remembering:

  • input_signature plays the role the placeholder shape used to play; None leaves a dimension dynamic. Without a signature, tf.function retraces for each new input shape or dtype, which is covered on Graphs and tf.function.

  • A tf.function does not prune unused work the way Session.run(fetches) did: every variable update in the traced body runs even if you ignore part of the output. Split code into several functions when you only want part of it.

  • Variables may only be created on the first call of a traced function; create them outside or in build.

Variables, scopes and collections

TensorFlow 1 found variables by name through tf.get_variable, variable_scope and the global collections. TensorFlow 2 removes global collections: untracked variables are simply garbage collected. Group variables in a tf.Module (or a Keras layer or model) and read them through trainable_variables.

import tensorflow as tf


class Dense(tf.Module):
    def __init__(self, n_in, n_out, name=None):
        super().__init__(name=name)
        self.w = tf.Variable(tf.random.normal([n_in, n_out], stddev=0.1), name="w")
        self.b = tf.Variable(tf.zeros([n_out]), name="b")

    @tf.function
    def __call__(self, x):
        return tf.matmul(x, self.w) + self.b


layer = Dense(3, 2)
print([v.name for v in layer.trainable_variables])   # ['b:0', 'w:0']

Resource variables replace the old reference variables and are always used when eager execution is on. Code that tested isinstance(v, tf.compat.v1.Variable) can give different answers in TensorFlow 2; check the release notes if a legacy library does this.

The upgrade script tf_upgrade_v2

tf_upgrade_v2 is installed with TensorFlow and rewrites TensorFlow 1 Python source (and notebooks) to TensorFlow 2 style. It renames symbols, adds keyword arguments where parameter order changed, and writes a report with INFO, WARNING and ERROR lines with line numbers. It is a first step, not a guarantee that the code is correct TensorFlow 2 code.

# one file
tf_upgrade_v2 --infile old_model.py --outfile new_model.py

# a whole project, with a report
tf_upgrade_v2 --intree legacy_project/ --outtree legacy_project_v2/ --reportfile report.txt

# conservative mode: only switch imports to tensorflow.compat.v1
tf_upgrade_v2 --mode SAFETY --infile old_model.py --outfile old_model_safe.py

Useful options:

Option Effect

--infile, --outfile

Convert one .py or .ipynb file

--intree, --outtree

Convert a directory tree; --copyotherfiles controls whether non-Python files are copied

--inplace

Allow overwriting the input files

--mode DEFAULT or SAFETY

DEFAULT converts what it can and falls back to compat.v1 for the rest; SAFETY leaves the code as TensorFlow 1 and only changes imports

--reportfile

Where the report is written

--no_import_rename, --no_upgrade_compat_v1_import

Skip renaming the import to compat.v2, or skip upgrading an explicit compat.v1 import

--print_all

Print the entire log instead of only errors

Practical advice from the official guide: do not hand-edit before running the script (it can then map keyword arguments of reordered functions incorrectly), make sure tests exist and pass first, and read every ERROR line, since tf.contrib and similar usage is flagged but not converted. The recommended order is: test on TensorFlow 1.15, run the script over the whole tree including tests, review the report, install TensorFlow 2, run with tf.compat.v1.disable_v2_behavior(), then enable the version 2 behaviours and finally remove the remaining compat.v1 calls.

The script is still installed with TensorFlow 2.21 and runs on Python 3.13. On a small TensorFlow 1 file it renamed tf.Session and tf.placeholder to their tf.compat.v1 forms, reported tf.contrib.layers.flatten as an ERROR it cannot convert, and wrote the details to report.txt.

tf.compat.v1 as a bridge

tf.compat.v1 keeps most TensorFlow 1 symbols alive so migrated code can keep running while you modernise it. Treat it as a temporary bridge: the official guide advises proofreading the replacements the script produces and moving them to the tf.* namespace as soon as practical, because many compat.v1 APIs are not fully compatible with TensorFlow 2 behaviour. The collection APIs, for example, either raise or return empty lists under eager execution.

The behaviours can be toggled as a set or individually during an incremental port.

import tensorflow as tf

# Whole TensorFlow 1 behaviour back (graph mode, sessions): useful as a first run of converted code
tf.compat.v1.disable_v2_behavior()

# Or move forward one switch at a time (argument-free calls)
tf.compat.v1.enable_eager_execution()      # can be set once per program
tf.compat.v1.enable_resource_variables()
tf.compat.v1.enable_control_flow_v2()
tf.compat.v1.enable_v2_tensorshape()
tf.compat.v1.enable_tensor_equality()

Some of these switches only apply when eager execution is disabled, and "collection removal" cannot be toggled on its own because it follows from eager execution. Do not run both a disable_v2_behavior() and an enable_eager_execution() line in one program; the snippet shows the options, not a single working script. Run in separate processes, each alternative works: after disable_v2_behavior(), tf.executing_eagerly() returns False, and the sequence of enable_* calls leaves eager execution on. Calling enable_eager_execution() after TensorFlow has already run something raises ValueError: tf.enable_eager_execution must be called at program startup.

Porting a training loop

A condensed example of the end state: a Keras model, a GradientTape step compiled with tf.function, and no session.

import keras
import tensorflow as tf

model = keras.Sequential([keras.Input(shape=(4,)), keras.layers.Dense(8, activation="relu"), keras.layers.Dense(1)])
optimizer = keras.optimizers.Adam(1e-3)
loss_fn = keras.losses.MeanSquaredError()


@tf.function
def train_step(x, y):
    with tf.GradientTape() as tape:
        pred = model(x, training=True)
        loss = loss_fn(y, pred)
    grads = tape.gradient(loss, model.trainable_variables)
    optimizer.apply_gradients(zip(grads, model.trainable_variables))
    return loss


x = tf.random.normal([32, 4])
y = tf.random.normal([32, 1])
for step in range(3):
    print(step, float(train_step(x, y)))

The same design in more depth is on Writing a Training Loop from Scratch. Compare with PyTorch, which was always eager, in the PyTorch training loop.

Recognising outdated advice

When a tutorial shows any of the following, assume it targets TensorFlow 1 (or early 2.x with Keras 2) and look for a current equivalent:

Sign in the text What to do

import tensorflow as tf followed by tf.Session(), tf.placeholder or tf.global_variables_initializer()

Rewrite as eager code or a tf.function

tf.contrib anywhere

Find a mainline or maintained replacement

tf.estimator, input_fn, model_fn

Move to Keras fit and tf.data

from tensorflow.contrib.keras or tf.layers

Use keras.layers

"Keras is a separate library you install on top of TensorFlow"

In current releases import keras is Keras 3 and tf.keras resolves to it; see Keras 3 Overview

model.save("dir") described as the way to write a SavedModel

Use model.save("model.keras") and model.export(...); see Saving Keras Models

TensorFlow Lite as tf.lite

The runtime is now LiteRT; see On-Device Inference with LiteRT

For the surrounding landscape, see the general training deep networks page and the framework comparison on Choosing a Framework.

References