MYHOSPITALNOW.COM

Find Trusted Doctors & Hospitals

Discover healthcare providers, compare hospitals, and explore treatment options worldwide.

Free Treatment Quotes • Doctor Search • Hospital Comparison

Find Healthcare Options

www.myhospitalnow.com

Tensorsflow Lab2 – Tensorsflow V1Sessions

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 stepWhat happensWhy
executing_eagerly() returns TrueTF2 default modeOps run immediately
sess.run(c) raises The Session graph is emptyThe session has nothing to executea, b and c were computed eagerly and never added to a graph
c shows numpy=12The value already existsEager tensors hold their result
disable_eager_execution() and then reset_default_graph()Switches to graph mode with a clean graphNew ops go into the default graph
c shows 'sum:0' with no valueA symbolic tensorIt is only computed when a session runs it
sess.run(c) returns 12, sess.run(d) returns 35The session evaluates graph nodesd was added to the same default graph after the session was created
Variables, placeholder, feed_dictReturns [401. 501. 601.]100 ร— [4, 5, 6] + 1
FileWriter and %tensorboardSaves and displays the graphFor visual inspection

Prerequisites

  • Python 3 with a current TensorFlow 2.x release (pip install tensorflow). The notebook output shows python3.7 and tensorflow_core paths, 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 the tensorflow package.
  • 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 until sess.run(init) runs it.
  • feed_dict maps each placeholder tensor to a concrete value for that single run() 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 of tf.Variable is trainable, not dtype. The code sets trainable=tf.float32, and that causes the later warning tf.float32 has type DType, but expected one of: int, long, bool when the variables and trainable_variables collections are serialized. Pass dtype=tf.float32 as a keyword and the warning goes away. The values are floats either way, because the initial value already contains floats.
  • Placeholder named x_1:0 instead of x: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. Call tf.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. Prefer with 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, use shutil.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.v1TF2 equivalent
Session.run(t)Call the function; use t.numpy() for the value
placeholder + feed_dictFunction arguments
global_variables_initializer()Not needed
summary.FileWriter(dir, graph)summary.create_file_writer + trace_on / trace_export

Common errors and fixes

ErrorCauseFix
RuntimeError: The Session graph is emptyThe tensors were created in eager modeCall disable_eager_execution() first, then rebuild the ops
RuntimeError: tf.placeholder() is not compatible with eager executionEager execution is still onDisable it at startup or use a tf.function argument
InvalidArgumentError: You must feed a value for placeholder tensor 'x'feed_dict is missingPass feed_dict={x: ...}
FailedPreconditionError mentioning an uninitialized variableinit was not runCall sess.run(init) before reading the variables
ValueError: Cannot feed value of shape (2,) for Tensor 'x:0'The fed value has the wrong shapeMatch the placeholder shape, or use shape=[None]
RuntimeError: Attempted to use a closed Sessionrun() 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

Find Trusted Cardiac Hospitals

Compare heart hospitals by city and services โ€” all in one place.

Explore Hospitals
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.

Related Posts

Tensorsflow Lab8 – Tensorsflow FunctionalModel

This lab uses the UCI heart disease dataset (303 patients, 13 features, a binary target) to build a binary classifier with the Keras Functional API in TensorFlow….

Read More

Tensorsflow Lab7 – Tensorsflow SequentialModel

This lab uses the WHO life expectancy dataset to build a regression model with the TensorFlow Keras Sequential API. The notebook above covers loading the data, inspecting…

Read More

Tensorsflow Lab6 – Tensorsflow SimpleLinearRegression

This lab builds simple linear regression (y = Wx + b) from scratch in TensorFlow 2. It creates the weight and bias with tf.Variable, computes gradients of…

Read More

Tensorsflow Lab5 – Tensorsflow GradientTape

tf.GradientTape is TensorFlow's automatic differentiation API. It records the operations you run inside a with block, then plays them back in reverse to compute gradients for training….

Read More

Tensorsflow Lab4 – Tensorsflow function

This lab shows how tf.function turns ordinary Python functions into TensorFlow graphs. It covers how AutoGraph converts if, for and while into graph ops, why Python side…

Read More

Tensorsflow Lab3 – Tensorsflow EagerExecution

In eager execution, TensorFlow runs each operation as soon as Python calls it and gives you a concrete value back, with no graph to build first. It…

Read More
Subscribe
Notify of
guest
0 Comments
Newest
Oldest Most Voted
0
Would love your thoughts, please comment.x
()
x