Maths for Machines
0 of 5 lessons done100 questions

Lesson 1 of 5

Prediction, loss, gradients, and optimization

A model makes a prediction, a loss grades it, and gradients tell every parameter how a tiny change would affect that grade.

Core lesson · about 5 minutes · 3 guided parts

A student throws a ball, measures the miss, then changes direction a little. Repeated feedback slowly improves the throw.

Your learning route

Build the idea one piece at a time

  1. From regression to logits and cross-entropy
  2. Backpropagation and gradient updates
  3. Follow one gradient through a tiny classifier
Prediction, loss, gradients, and optimization, made visible
adjust parameters to reduce error

From regression to logits and cross-entropy

Linear regression predicts a number, logistic regression predicts a binary probability, and softmax extends the same score-to-probability idea to many classes.

Linear regression uses ŷ=wᵀx+b and commonly fits squared error. Logistic regression feeds the score through σ(z)=1/(1+e⁻ᶻ), then uses binary cross-entropy; both are simple models that reveal the full prediction-loss-gradient loop.

For logits z, softmax assigns pᵢ=exp(zᵢ) ÷ Σⱼexp(zⱼ); subtract max(z) before exponentiating for numerical stability.

For a one-hot target y, loss L=−Σᵢyᵢ log pᵢ=−log p(correct class).

Cross-entropy is justified as negative log-likelihood for a categorical observation; label noise and distribution shift still matter.

A model first converts input features into raw scores. Logistic sigmoid handles two classes; softmax exponentiates and normalizes many logits so their probabilities are nonnegative and total one.

Cross-entropy reads the probability assigned to the correct answer. A wrong but uncertain forecast receives moderate loss, while a wrong forecast made with near-certainty receives a large loss, which pushes training to correct confident errors.

Subtracting the largest logit before exponentiation leaves all softmax ratios unchanged because the same constant cancels. It prevents enormous exponentials and is therefore a mathematical equivalence with better numerical behavior.

In symbolspᵢ=softmax(z)ᵢ; L=−Σᵢ yᵢ log pᵢ

Worked example

Two logits are ln 3 and 0. What probability does softmax assign to the first class, and what is the loss if it is correct?

  1. Exponentials are 3 and 1, totaling 4.
  2. The first-class probability is 3/4.
  3. Its loss is −ln(3/4)≈0.2877.

Answer: Probability 0.75; loss ≈0.2877 nats

Backpropagation and gradient updates

The chain rule passes responsibility backward through every operation used in the forward prediction.

A computational graph stores intermediate values, then reverse-mode automatic differentiation accumulates vector–Jacobian products.

Gradient descent updates θ←θ−η∇L; η is the learning rate, and stochastic mini-batches give noisy gradient estimates.

Gradients can vanish or explode through many multiplications; initialization, residual paths, normalization, and clipping help in different ways.

Backpropagation applies the chain rule from the loss toward earlier operations. Each parameter receives a derivative measuring how an extremely small increase would change the current batch loss.

Gradient descent moves in the negative-gradient direction because the gradient points toward local increase. The learning rate decides how far to trust that local linear picture before recomputing at a new point.

Mini-batches replace the full-data gradient with a noisy estimate that is much cheaper to compute. Shuffling, optimizer state, clipping, and schedules control this noise and scale, but held-out evaluation is still needed to detect overfitting.

In symbolsθₜ₊₁=θₜ−η∇θL(θₜ)

Worked example

A parameter is θ=4, its gradient is 1.5, and learning rate is 0.2. Perform one gradient-descent step.

  1. Scale the gradient: 0.2×1.5=0.3.
  2. Move opposite the gradient.
  3. θ(new)=4−0.3=3.7.

Answer: 3.7

Practical deep dive for this lesson

Follow one gradient through a tiny classifier

A concrete forward and backward pass shows how prediction error becomes a parameter update instead of remaining an abstract arrow.

For binary logistic regression, compute z=wx+b, p=sigmoid(z), and loss from the true label y. The derivative with respect to z simplifies to p−y.

The chain rule gives dL/dw=(p−y)x and dL/db=p−y. The feature value scales how strongly this example moves its weight, while the sign says which direction increases the correct-class probability.

A batch averages such contributions before the optimizer updates. Feature scaling, regularization, and learning rate alter training dynamics, so gradient arithmetic should be checked on a tiny hand-calculated case.

In symbolsbinary logistic: ∂L/∂w=(p−y)x

Worked example

For x=2, y=1, current p=0.75, w=1, and learning rate 0.1, perform one plain-gradient update of w.

  1. Compute p−y=0.75−1=−0.25.
  2. Multiply by x: dL/dw=−0.25×2=−0.5.
  3. Apply w(new)=w−η×gradient=1−0.1(−0.5).
  4. Obtain w(new)=1.05; the increase raises z for this positive example.

Answer: w(new)=1.05

Check your picture

For softmax cross-entropy, what is ∂L/∂zᵢ for one-hot target y?

Reveal answer

pᵢ−yᵢ

This lesson versus the whole chapter

Your topic-specific practical example is above.

The final lesson collects five longer chapter-wide workflows for machine learning, LLMs, trading, physics, and everyday decisions.

Formula shelf

Symbols with meaning

Linear regressionŷ=wᵀx+b

Predict a numeric target with a weighted feature sum.

Logistic probabilityp=σ(wᵀx+b)

Turn a binary-class score into a probability.

Softmaxpᵢ=exp(zᵢ) ÷ Σⱼexp(zⱼ)

Turn logits into categorical probabilities.

Cross-entropy lossL=−Σᵢ yᵢ log pᵢ

Negative log probability assigned to the target.

Gradient updateθ←θ−η∇L

Move parameters locally downhill.

Cosine similarityaᵀb/(||a||||b||)

Compare embedding direction without magnitude.

Scaled attentionsoftmax(QKᵀ/√dₖ)V

Mix values according to normalized query-key matches.

Layer normalizationγ⊙(x−μ)/√(σ²+ε)+β

Normalize feature scale per example or token.

Residual blocky=x+F(x)

Learn a correction while preserving a direct path.

Temperature samplingpᵢ(T)=softmax(zᵢ/T)

Control distribution sharpness before sampling.

Before moving on

You are ready when you can…

  • Connect linear and logistic regression to logits, softmax, cross-entropy, gradients, and updates
  • Explain learned embeddings and similarity choices
  • Compute scaled dot-product attention with masks
  • Explain layer normalization and residual gradient paths
  • Use temperature and truncation sampling, and audit an end-to-end LLM evaluation