Module 5 — Linear Regression, Logistic Regression, Softmax

Sources: Lec 10 — Linear Regression; Lec 11 — Logistic Regression. · Prev: Module 4 · Next: Module 6 — SVM · Index: 00_INDEX_and_Coverage


C26. Linear Regression and Least Squares

Intuition

Draw the straight line (or plane) that passes as close as possible to the data, where “close” means the sum of squared vertical gaps is smallest. “Linear” refers to the parameters, not necessarily to the inputs: is allowed.

  y
  |            ●        ← each vertical gap e_i = y_i − ŷ_i is a residual
  |         ┆ ╱
  |      ● ─┆╱─ ŷ = β0 + β1 x   (line minimises Σ e_i²)
  |     ╱┆
  |   ╱ ●
  +----------------→ x

Formal definition

Model: (one regressor), or for : Given , , the sum of squared errors where is the matrix with rows and .

Derivation of the normal equations

Expand: . Using and for symmetric : Set to zero: , so (when is invertible) The Hessian is , so the stationary point is a minimum (unique if has full column rank).

Key insights

  • Residuals are orthogonal to every column of : . In particular, residuals sum to zero (the intercept column).
  • If columns of are linearly dependent (duplicate / collinear features, or ), is singular and the solution is not unique.
  • Basis expansions (polynomials, interactions) keep the model linear in .

Worked examples

Example 1 — Very Easy · Advertising and sales

  • Problem: A shop spends (₹ lakh) on ads and sees sales (₹ lakh). Fit .
  • Asked: .
  • Concept: Normal equations.
  • Approach: Build and .
  • Solution: , . , . , inverse . .
  • Final answer: .

Key lesson

The slope equals : every extra ₹ 1 lakh of ads adds ₹ 1.5 lakh of sales.

Example 2 — Easy · Residuals and SSE

  • Problem: For Example 1, compute fitted values, residuals and SSE.
  • Asked: .
  • Concept: Residuals.
  • Approach: Plug in.
  • Solution: . . .
  • Final answer: .

Key lesson

Residuals sum to .

Example 3 — Moderate · Orthogonality of residuals

  • Problem: Verify the orthogonality conditions for Example 2 and explain what they say.
  • Asked: Check.
  • Concept: Normal equations as orthogonality.
  • Approach: Dot products.
  • Solution: Column of ones: ✓. Column : ✓.
  • Final answer: .

Key lesson

The fitted vector is the orthogonal projection of onto the column space of .

Example 4 — Hard · Line vs quadratic

  • Problem: A sensor’s error depends on the distance from its calibration point . Data . Compare the best straight line with the quadratic .
  • Asked: SSE of both.
  • Concept: Basis expansion (linear in parameters).
  • Approach: Line via ; quadratic by inspection and normal equations.
  • Solution: Line: , . ; . , . : residuals , SSE . Quadratic: try : values ✓ exact. This is a feasible point with and , so it is the minimiser: , SSE .
  • Final answer: Line SSE ; quadratic SSE with .

Key lesson

Adding as a feature keeps the problem linear and can remove the model’s bias.

Example 5 — Very Hard · Collinear features

  • Problem: Features and with intercept. (a) Show is singular. (b) Describe all least-squares solutions. (c) Why are predictions still unique?
  • Asked: Singularity and solution set.
  • Concept: Collinearity.
  • Approach: Dependent columns.
  • Solution: (a) ; colcol. with rowrow ⇒ . (b) The model is . Only and are determined (from Example 1: , ). Solutions: for any . (c) All give the same , hence the same fitted values and SSE .
  • Final answer: Infinite family; predictions identical.

Key lesson

Collinear features make coefficients meaningless though predictions are fine. Cures: drop a feature, regularise, or use the pseudo-inverse (which picks the minimum-norm solution ).

Common mistakes

  • Forgetting the column of ones.
  • Inverting when .

Exam traps

  • “Linear regression” = linear in the parameters.
  • The normal equations require invertible.

Connections: Logistic regression (C27), PCA reconstruction error (C45), perceptron’s squared-error variant (C49 / C51).

Mastery checklist

  • Derive .
  • Fit a line by hand.
  • Explain collinearity.

C27. Binomial Logistic Regression

Intuition

Regression on a 0/1 target produces nonsense (predictions outside ). Instead model the probability of class 1 with an S-shaped function of a linear score. The score is a distance-like quantity from a hyperplane; probability sits exactly on it.

 σ(z)
 1.0 |                 ________
     |              _/
 0.5 |- - - - - - -●        ← z = 0: on the boundary, p = 0.5
     |          __/
 0.0 |________/
     +--------------------→ z = β0 + βᵀX

Formal definition

Decision: class 1 iff . The decision boundary is a hyperplane.

Derivation: likelihood → cross-entropy → gradient

Labels , . Bernoulli likelihood: . Log-likelihood per sample: . Loss (negative, = cross-entropy): Substitute : and . Then Differentiate: (with ). Hence No closed-form solution; solve by gradient descent or Newton’s method. is convex in (its Hessian is ), so there is no spurious local minimum.

