Interview's MateData Science
Interview's Mate

Data Science

Python → ML → MLOps

Visualizer

DSA Visualizer
All 32 lessons
Custom Playground
Try your own examples

Learning

System Design
31 architecture topics
SQL Learning
160 foundations → production topics
AI Engineering
160 LLM → backend topics
Data Science
160 Python → MLOps topics
Data Engineer
160 SQL → streaming topics
Docker
160 Docker learning topics
Kubernetes
160 K8s fundamentals → cloud
Java LearnSoon
Coming soon
Python Learn
Interview Q&A & internals
JavaScript Learn
Closures, async & DOM Q&A
Tech Learn
Search, practise & track Q&A
AI DSA Practice
Solve coding problems
Theme
Home
Data Science topics
Lesson 59/ 160
03. Mathematics & Statistics

Derivatives, Partial Derivatives & Chain Rule

Compute gradients of scalar losses w.r.t. parameters - the math behind learning.

IntermediateDerivative · Partial3 quiz questions
Practice Generative AI Q&A
In plain wordsDiagramTheoryStep by stepWhen to use itInterview cluesMistakes to avoidQuiz (3)Practice

In plain words

A derivative says how much the answer changes when you nudge an input a tiny bit; the gradient collects that for every input at once.

Think of it like…

Standing on a hillside in fog: the slope under your feet (the gradient) tells you which way is uphill and how steep. With two coordinates, the partial derivatives are the slope in the east-west direction and the north-south direction, and the gradient combines them into the steepest uphill arrow.

Where you’ve seen it

A one-parameter model ŷ = w x with squared-error loss on three points x = [1, 2, 3], y = [2, 4, 7] has loss L(w) = (1/3) Σ (y − w x)². The derivative is dL/dw = −(2/3) Σ x (y − w x). At w = 1 the residuals are [1, 2, 4], so Σ x·residual = 1 + 4 + 12 = 17 and dL/dw = −(2/3) × 17 ≈ −11.3: the slope is negative, so increasing w lowers the loss. The best w solves dL/dw = 0: Σ x·y / Σ x² = (2 + 8 + 21) / 14 ≈ 2.21.

Words you’ll hear

Derivative
Instantaneous rate of change; slope of the tangent.
Partial derivative / gradient
Rate of change with respect to one variable / the vector of all of them.
Chain rule
d/dx f(g(x)) = f′(g(x)) · g′(x); gradients multiply through composed functions.
Backpropagation
Efficient application of the chain rule from the loss back through a network's layers.

Visual diagram

Loading interactive diagram

Theory & deep dive

Derivatives, partials and gradients

Basic rules: d/dx xⁿ = n xⁿ⁻¹; d/dx eˣ = eˣ; d/dx ln x = 1/x; the derivative of a sum is the sum of derivatives, and constants multiply through. For f(w) = (3w − 6)², the chain rule gives f′(w) = 2(3w − 6) · 3 = 18w − 36; at w = 1 the slope is −18, at w = 2 it is 0 (the minimum). For several parameters, hold the others fixed: if L(w₁, w₂) = (w₁ x₁ + w₂ x₂ − y)², then ∂L/∂w₁ = 2(w₁ x₁ + w₂ x₂ − y) x₁ and ∂L/∂w₂ = 2(w₁ x₁ + w₂ x₂ − y) x₂. The gradient ∇L = [∂L/∂w₁, ∂L/∂w₂] points in the direction of steepest increase; its negative is the steepest decrease.

Useful derivatives in machine learning: the sigmoid σ(z) = 1 / (1 + e⁻ᶻ) has σ′(z) = σ(z)(1 − σ(z)) (maximum 0.25), tanh′ = 1 − tanh², ReLU′ is 1 for z > 0 and 0 otherwise, and for squared error L = (y − ŷ)² the derivative with respect to the prediction is −2(y − ŷ). For logistic regression with cross-entropy loss the gradient with respect to the weights simplifies neatly to Xᵀ(ŷ − y) / n.

A numerical gradient check

f = lambda w: (3*w - 6)**2; h = 1e-5; (f(1+h) - f(1-h)) / (2*h) ≈ −18.0, matching the analytic derivative 18w − 36 at w = 1.

Key takeaway: Partial derivatives hold other variables fixed; the gradient collects them and points uphill.

The chain rule and backpropagation

