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)withx = [[10.]]is matrix multiplication. TensorFlow converts the Python list to a float32 tensor of shape (1, 1), and the result is[[100.]]. Both inputs totf.matmulmust have rank 2 or higher.tf.constant([[10, 20], [30, 40]])infersint32because the literals are integers. Writing10.0instead would givefloat32.tf.add(a, 2)broadcasts the scalar2across every element, so the result is[[12, 22], [32, 42]].a * bis element-wise multiplication, the same astf.multiply. It is not a matrix product. For a matrix product, usetf.matmul(a, b)ora @ b.m * x + cwith threetf.Variableobjects returns a plaintf.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)
| Aspect | Eager (default) | tf.function |
|---|---|---|
| When ops run | Immediately, one by one | Traced once, then the graph runs |
| Debugging | print, pdb, .numpy() all work | Use tf.print; .numpy() is unavailable |
| Python if/for on tensors | Plain Python | Converted by AutoGraph to tf.cond / tf.while_loop |
| Performance | Python overhead per op | Usually faster for many small ops |
| Export to SavedModel | Not directly | Yes |
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
| Error | Cause | Fix |
|---|---|---|
| InvalidArgumentError: expected to be a int32 tensor but is a float tensor | Mixing dtypes, for example int32 a with a float32 tensor | Convert first: tf.cast(a, tf.float32) |
| TypeError: Cannot convert 1.5 to EagerTensor of dtype int32 | Python float used with an int32 tensor, for example a * 1.5 | Create the tensor with floats or cast it |
| InvalidArgumentError from tf.matmul about rank or shape | Inputs are 1-D or the inner dimensions don't match | Reshape 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 tensor | Use tf.print, or return the tensor and call .numpy() outside |
tf.executing_eagerly() returns False at top level | Legacy code called disable_eager_execution() or uses TF1 sessions | Remove 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
- 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