Module 5 — Linear Regression, Logistic Regression, Softmax
Sources: Lec 10 — Linear Regression; Lec 11 — Logistic Regression.
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.
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
- Problem: Fit to .
- Asked: .
- Concept: Normal equations.
- Approach: Build and .
- Solution: , . , . , inverse . .
- Final answer: .
- Key lesson: The slope equals .
Example 2 — Easy
- 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
- 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
- Problem: 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. Since this is a feasible point with and , it is the minimiser: , SSE .
- Final answer: Line SSE ; quadratic SSE with .
- Key lesson: Adding as a feature keeps the problem linear and can fix the model’s bias.
Example 5 — Very Hard
- 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 (by 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 (cure: drop a feature, regularise, or use a pseudo-inverse).
Common mistakes
- Forgetting the column of ones.
- Inverting when .
Exam traps
- “Linear regression” = linear in parameters.
- 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.
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: .
- 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
- Problem: for .
- Asked: Three probabilities.
- Concept: Sigmoid.
- Approach: .
- Solution: ; ; .
- Final answer: .
- Key lesson: .
Example 2 — Easy
- Problem: 1-D model . Find the boundary and , .
- Asked: Boundary and probabilities.
- Concept: boundary.
- Approach: Solve .
- Solution: Boundary . : ⇒ . : ⇒ .
- Final answer: Boundary ; probabilities and .
- Key lesson: Distance from the boundary controls confidence.
Example 3 — Moderate
- 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: Loss only looks at the probability assigned to the true class.
Example 4 — Hard
- Problem: Data : . Start at . Do one gradient-descent step with and compare the loss before and after.
- Asked: New and loss.
- Concept: Gradient formula.
- Approach: at start.
- Solution: for all. . . Update: . Loss before: . After: ; (decreased by 0.331).
- Final answer: ; loss .
- Key lesson: Positive slope emerges because larger go with .
Example 5 — Very Hard
- 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
- 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
- Problem: 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
- Problem: Show that softmax over equals the binary logistic probabilities.
- Asked: Equivalence.
- Concept: Softmax generalises sigmoid.
- Approach: Write .
- Solution: and .
- Final answer: Identical to equations (11.1).
- Key lesson: Binary logistic is the case with one score set to (using shift invariance).
Example 4 — Hard
- Problem: Scores . Direct overflows. Compute softmax stably.
- Asked: Probabilities.
- Concept: Shift invariance.
- Approach: Subtract the max.
- Solution: . ; sum . Probabilities: — identical to Example 1 (since the scores differ by the same offsets).
- Final answer: .
- Key lesson: Always subtract before exponentiating.
Example 5 — Very Hard
- 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 ✓ (because both and sum to 1). A descent step lowers (wrong classes, positive gradient) and raises (true class, negative gradient) — with the push 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; ask it what it knows about cats and “they don’t wear collars”. A generative model tries to learn what dogs and cats actually look like.
Formal comparison
| Generative | Discriminative | |
|---|---|---|
| Models | $p(\vec X | w),,p(w)$ |
| Predicts via | Bayes’ rule | direct |
| Can sample ? | Yes | No |
| Examples | Naive Bayes, LDA | Logistic, 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
- 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 vs NB.
Example 2 — Easy
- 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: 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
- Problem: Two Gaussian classes , , , equal priors. Compute at .
- Asked: Posterior.
- Concept: Generative posterior is logistic.
- Approach: (C18 Ex. 1).
- Solution: . .
- Final answer: .
- Key lesson: Generative Gaussian ⇒ logistic posterior.
Example 4 — Hard
- Problem: Prove the logistic form: with .
- Asked: Algebra.
- Concept: Bayes in log-odds form.
- Approach: Divide numerator and denominator by .
- Solution: with . ∎ For equal-covariance Gaussians is the linear discriminant of C18.
- Final answer: As shown.
- Key lesson: Log-odds of the posterior equals the discriminant function.
Example 5 — Very Hard
- 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 on only 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.