Tensors and automatic differentiation
Understanding how PyTorch computes derivatives automatically.
Goal: Writing a manual training step in TensorFlow and compiling it with tf.function.
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}")
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.
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
Understanding how PyTorch computes derivatives automatically.
Writing the training and evaluation loop by hand on synthetic data.
Composing function transformations: differentiation, vectorization and compilation.
Sections
No section has this name. Press “Search” to search all site content.
Favourites
My results & certificates
My academy progressMy quiz resultsKids’ progressAcademy certificatesQuiz certificatesStart any lesson or quiz and it will show up here so you can get back to it quickly.
Settings
I am the AI Frameworks & Libraries Assistant. Describe your project or ask me about a library, a comparison or a code example, and I will answer from the encyclopedia's database with links and sources.
Answers from the encyclopedia's database only, without a language model and without sending your question to any third party.
The assistant can make mistakes, so check the attached sources.