For a composition y = f(g(h(x))), the derivative is the product of the local derivatives: dy/dx = f′(g(h(x))) · g′(h(x)) · h′(x). A neural network is such a composition of many layers, and backpropagation computes every parameter's gradient efficiently: run the forward pass storing intermediate values, then sweep backwards, multiplying the upstream gradient by each layer's local derivative. The cost of the backward pass is about the same as the forward pass, so training scales to millions of parameters.

Because gradients are products, they can vanish (many factors below 1, as with sigmoid's ≤ 0.25 derivative, so early layers learn slowly) or explode (many factors above 1). This motivates ReLU-family activations, careful initialisation, normalisation layers, residual connections and gradient clipping. In practice you write the forward function and let automatic differentiation do the rest (loss.backward() in PyTorch), but you should know how to verify gradients numerically, read a gradient shape (it equals the parameter's shape) and recognise when an operation is non-differentiable (rounding, argmax) and needs a surrogate.

Autograd in PyTorch

w = torch.tensor(1.0, requires_grad=True); loss = ((3*w - 6)**2); loss.backward(); w.grad returns tensor(-18.), the same as the hand-computed derivative.

Key takeaway: Gradients multiply along the computation path; vanishing and exploding gradients come from long products.

How it works, step by step

Step 1 of 4
Define

1. Write the loss as a function of parameters

Express the loss using the model's predictions and the data, with parameters as variables.

L(w) = (1/3) Σ (y − w x)²
Key numbers at this step
One
scalar loss

When to use it & trade-offs

What it is

A derivative f′(x) measures how fast a function changes at x: the slope of the tangent line, or the change in output per tiny change in input. When a loss depends on many parameters, a partial derivative ∂L/∂wⱼ measures the change per tiny change in one parameter with the others held fixed, and the vector of all partials is the gradient ∇L. The chain rule handles composite functions: d/dx f(g(x)) = f′(g(x)) · g′(x), the engine of backpropagation, which computes gradients through the layers of a neural network. Together they tell a learning algorithm which way, and how steeply, to adjust each parameter to reduce the loss.

Why it matters: Training a model means minimising a loss, and gradients say how to do it: if increasing a weight raises the loss, decrease it. You don't need to differentiate by hand in practice (autograd does it), but understanding derivatives lets you read loss functions, debug exploding or vanishing gradients, check an implementation numerically, and understand why choices like activation functions and loss scaling matter.

When to reach for it

  • Training models by gradient-based optimisation
  • Debugging vanishing or exploding gradients
  • Checking custom loss implementations

When to avoid or be careful

  • Trusting a hand-derived gradient without a numerical check
  • Using non-differentiable operations inside the loss without a surrogate
  • Deep stacks of sigmoid activations without care

Ways to get gradients

Analytic (by hand)
Best for: Simple models and understanding

Strengths: Exact; insight into structure.

Watch out: Tedious and error-prone for big models.

Automatic differentiation
Best for: Neural networks and custom losses

Strengths: Exact gradients with no manual derivation.

Watch out: Memory for stored activations; needs differentiable ops.

Numerical (finite differences)
Best for: Gradient checking

Strengths: Easy to implement.

Watch out: Slow and approximate for many parameters.

Interview signals & numbers to know

When this topic comes up

  • “Derive the gradient of the loss”
  • “What is backpropagation?”
  • “Why do gradients vanish?”
  • Chain rule questions
  • Gradient checking

Benchmarks & rules of thumb

18w − 36 -
derivative of (3w − 6)²
≤ 0.25 -
maximum derivative of the sigmoid
−11.3 -
dL/dw at w = 1 in the example

Common mistakes & follow-ups

Common interview mistakes

  • Forgetting the inner derivative in the chain rule (2(3w − 6) instead of 2(3w − 6) · 3).
  • Treating the gradient as a direction of descent rather than steepest ascent.
  • Stacking many sigmoid layers and wondering why the early layers never learn.

Likely interviewer follow-ups

  • What is a partial derivative and what does the gradient point towards?
  • Explain backpropagation using the chain rule.
  • How would you check that your gradient is correct?
Interview tip: Differentiate (3w − 6)² out loud, including the inner factor of 3. Showing the chain rule on a tiny function beats reciting its definition.

Knowledge check

Loading quiz

Put it into practice

Practice related interview Q&A

Apply Derivatives, Partial Derivatives & Chain Rule with data science interview Q&A and hands-on practice.

Open Data Science Q&A →Machine Learning Q&A
Previous topic
Eigenvalues, Eigenvectors & SVD
Next topic
Gradient Descent & Optimization Intuition