Key insights

  • Sigmoid derivative: .
  • The boundary is linear because it is .
  • (Lecture slip: “the loss is linear in ” is inaccurate — the boundary is linear; the loss is convex, not linear.)

Worked examples

Example 1 — Very Easy · The sigmoid

  • Problem: for .
  • Asked: Three probabilities.
  • Concept: Sigmoid.
  • Approach: .
  • Solution: ; ; .
  • Final answer: .

Key lesson

.

Example 2 — Easy · Pass probability vs study hours

  • Problem: A model for passing an exam uses ( = hours studied). Find the boundary and at and .
  • Asked: Boundary and probabilities.
  • Concept: boundary.
  • Approach: Solve .
  • Solution: Boundary hours. : ⇒ . : ⇒ .
  • Final answer: Boundary ; probabilities and .

Key lesson

Distance from the boundary controls confidence.

Example 3 — Moderate · Cross-entropy

  • Problem: Predicted probabilities of class 1 are for labels . Compute the total and average cross-entropy.
  • Asked: .
  • Concept: Cross-entropy.
  • Approach: for the true class.
  • Solution: Sample 1: . Sample 2 (): . Sample 3: . Total ; mean .
  • Final answer: (mean ).

Key lesson

The loss only looks at the probability assigned to the true class.

Example 4 — Hard · One gradient step on pass/fail data

  • Problem: Hours studied vs pass: . Start at . Do one gradient-descent step with and compare the loss before and after.
  • Asked: New and loss.
  • Concept: Gradient formula.
  • Approach: at the start.
  • Solution: for all. . . Update: . Loss before: . After: ; (decrease of ).
  • Final answer: ; loss .

Key lesson

A positive slope emerges because larger go with .

Example 5 — Very Hard · Perfectly separable data

  • Problem: Two points , model (no intercept). Show the loss has no minimiser and explain.
  • Asked: Behaviour of .
  • Concept: Separable data ⇒ MLE does not exist.
  • Approach: Write the loss.
  • Solution: At : . At : . : : ; : ; : ; as but for every finite .
  • Final answer: The infimum is never attained: .

Key lesson

On linearly separable data, unregularised logistic regression pushes the weights to infinity; use regularisation or early stopping.

Common mistakes

  • Using labels with the formulas.
  • Sign errors in the gradient ().

Exam traps

  • Threshold ⇔ .
  • The model is a classifier despite “regression” in its name.

Connections: C26, C28 (softmax), C29, perceptron (C49), SVM (C30).

Mastery checklist

  • Derive cross-entropy from the Bernoulli likelihood.
  • Derive .
  • Explain why the boundary is linear.

C28. Multinomial Logistic Regression and Softmax

Intuition

With classes keep one score per class and turn the scores into probabilities that sum to 1 by exponentiating and normalising.

Formal definition

Labels are one-hot vectors . Per-sample loss with true class : The parameters form a matrix (the lecture writes without the bias).

Derivation of the gradient w.r.t. scores

. Then . ∎ (Same shape as the binary gradient .)

Key insights

  • Binary logistic regression = softmax with 2 classes (Example 3).
  • Softmax is shift-invariant: .
  • Predicted class = (equivalently of the scores).

Worked examples

Example 1 — Very Easy · Softmax of three scores

  • Problem: Softmax of .
  • Asked: Probabilities.
  • Concept: Softmax.
  • Approach: Exponentiate, normalise.
  • Solution: ; sum . Probabilities: .
  • Final answer: .

Key lesson

Outputs lie in and sum to 1.

Example 2 — Easy · Cross-entropy

  • Problem: The true class is the second. Cross-entropy for Example 1?
  • Asked: .
  • Concept: .
  • Approach: Pick the true class.
  • Solution: .
  • Final answer: .

Key lesson

Other classes’ probabilities matter only through the normalisation.

Example 3 — Moderate · Softmax contains the sigmoid

  • Problem: Show that softmax over equals the binary logistic probabilities.
  • Asked: Equivalence.
  • Concept: Softmax generalises the sigmoid.
  • Approach: Write .
  • Solution: and .
  • Final answer: Identical to the binary formulas of C27.

Key lesson

Binary logistic is the case with one score set to (using shift invariance).

Example 4 — Hard · Overflow-safe softmax

  • Problem: Scores . Direct overflows. Compute softmax stably.
  • Asked: Probabilities.
  • Concept: Shift invariance.
  • Approach: Subtract the max.
  • Solution: . ; sum . Probabilities: — identical to Example 1 (the scores differ by the same offsets).
  • Final answer: .

Key lesson

Always subtract before exponentiating.

Example 5 — Very Hard · The gradient on the scores

  • Problem: For Example 1 with the true class second, write and verify it sums to zero. Then explain the gradient step’s effect on each score.
  • Asked: Gradient vector and interpretation.
  • Concept: .
  • Approach: with .
  • Solution: . Sum ✓ (both and sum to 1). A descent step lowers (wrong classes, positive gradient) and raises (true class, negative gradient) — the push is proportional to the error.
  • Final answer: Gradient .

