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 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 has been the default since TensorFlow 2.x. This lab covers tf.executing_eagerly(), constants, variables and ordinary Python control flow, and adds corrected outputs, gradients with GradientTape and how eager mode relates to tf.function.


What eager execution is and why it matters

TensorFlow 1.x worked in two steps. You defined a static graph, then ran it inside a tf.Session. Intermediate values were symbolic, so you couldn't print them or use them in a Python if statement. Eager execution drops that split. Each call such as tf.matmul or tf.add runs right away and returns a tf.Tensor that already holds its value, which you can read with .numpy().

Eager mode is on by default in TensorFlow 2, which is why the first cell above, tf.executing_eagerly(), returns True. You can debug with print or a normal debugger, use NumPy-style code and mix TensorFlow with plain Python. For speed and deployment, you can still compile functions into graphs with tf.function, which is covered further down.

Prerequisites and setup

The notebook was saved with Python 3.7. Current TensorFlow releases need a newer Python, so check the supported versions on the TensorFlow install page and create a fresh virtual environment before you start.

python3 -m venv tf-lab
source tf-lab/bin/activate
pip install --upgrade pip
pip install tensorflow notebook
python -c "import tensorflow as tf; print(tf.__version__, tf.executing_eagerly())"Code language: JavaScript (javascript)

The last command prints the installed version and then True. If it prints False, some code or a legacy import has disabled eager mode. One example is tf.compat.v1.disable_eager_execution().

Understanding the tensor operations in the example

  • tf.matmul(x, x) with x = [[10.]] is matrix multiplication. TensorFlow converts the Python list to a float32 tensor of shape (1, 1), and the result is [[100.]]. Both inputs to tf.matmul must have rank 2 or higher.
  • tf.constant([[10, 20], [30, 40]]) infers int32 because the literals are integers. Writing 10.0 instead would give float32.
  • tf.add(a, 2) broadcasts the scalar 2 across every element, so the result is [[12, 22], [32, 42]].
  • a * b is element-wise multiplication, the same as tf.multiply. It is not a matrix product. For a matrix product, use tf.matmul(a, b) or a @ b.
  • m * x + c with three tf.Variable objects returns a plain tf.Tensor, not a variable. Arithmetic on variables always produces new tensors.
import tensorflow as tf

a = tf.constant([[10, 20], [30, 40]])
b = tf.add(a, 2)

print(a * b)        # element-wise
print(a @ b)        # matrix product, same as tf.matmul(a, b)
print((a * b).numpy())  # plain NumPy arrayCode language: PHP (php)
tf.Tensor(
[[ 120  440]
 [ 960 1680]], shape=(2, 2), dtype=int32)
tf.Tensor(
[[ 760  840]
 [1640 1820]], shape=(2, 2), dtype=int32)
[[ 120  440]
 [ 960 1680]]

Corrections to the notebook

Some of the saved outputs in the notebook come from earlier runs: the execution counters jump around (7, then 19 to 23). Two of those outputs don't match the current code, and the variable constructor is called incorrectly. Here is the corrected version:

import tensorflow as tf

a = tf.constant([[10, 20], [30, 40]])
b = tf.add(a, 2)
print(a * b)
# Correct output: [[120 440] [960 1680]]
# (the notebook shows [[200 231] [264 299]], a stale result)

# Pass dtype by keyword. The second positional argument of tf.Variable is `trainable`.
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')
x = tf.Variable([100.0, 100.0, 100.0], dtype=tf.float32, name='x')
print(x)
# <tf.Variable 'x:0' shape=(3,) dtype=float32, numpy=array([100., 100., 100.], dtype=float32)>
# (the notebook shows 'v:0', left over from an older run)

y = m * x + c
print(y)  # tf.Tensor([401. 501. 601.], shape=(3,), dtype=float32)Code language: PHP (php)

Note: Before you share a notebook, use Kernel > Restart & Run All so that every saved output matches the code above it.

Updating variables in place

A tf.Tensor is immutable. A tf.Variable holds state you can change, which is how model weights are stored. Update it with assign, assign_add or assign_sub. Don't rebind it with =, because that replaces the Python object with a new tensor.

x.assign([200.0, 200.0, 200.0])
x.assign_add([1.0, 1.0, 1.0])
print(x.numpy())            # [201. 201. 201.]
print((m * x + c).numpy())  # [ 805. 1006. 1207.]Code language: CSS (css)

