smartyfy.mrindigi.com

AI & Machine Learning Master Course — 103. Backpropagation step by step

Smartyfy AI & Machine Learning Master Course

Course ID: smartyfy-ai-ml-master-200

Lesson 103: Backpropagation step by step

Prerequisites: Lesson 102. Learning outcome: Derive and verify gradients in a small neural network.

Backpropagation is organized chain-rule calculation

Backpropagation computes derivatives of a scalar loss with respect to many parameters by reusing intermediate derivatives along a computation graph. It does not search for a good architecture or choose a learning rate. It answers a local question: how would a small parameter change affect the current loss?

Consider one hidden tanh unit followed by a scalar linear output. Define z = wx+b, h = tanh(z), prediction = vh+c, and loss = one half times (prediction−target) squared. The one-half convention makes the derivative with respect to prediction equal to the residual, rather than twice the residual.

A forward pass calculates z, h, prediction, and loss. A backward pass propagates sensitivities in the reverse dependency order. Saving h avoids recomputing tanh when using its derivative 1−h². Larger networks use the same principle with matrix-shaped derivatives.

Derive every local factor

Let e = prediction−target. The output-layer derivatives are dL/dv = e h and dL/dc = e. The sensitivity arriving at the hidden activation is dL/dh = e v. Passing through tanh gives dL/dz = e v (1−h²).

Finally, z depends on w through x and on b through one. Therefore dL/dw = e v (1−h²)x and dL/db = e v (1−h²). Each derivative is a product of the local factors along its path from parameter to loss.

If a parameter contributes through several paths, add the path contributions. Reusing a weight across observations also requires accumulating its contributions across the batch. Whether the loss is summed or averaged determines the final scaling. A missing factor of batch size can silently change the effective learning rate.

Put numbers on the graph

Use x=2, target=0.8, w=0.3, b=−0.1, v=1.2, and c=0.2. Then z=0.5 and h is approximately 0.462117. Prediction is approximately 0.754541, so the residual is −0.045459 and loss is approximately 0.00103328.

The four derivatives in order w,b,v,c are approximately −0.085803, −0.042902, −0.021008, and −0.045459. The w derivative is twice the b derivative because x=2. This is a useful internal consistency check independent of numerical finite differences.

A gradient-descent step subtracts learning rate times the gradient. With rate 0.1, the negative derivatives increase these parameters. The recomputed loss is approximately 0.00019732, lower in this particular small step. A larger step need not reduce loss, because the derivative describes local sensitivity rather than a global guarantee.

Forward nodes display z 0.5, tanh z 0.462117, output 0.754541 and half-squared loss 0.00103328. Reverse arrows carry local loss sensitivities and the parameter gradient.
Backpropagation multiplies local derivatives while moving backward through the graph. Open full-size diagram

CPU lab: compare analytical and numerical derivatives

The NumPy example computes the analytical gradient, then perturbs each parameter by plus and minus 0.000001. The central-difference approximation is [L(p+epsilon)−L(p−epsilon)]/(2epsilon). All four numerical derivatives agree within the stated tolerances.

This code ran on CPU with NumPy 2.3.5. It also recomputes loss after the small update. No PyTorch execution is claimed. The linked gradient-check documentation provides framework context, while the example verifies the calculus directly with available numerical tools.

import numpy as np
p = np.array([.3, -.1, 1.2, .2])  # w, b, v, c
x, target = 2., .8
def loss(p):
    w, b, v, c = p
    return .5 * (v * np.tanh(w * x + b) + c - target) ** 2
w, b, v, c = p
h = np.tanh(w * x + b); error = v * h + c - target
dz = error * v * (1 - h * h)
analytic = np.array([dz * x, dz, error * h, error])
eps = 1e-6; numerical = np.empty(4)
for j in range(4):
    step = np.zeros(4); step[j] = eps
    numerical[j] = (loss(p + step) - loss(p - step)) / (2 * eps)
print('prediction', round(error + target, 6), 'loss', round(loss(p), 8))
print('analytic gradient', np.round(analytic, 6))
print('numerical gradient', np.round(numerical, 6))
assert np.allclose(analytic, numerical, atol=1e-8, rtol=1e-6)
print('loss after step', round(loss(p - .1 * analytic), 8))