Key lesson

The sum-to-zero property reflects shift invariance: there is one redundant degree of freedom among the scores.

Common mistakes

  • Using the sigmoid for each class independently (probabilities then do not sum to 1).
  • Forgetting the log-sum-exp stabilisation.

Exam traps

  • One-hot encoding of labels.
  • Loss of the probability of the correct class.

Connections: C27, C29, neural-network output layers (C53–C54).

Mastery checklist

  • Compute softmax and its cross-entropy.
  • Derive .
  • Use the max-subtraction trick.

C29. Discriminative vs Generative Classifiers

Intuition

Generative (e.g. Naive Bayes, Gaussian discriminant analysis): learn what each class looks like, , then invert with Bayes. Discriminative (e.g. logistic regression, SVM, perceptron): learn the boundary or directly, without modelling . Lecture example: all dogs in training wear collars, no cat does. A discriminative model happily uses the collar; a generative model tries to learn what dogs and cats actually look like.

flowchart LR
    subgraph Generative
      A["learn p(X | w) and p(w)"] --> B["Bayes rule"] --> C["p(w | X)"]
    end
    subgraph Discriminative
      D["learn p(w | X) or the boundary directly"] --> E["p(w | X)"]
    end

Formal comparison

GenerativeDiscriminative
Models or boundary
Predicts viaBayes’ ruledirect
Can sample ?YesNo
ExamplesNaive Bayes, LDALogistic, SVM, perceptron

Mathematical bridge

For two Gaussian classes with a shared covariance, the generative posterior is a logistic function: with (C18). So the two families coincide in form; they differ in how the parameters are fitted (joint likelihood vs conditional likelihood) and in robustness to model misspecification.

Worked examples

Example 1 — Very Easy · Label the algorithm

  • Problem: Classify as generative or discriminative: Naive Bayes, logistic regression, SVM, perceptron, Gaussian discriminant analysis.
  • Asked: Label each.
  • Concept: Taxonomy.
  • Approach: Does it model ?
  • Solution: NB — generative; logistic — discriminative; SVM — discriminative; perceptron — discriminative; Gaussian discriminant analysis — generative.
  • Final answer: As stated.

Key lesson

The lecture’s contrast: logistic regression vs Naive Bayes.

Example 2 — Easy · The dog without a collar

  • Problem: In the dog / cat story a new dog without a collar arrives. What does a collar-based discriminative model say? What might a generative model say?
  • Asked: Predictions and reason.
  • Concept: Shortcut learning.
  • Approach: Think about what each model learned.
  • Solution: Discriminative: the only learned separator is “collar ⇒ dog”, so no collar ⇒ cat (wrong). Generative: it has modelled dog shape, ears, tail, etc.; stays high ⇒ likely dog.
  • Final answer: Discriminative errs; generative may be right.

Key lesson

Discriminative models exploit whatever separates the training classes, even spurious cues.

Example 3 — Moderate · Posterior from a generative model

  • Problem: Two Gaussian classes , , , equal priors. Compute at .
  • Asked: Posterior.
  • Concept: The generative posterior is logistic.
  • Approach: (C18 Ex. 1).
  • Solution: . .
  • Final answer: .

Key lesson

Gaussian generative model ⇒ logistic posterior.

Example 4 — Hard · Prove the logistic form

  • Problem: Prove with .
  • Asked: Algebra.
  • Concept: Bayes in log-odds form.
  • Approach: Divide numerator and denominator by .
  • Solution: . ∎ For equal-covariance Gaussians is the linear discriminant of C18.
  • Final answer: As shown.

Key lesson

The log-odds of the posterior equal the discriminant function.

Example 5 — Very Hard · Duplicate feature: NB vs logistic

  • Problem: A binary feature with , , equal priors, appears twice (duplicate column). Compare Naive Bayes (generative) and logistic regression (discriminative) posteriors for an instance with .
  • Asked: Two posteriors.
  • Concept: Calibration under redundancy.
  • Approach: Log-odds.
  • Solution: Truth: , log-odds . NB: each copy adds ⇒ ⇒ . Logistic regression fitted by maximum conditional likelihood: ; the likelihood depends only on and is maximised at ⇒ posterior .
  • Final answer: NB ; logistic (correct).

Key lesson

Discriminative training adjusts weights to the joint evidence and is robust to correlated features; NB double-counts. (Both still pick .)

Common mistakes

  • Believing generative models are always more accurate.
  • Believing discriminative models cannot give probabilities.

Exam traps

  • “Logistic regression is discriminative; Naive Bayes is generative” (lecture).
  • A generative classifier can create synthetic data; a discriminative one cannot.

Connections: C14, C18–C22, C27.

Mastery checklist

  • Give the definition and an example of each.
  • Derive the logistic form of the Gaussian posterior.
  • Explain the collar example.