A custom training loop with GradientTape

MediumDeep learning and building neural networksBasics

Goal: Writing a manual training step in TensorFlow and compiling it with tf.function.

Python — example.py
import tensorflow as tf

tf.random.set_seed(0)
x = tf.random.normal((256, 1)); y = 3 * x + 2 + 0.1 * tf.random.normal((256, 1))
w, b = tf.Variable(0.0), tf.Variable(0.0)
opt = tf.keras.optimizers.SGD(0.1)

@tf.function
def step():
    with tf.GradientTape() as tape:
        loss = tf.reduce_mean((w * x + b - y) ** 2)
    opt.apply_gradients(zip(tape.gradient(loss, [w, b]), [w, b]))
    return loss

for i in range(100):
    loss = step()
print(f"w={w.numpy():.3f} b={b.numpy():.3f} loss={loss.numpy():.4f}")

Code explanation

GradientTape records operations to compute gradients, and tf.function turns the function into a faster computation graph. We fit the straight line y = 3x + 2 with noise and check that the parameters converge.

Requirements

Shell
pip install tensorflow

How to run

Save the code in a file example.py then run it:

Shell
python example.py

Output recorded during testing

w=3.003 b=1.999 loss=0.0111

This example was actually run and tested on 21 November 2026 on a CPU — tensorflow 2.21.0, python 3.13.18

Libraries used

Related examples

AdvancedJAXRun and tested

grad, vmap and jit in JAX

Composing function transformations: differentiation, vectorization and compilation.

Deep learning and building neural networks · Differentiable computing