Understand what a gradient check can and cannot prove

Finite differences are an independent approximation to local derivatives, useful for checking a hand-written backward pass. Epsilon must balance truncation error against floating-point cancellation. Double precision and moderate parameter magnitudes make small educational checks easier to interpret.

Avoid checking at nondifferentiable points such as a ReLU kink if you expect an ordinary derivative to match a central difference. Stochastic dropout, changing batches, or stateful normalization can also change the function between evaluations. Freeze randomness and state or disable those components while checking the intended deterministic function.

A passing check at one point does not prove the entire training system correct. Indexing errors may appear only for other shapes; loss-label mismatch may produce a perfectly differentiated wrong objective. Test several small inputs and shapes, then inspect training behavior and data semantics separately.

From one observation to a batch

For a mean loss over n observations, sum their parameter-gradient contributions and divide by n. The derivative has the same shape as its parameter: a matrix weight receives a matrix gradient, and a bias vector receives a vector gradient. Shape assertions can catch accidental reductions or broadcasts.

Compute all gradients using the same parameter state before applying updates. Updating v and then using the new v to calculate the hidden gradient would mix two different computation graphs. Store the gradients first, or use an automatic differentiation system that tracks the forward computation consistently.

Gradient descent follows the negative gradient because the first-order change is approximately the gradient dot the parameter step. Choosing step equal to minus eta times gradient yields approximately minus eta times squared gradient norm. This explains a sufficiently small local descent direction, while curvature and numerical effects limit the approximation.

Four practice questions with worked answers

Practice 1

For half-squared error with prediction 3 and target 1, what is dL/dprediction?

Answer: The residual is 3−1=2, so the derivative is 2. Without the one-half factor in the loss, it would be 4.

Practice 2

Why is the demonstrated w gradient twice the b gradient?

Answer: Both share the factor dL/dz. Since dz/dw=x=2 and dz/db=1, their ratio is two for this observation.

Practice 3

What happens if a mean batch loss accidentally uses a summed gradient?

Answer: The gradient is larger by the batch size relative to the intended mean objective. This effectively scales the update and can destabilize an otherwise reasonable learning rate.

Practice 4

Why should all gradients be computed before updating any parameters?

Answer: Every derivative should refer to the same forward-pass parameter values. Updating one weight early and using it in another derivative mixes states and no longer computes the gradient of the recorded loss.

Five multiple-choice questions

Question 1

What mathematical rule underlies backpropagation?

  • A. A guarantee that every update lowers test error
  • B. The chain rule with accumulated path contributions
  • C. A search over all possible parameter values

Correct: B. It efficiently organizes local derivative calculations.

Question 2

What is d tanh(z)/dz in terms of h=tanh(z)?

  • A. h times (1−h)
  • B. One for every z
  • C. 1−h²

Correct: C. The tanh derivative is 1−h². The distractor h(1−h) instead describes the sigmoid derivative when h is the sigmoid output.

Question 3

Why use central finite differences?

  • A. To prove global optimality
  • B. To independently approximate a local derivative
  • C. To avoid evaluating the loss at perturbed parameters

Correct: B. Perturbed loss evaluations provide a numerical check of analytical gradients.

Question 4

What can break a straightforward finite-difference comparison?

  • A. Using the same fixed data on both perturbations
  • B. Matching gradient and parameter shapes
  • C. Randomness or a nondifferentiable evaluation point

Correct: C. The comparison assumes a stable, suitably differentiable local function.

Question 5

Does a passing gradient check prove the labels are correct?

  • A. No, a wrong objective can still be differentiated correctly
  • B. Yes, derivatives validate the dataset semantics
  • C. Only when the loss is small

Correct: A. Calculus correctness and data correctness are separate audits.

Common pitfalls

Avoid missing loss-scaling factors, updating parameters before all derivatives are ready, or checking stochastic functions without controlling randomness. A derivative check is local and numerical; combine it with shape, data, and training diagnostics.

Summary

Backpropagation applies the chain rule in reverse dependency order and accumulates shared contributions. A tiny analytical example plus central finite differences makes both the arithmetic and its limits visible.

Primary sources and further reading