S30 Logo
S30 AI Labwww.thes30.com
Back
#5

Calculus & Gradients

Easy📐 Math for MLW2 D2

Before You Start

Required knowledge
Algebra, functions, derivatives, and NumPy arrays.
Libraries used
NumPy
Dataset and source
Toy scalar/vector functions and numeric inputs defined in the notebook.
Expected output
Analytic and finite-difference gradient comparisons and a numerical Hessian.

Calculus & Gradients — Theory & Concepts

Read this before attempting the exercises. Gradients are how ML models learn. Every optimization algorithm (SGD, Adam, etc.) relies on computing gradients.


1. Derivatives — The Core Idea

A derivative measures how fast a function changes as its input changes.

f(x) = x²
f'(x) = 2x      < slope at any point

At x=3: f'(3) = 6  > function is increasing, slope = 6
At x=0: f'(0) = 0  > function is flat (minimum!)

ML Connection: We want to find the minimum of the loss function. The gradient tells us which direction to move.

Derivative as tangent slope


2. Partial Derivatives & Gradients

For functions of multiple variables, the gradient is the vector of all partial derivatives:

f(w₁, w₂) = w₁² + 3w₂²

∂f/∂w₁ = 2w₁
∂f/∂w₂ = 6w₂

∇f = [2w₁, 6w₂]    < gradient vector

The gradient points in the direction of steepest ascent. To minimize, go in the opposite direction.

Gradient on contour map


3. Chain Rule — Backbone of Backpropagation

If y = f(g(x)), then:

dy/dx = (dy/dg) x (dg/dx)

Example: Neural network layer

z = Wx + b          (linear)
a = σ(z)            (activation)
L = loss(a, y)      (loss)

∂L/∂W = (∂L/∂a) x (∂a/∂z) x (∂z/∂W)
       = (∂L/∂a) x σ'(z) x x

This is exactly what backpropagation computes — chain rule applied layer by layer.

Chain rule backprop flow


4. Gradient Descent

# Basic gradient descent
w = initial_weights
for step in range(n_steps):
    grad = compute_gradient(loss, w, X, y)
    w = w - learning_rate * grad
Loss landscape:
    \         /
     \       /
      \     /
       \   /
        \ /  < minimum (gradient = 0)

Variants:

VariantBatch SizeProsCons
Batch GDAll dataStableSlow, needs all data in memory
SGD1 sampleFast, onlineNoisy
Mini-batch SGD32-512Best of bothStandard in practice

Gradient descent trajectory and learning rate


5. Numerical Gradient Check

Always verify your analytical gradient with a numerical approximation:

def numerical_gradient(f, x, eps=1e-5):
    grad = np.zeros_like(x)
    for i in range(len(x)):
        x_plus = x.copy(); x_plus[i] += eps
        x_minus = x.copy(); x_minus[i] -= eps
        grad[i] = (f(x_plus) - f(x_minus)) / (2 * eps)
    return grad

# Check: relative error should be < 1e-5
rel_error = np.linalg.norm(analytical - numerical) / (np.linalg.norm(analytical) + 1e-8)

FAANG Interview Tip: If asked "how do you verify your gradient implementation?", this is the answer. Two-sided finite differences are more accurate than one-sided.

Finite difference gradient check


6. Common Derivatives for ML

FunctionDerivativeWhere Used
x²2xL2 loss
x
eˣeˣSoftmax
log(x)1/xCross-entropy
σ(x) = 1/(1+e⁻ˣ)σ(x)(1-σ(x))Logistic regression
ReLU(x) = max(0,x)1 if x>0, 0 if x<0Neural networks
tanh(x)1 - tanh²(x)RNNs

7. Jacobians & Hessians

  • ●Jacobian — matrix of all first-order partial derivatives (for vector-valued functions)
  • ●Hessian — matrix of all second-order partial derivatives (curvature information)
Hessian of f(w₁, w₂):
H = + ∂²f/∂w₁²    ∂²f/∂w₁∂w₂ +
    + ∂²f/∂w₂∂w₁  ∂²f/∂w₂²   +

ML Use: Newton's method uses the Hessian for faster convergence: w ← w - H⁻¹∇f. Too expensive for large models, but the concept matters for interviews.

Jacobian vs Hessian intuition


Now you're ready to attempt the exercises. Switch to the Exercise tab and start coding!

Ready to practice?

Python 3 — Notebook
0/5 solvedSubstack Notes
1
Dataset & Setup

Calculus & Gradients — FAANG-Level Lab

Goal: Implement and verify gradients like an ML engineer.

Key idea: If you can’t gradient-check it, you don’t really trust it.

Loading editor...
1

Finite Differences (Gradient Checking)

2
Implement numerical gradient for scalar f(w)
1

Section 1 — Finite Differences (Gradient Checking)

Task 1.1: Implement numerical gradient for scalar f(w)

  • ●Use central difference: (f(w+eps e_i) - f(w-eps e_i)) / (2 eps)

Explain: Why is central difference more accurate than forward difference?

Explain: Why is central difference more accurate than forward difference?
Loading editor...
2

Chain Rule in Code

3
Gradient of MSE for linear model
1

Section 2 — Chain Rule in Code

Task 2.1: Gradient of MSE for linear model

Model: y_hat = Xw Loss: L(w) = (1/n) * sum_i (y_hat_i - y_i)^2

  • ●Let r = Xw - y
  • ●grad = (2/n) * X^T r

FAANG gotcha: shape mismatches; keep w as (d,) and X as (n,d).

Loading editor...
3

Logistic Regression (Core Interview Gradient)

4
Binary cross-entropy gradient
1

Section 3 — Logistic Regression (Core Interview Gradient)

Task 3.1: Binary cross-entropy gradient

Given labels y in {0,1}. p = sigmoid(Xw) Loss = -(1/n) * sum(y log p + (1-y) log(1-p))

  • ●sigmoid(z)=1/(1+exp(-z))
  • ●grad = (1/n) * X^T (p - y)
  • ●add numerical stability for logs (clip p)
Loading editor...
4

Jacobian/Hessian Intuition

5
Compute Hessian of f(w)=sum(w^2) numerically
2

Section 4 — Jacobian/Hessian Intuition

Task 4.1: Compute Hessian of f(w)=sum(w^2) numerically

Hessian matrix formula with second partial derivatives

  • ●Hessian of sum(w^2) is 2I
  • ●Use numerical_grad on each component of grad

This is mainly about shape thinking: Hessian is (d,d).

Loading editor...

Need help? Share feedback