Dynamic control flow and gradients

Every value exists right away in eager mode. That's why the FizzBuzz-style function above can use ordinary for, if and elif on tensor values. In that function, counter is incremented but never used, so you can remove it. Calling the function tensorflow also makes the code harder to read. Here is a shorter equivalent that loops over tf.range:

def classify(max_num):
    for n in tf.range(max_num + 1):
        if n % 15 == 0:
            print('Divisible by 3 and 5:', n.numpy())
        elif n % 3 == 0:
            print('Divisible by 3:', n.numpy())
        elif n % 5 == 0:
            print('Divisible by 5:', n.numpy())
        else:
            print(n.numpy())

classify(15)Code language: PHP (php)

Eager mode also lets you compute gradients on the fly. tf.GradientTape records the operations run inside its block and then differentiates them. Training loops are built on this.

w = tf.Variable(3.0)
with tf.GradientTape() as tape:
    loss = w * w + 2.0 * w      # loss = w^2 + 2w

grad = tape.gradient(loss, w)   # d(loss)/dw = 2w + 2
print(grad)                     # tf.Tensor(8.0, shape=(), dtype=float32)Code language: PHP (php)

Eager execution versus tf.function

Eager mode is easy to work with, but each operation goes through Python one at a time. Decorating a function with @tf.function traces it into a graph that TensorFlow can optimise and export in a SavedModel. Inside the traced function, tf.executing_eagerly() returns False.

@tf.function
def linear(m, x, c):
    print('Tracing, eager =', tf.executing_eagerly())  # runs only while tracing
    tf.print('Running, y =', m * x + c)                 # runs on every call
    return m * x + c

linear(m, x, c)
linear(m, x, c)   # no second 'Tracing' line: the graph is reusedCode language: PHP (php)
AspectEager (default)tf.function
When ops runImmediately, one by oneTraced once, then the graph runs
Debuggingprint, pdb, .numpy() all workUse tf.print; .numpy() is unavailable
Python if/for on tensorsPlain PythonConverted by AutoGraph to tf.cond / tf.while_loop
PerformancePython overhead per opUsually faster for many small ops
Export to SavedModelNot directlyYes

Note: To step through a tf.function while debugging, call tf.config.run_functions_eagerly(True). Set it back to False afterwards, or the performance gain disappears.

Common errors and fixes

ErrorCauseFix
InvalidArgumentError: expected to be a int32 tensor but is a float tensorMixing dtypes, for example int32 a with a float32 tensorConvert first: tf.cast(a, tf.float32)
TypeError: Cannot convert 1.5 to EagerTensor of dtype int32Python float used with an int32 tensor, for example a * 1.5Create the tensor with floats or cast it
InvalidArgumentError from tf.matmul about rank or shapeInputs are 1-D or the inner dimensions don't matchReshape to 2-D and check that a.shape[-1] == b.shape[-2]
AttributeError: 'Tensor' object has no attribute 'numpy'Called .numpy() inside tf.function or on a graph tensorUse tf.print, or return the tensor and call .numpy() outside
tf.executing_eagerly() returns False at top levelLegacy code called disable_eager_execution() or uses TF1 sessionsRemove that call and migrate the session code to TF2 style

Frequently asked questions

Is eager execution enabled by default in TensorFlow 2?

Yes. TensorFlow 2 runs eagerly by default, so tf.executing_eagerly() returns True at the top level. It returns False only inside a tf.function, or if legacy code has disabled eager mode.

How do I get a NumPy array from an eager tensor?

Call .numpy() on the tensor or variable, for example y.numpy(). This works only in eager mode, not inside a function decorated with tf.function.

What is the difference between a * b and tf.matmul(a, b)?

a * b multiplies matching elements and is the same as tf.multiply. tf.matmul(a, b), or a @ b, computes a matrix product, which needs the inner dimensions to match.

Should I disable eager execution for better performance?

No. Keep eager mode on and wrap the heavy parts in @tf.function. You get graph performance there and can still debug the rest of the code easily.

Why does tf.Variable([1.0], tf.float32) not set the dtype?

The second positional argument of tf.Variable is trainable, not dtype. Pass the type by keyword, as in tf.Variable([1.0], dtype=tf.float32).

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 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…

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