This lab shows how TensorFlow 1.x style graphs and sessions still work in TensorFlow 2 through the tf.compat.v1 API. You will see why Session.run() fails while eager execution is on, how to turn eager execution off, and how to run constants, variables and placeholders with feed_dict. The last step writes the graph so you can view it in TensorBoard. Below the notebook you will find a corrected script, the TensorFlow 2 way to do the same thing, and fixes for the errors you are most likely to hit.
What the notebook demonstrates
TensorFlow 1.x worked in two phases. First you built a computation graph, and nothing was computed while you did that. Then you opened a Session and called run() to evaluate parts of the graph. TensorFlow 2 turns on eager execution by default, so every operation runs as soon as you call it and returns a concrete value. The tf.compat.v1 module keeps the old graph and session API available so that legacy code can still run.
| Notebook step | What happens | Why |
|---|---|---|
executing_eagerly() returns True | TF2 default mode | Ops run immediately |
sess.run(c) raises The Session graph is empty | The session has nothing to execute | a, b and c were computed eagerly and never added to a graph |
c shows numpy=12 | The value already exists | Eager tensors hold their result |
disable_eager_execution() and then reset_default_graph() | Switches to graph mode with a clean graph | New ops go into the default graph |
c shows 'sum:0' with no value | A symbolic tensor | It is only computed when a session runs it |
sess.run(c) returns 12, sess.run(d) returns 35 | The session evaluates graph nodes | d was added to the same default graph after the session was created |
Variables, placeholder, feed_dict | Returns [401. 501. 601.] | 100 ร [4, 5, 6] + 1 |
FileWriter and %tensorboard | Saves and displays the graph | For visual inspection |
Prerequisites
- Python 3 with a current TensorFlow 2.x release (
pip install tensorflow). The notebook output showspython3.7andtensorflow_corepaths, which come from an early TF 2 install. Current TensorFlow releases no longer support Python 3.7, so use a newer interpreter. - Jupyter Notebook or JupyterLab (
pip install notebook). TensorBoard is installed together with thetensorflowpackage. - A fresh kernel. Eager execution can only be switched off for the whole process, and the notebook ends by telling you to restart Jupyter for that reason.
python -m venv tf-lab
source tf-lab/bin/activate
pip install tensorflow notebook
python -c "import tensorflow as tf; print(tf.__version__, tf.executing_eagerly())"Code language: JavaScript (javascript)
Corrected, runnable version of the lab
The script below runs the graph-mode part of the notebook in one go. It fixes the tf.Variable call, turns off eager execution before any tensors exist, and uses a with block so the session is always closed. Save it as v1_sessions.py and run it with python v1_sessions.py.
import tensorflow as tf
# Must run before any graphs, ops or tensors are created
tf.compat.v1.disable_eager_execution()
print("Eager:", tf.compat.v1.executing_eagerly()) # False
# Constants and simple ops
a = tf.constant(5, name="a")
b = tf.constant(7, name="b")
total = tf.add(a, b, name="sum")
product = tf.multiply(a, b, name="product")
# Variables need dtype as a keyword argument
m = tf.Variable([4.0, 5.0, 6.0], dtype=tf.float32, name="m")
c = tf.Variable([1.0, 1.0, 1.0], dtype=tf.float32, name="c")
# Placeholder: a value supplied at run time through feed_dict
x = tf.compat.v1.placeholder(tf.float32, shape=[3], name="x")
y = m * x + c
init = tf.compat.v1.global_variables_initializer()
with tf.compat.v1.Session() as sess:
print("sum, product:", sess.run([total, product]))
sess.run(init)
y_output = sess.run(y, feed_dict={x: [100.0, 100.0, 100.0]})
print("Final result: mx + c =", y_output)
writer = tf.compat.v1.summary.FileWriter("./logs", sess.graph)
writer.close()Code language: PHP (php)
Eager: False
sum, product: [12, 35]
Final result: mx + c = [401. 501. 601.]Code language: PHP (php)
sess.run([total, product])fetches several tensors in one call and returns them as a list.global_variables_initializer()only builds an op. Variables have no value untilsess.run(init)runs it.feed_dictmaps each placeholder tensor to a concrete value for that singlerun()call. The value must match the placeholder's dtype and shape.FileWriter(logdir, sess.graph)saves the graph definition as an event file that TensorBoard can read.
What was wrong in the original notebook
The notebook runs, but some of its output comes from a bug and some from cells that were run more than once.
tf.Variable([4.0, 5.0, 6.0], tf.float32, name='m'): the second positional parameter oftf.Variableistrainable, notdtype. The code setstrainable=tf.float32, and that causes the later warningtf.float32 has type DType, but expected one of: int, long, boolwhen thevariablesandtrainable_variablescollections are serialized. Passdtype=tf.float32as a keyword and the warning goes away. The values are floats either way, because the initial value already contains floats.- Placeholder named
x_1:0instead ofx:0: the cell was run twice, so TensorFlow gave the second node a unique name. In graph mode, every time you re-run a cell it adds new nodes to the default graph. Calltf.compat.v1.reset_default_graph()and rebuild the graph, or restart the kernel. - The first session is never closed:
sess = tf.compat.v1.Session()in eager mode is left open. Preferwith tf.compat.v1.Session() as sess:blocks. - Calling
disable_eager_execution()partway through the notebook: the TensorFlow documentation says to call it at program startup, before any graphs, ops or tensors are created. It happened to work in this demo, but in real code put it directly after the import. !rm -rf ./logs/only works on Linux and macOS. On Windows, useshutil.rmtree('./logs', ignore_errors=True)in Python.
Viewing the graph in TensorBoard
The %tensorboard magic embeds TensorBoard in the notebook, but the graph explorer is easier to use in a separate browser tab. You can also start TensorBoard from a terminal:
tensorboard --logdir ./logs --port 6060
# then open http://localhost:6060 and select the Graphs tabCode language: PHP (php)
Look for the nodes m, c, x, mul and add. Turn on Trace inputs and click add to highlight the path from x through mul. If you see duplicate nodes such as x_1, the graph was built more than once in the same kernel.
Note: If TensorBoard reports that it is reusing an existing instance, as in the notebook output, it may still be showing an old log directory. Stop the old process (kill <pid>) or pick a different --port.
The same computation in TensorFlow 2 style
Use tf.compat.v1 only for migrating or maintaining legacy code. For new code, tf.function replaces sessions, normal function arguments replace placeholders, and variables are initialized when you create them. You can still export a graph for TensorBoard with the trace API:
import tensorflow as tf # fresh kernel, eager execution on
m = tf.Variable([4.0, 5.0, 6.0], name="m")
c = tf.Variable([1.0, 1.0, 1.0], name="c")
@tf.function
def linear(x):
return m * x + c
writer = tf.summary.create_file_writer("./logs/tf2")
tf.summary.trace_on(graph=True)
y = linear(tf.constant([100.0, 100.0, 100.0]))
with writer.as_default():
tf.summary.trace_export(name="linear", step=0)
print(y.numpy()) # [401. 501. 601.]
| TF1 / compat.v1 | TF2 equivalent |
|---|---|
Session.run(t) | Call the function; use t.numpy() for the value |
placeholder + feed_dict | Function arguments |
global_variables_initializer() | Not needed |
summary.FileWriter(dir, graph) | summary.create_file_writer + trace_on / trace_export |
Common errors and fixes
| Error | Cause | Fix |
|---|---|---|
RuntimeError: The Session graph is empty | The tensors were created in eager mode | Call disable_eager_execution() first, then rebuild the ops |
RuntimeError: tf.placeholder() is not compatible with eager execution | Eager execution is still on | Disable it at startup or use a tf.function argument |
InvalidArgumentError: You must feed a value for placeholder tensor 'x' | feed_dict is missing | Pass feed_dict={x: ...} |
FailedPreconditionError mentioning an uninitialized variable | init was not run | Call sess.run(init) before reading the variables |
ValueError: Cannot feed value of shape (2,) for Tensor 'x:0' | The fed value has the wrong shape | Match the placeholder shape, or use shape=[None] |
RuntimeError: Attempted to use a closed Session | run() was called after close() | Open a new session or keep the work inside the with block |
Frequently asked questions
Does TensorFlow 2 still support tf.Session?
Not as tf.Session. It is available as tf.compat.v1.Session, and it works on graph tensors, which in practice means you need to disable eager execution first. It is meant for running legacy code.
Why does sess.run() say the session graph is empty?
With eager execution on, ops run immediately and are never added to the default graph, so the session has nothing to execute. Call tf.compat.v1.disable_eager_execution() at program start and build the graph again.
How do I re-enable eager execution after disabling it?
Restart the Python process or Jupyter kernel. Eager mode is a process-wide setting and should not be switched back and forth in the middle of a program.
What replaces placeholders and feed_dict in TensorFlow 2?
Write a Python function that takes the inputs as arguments, optionally decorate it with @tf.function for graph performance, and call it with tensors or NumPy arrays.
Why do my node names end in _1 in TensorBoard?
The same cell ran more than once in graph mode, so TensorFlow added duplicate nodes and gave them unique names. Reset the default graph or restart the kernel before you rebuild it.
Related tutorials
- More Machine Learning tutorials
- Staff MLOps Engineer: Role Blueprint, Responsibilities, Skills, KPIs, and Career Path
- Lead Machine Learning Engineer: Role Blueprint, Responsibilities, Skills, KPIs, and Career Path
I’m Rajesh Kumar, a DevOps, SRE, DevSecOps, Cloud, and Platform Engineering expert passionate about sharing practical knowledge, real-world experiences, and industry best practices. I have worked at Cotocus and regularly write about technology, travel, investing, health, product reviews, and digital marketing through my various platforms.
I publish technical articles at DevOps School, travel stories at Holiday Landmark, stock market insights at Stocks Mantra, health and fitness guidance at My Medic Plus, product reviews at TrueReviewNow, and SEO and digital marketing strategies at Wizbrand.
Find Trusted Cardiac Hospitals
Compare heart hospitals by city and services โ all in one place.
Explore Hospitals