Python helpers — run once, the checks below reuse them
import numpy as npsigmoid = lambda z: 1 / (1 + np.exp(-z))def softmax(z): z = np.asarray(z, float); e = np.exp(z - z.max()) # subtract the max: overflow-safe return e / e.sum()def add_ones(x): # build the design matrix Z return np.c_[np.ones(len(x)), x]
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: x2=x12 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: Y=β0+β1X+ϵ (one regressor), or for X∈Rm:
f(X)=β0+∑j=1mxjβj.
Given (Xi,Yi), i=1..n, the sum of squared errorsE(β)=∑i=1n(Yi−β0−∑jxijβj)2=(Y−Zβ)T(Y−Zβ),
where Z is the n×(m+1) matrix with rows [1,xi1,…,xim] and β=[β0,…,βm]T.
Derivation of the normal equations
Expand: E=YTY−2βTZTY+βTZTZβ. Using ∂β∂(βTa)=a and ∂β∂(βTAβ)=2Aβ for symmetric A:
∂β∂E=−2ZTY+2ZTZβ=−2ZT(Y−Zβ).
Set to zero: ZTZβ=ZTY, so (when ZTZ is invertible)
β=(ZTZ)−1ZTY.
The Hessian is 2ZTZ⪰0, so the stationary point is a minimum (unique if Z has full column rank).
Key insights
Residuals are orthogonal to every column of Z: ZT(Y−Zβ^)=0. In particular, residuals sum to zero (the intercept column).
If columns of Z are linearly dependent (duplicate / collinear features, or n<m+1), ZTZ 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 x=1,2,3 (₹ lakh) on ads and sees sales y=2,3,5 (₹ lakh). Fit y=β0+β1x.
Problem: Verify the orthogonality conditions ZTe=0 for Example 2 and explain what they say.
Asked: Check.
Concept: Normal equations as orthogonality.
Approach: Dot products.
Solution: Column of ones: 0.1667−0.3333+0.1667=0 ✓. Column x: 1(0.1667)+2(−0.3333)+3(0.1667)=0 ✓.
Final answer:ZTe=0.
Python check
e = y - Z @ beta; print(Z.T @ e) # ≈ [0, 0]
Key lesson
The fitted vector Zβ^ is the orthogonal projection of Y onto the column space of Z.
Example 4 — Hard · Line vs quadratic
Problem: A sensor’s error depends on the distance from its calibration point x=1. Data (0,1),(1,0),(2,1),(3,4). Compare the best straight line with the quadratic y=β0+β1x+β2x2.
Asked: SSE of both.
Concept: Basis expansion (linear in parameters).
Approach: Line via Sxy/Sxx; quadratic by inspection and normal equations.
Solution:Line:xˉ=1.5, yˉ=1.5. Sxy=0.75+0.75−0.25+3.75=5; Sxx=5. β1=1, β0=0. y^=x: residuals 1,−1,−1,1, SSE =4. Quadratic: try y=(x−1)2=1−2x+x2: values 1,0,1,4 ✓ exact. This is a feasible point with E=0 and E≥0, so it is the minimiser: β=(1,−2,1), SSE =0.
Final answer: Line SSE =4; quadratic SSE =0 with β=(1,−2,1).
Python check
x = np.array([0, 1, 2, 3.]); y = np.array([1, 0, 1, 4.])for deg in (1, 2): Z = np.vander(x, deg + 1, increasing=True) # columns 1, x, x² ... b = np.linalg.lstsq(Z, y, rcond=None)[0]; print(deg, np.round(b, 4), round(((y - Z @ b)**2).sum(), 4))# 1 [0. 1.] 4.0 2 [ 1. -2. 1.] 0.0
Key lesson
Adding x2 as a feature keeps the problem linear and can remove the model’s bias.
Example 5 — Very Hard · Collinear features
Problem: Features x1=(1,2,3) and x2=2x1=(2,4,6) with intercept. (a) Show ZTZ 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) Z=111123246; col3=2col2. ZTZ=361261428122856 with row3=2row2 ⇒ det=0. (b) The model is β0+(β1+2β2)x1. Only β0 and s=β1+2β2 are determined (from Example 1: β0=31, s=1.5). Solutions: (31,1.5−2β2,β2) for any β2. (c) All give the same Zβ, hence the same fitted values and SSE =1/6.
Final answer: Infinite family; predictions identical.
Python check
Z = np.c_[np.ones(3), [1, 2, 3], [2, 4, 6]]print(np.linalg.det(Z.T @ Z), np.linalg.matrix_rank(Z)) # 0.0 2print(np.linalg.pinv(Z) @ [2, 3, 5]) # [0.3333 0.3 0.6] ← the minimum-norm member
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 β2=0.6).
Regression on a 0/1 target produces nonsense (predictions outside [0,1]). 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 0.5 sits exactly on it.
σ(z)
1.0 | ________
| _/
0.5 |- - - - - - -● ← z = 0: on the boundary, p = 0.5
| __/
0.0 |________/
+--------------------→ z = β0 + βᵀX
Formal definition
p(y=1∣X;β)=1+eβ0+βTXeβ0+βTX=σ(z),z=β0+βTX,p(y=0∣X)=1+ez1.
Decision: class 1 iff p(y=1∣X)≥0.5⟺z≥0. The decision boundary β0+βTX=0 is a hyperplane.
Derivation: likelihood → cross-entropy → gradient
Labels yi∈{0,1}, pi=p(Xi;β). Bernoulli likelihood: p(yi∣Xi)=piyi(1−pi)1−yi. Log-likelihood per sample: yilnpi+(1−yi)ln(1−pi). Loss (negative, = cross-entropy):
L(β)=−∑i=1n[yilnpi+(1−yi)ln(1−pi)].
Substitute pi=1+eziezi: lnpi=zi−ln(1+ezi) and ln(1−pi)=−ln(1+ezi). Then
yilnpi+(1−yi)ln(1−pi)=yizi−ln(1+ezi),L(β)=−i∑[yi(β0+βTXi)−ln(1+eβ0+βTXi)].
Differentiate: ∂βj∂ln(1+ezi)=1+eziezixij=pixij (with xi0=1). Hence
∂βj∂L=i=1∑nxij(pi−yi).
No closed-form solution; solve by gradient descent or Newton’s method. L is convex in β (its Hessian is ∑pi(1−pi)xixiT⪰0), so there is no spurious local minimum.
Key insights
Sigmoid derivative: σ′(z)=σ(z)(1−σ(z)).
The boundary is linear because it is z=0.
(Lecture slip: “the loss is linear in β” is inaccurate — the boundary is linear; the loss is convex, not linear.)
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: (0,0),(1,0),(2,1),(3,1). Start at β=(0,0). Do one gradient-descent step with η=0.1 and compare the loss before and after.
Asked: New β and loss.
Concept: Gradient formula.
Approach:pi=0.5 at the start.
Solution:pi=0.5 for all. ∂L/∂β0=∑(pi−yi)=0.5+0.5−0.5−0.5=0. ∂L/∂β1=∑xi(pi−yi)=0+0.5−1−1.5=−2. Update: β=(0,0)−0.1(0,−2)=(0,0.2). Loss before: 4ln2=2.7726. After: p=σ(0.2x)=(0.5,0.5498,0.5987,0.6457); L=0.6931+0.7981+0.5130+0.4373=2.4417 (decrease of 0.331).
A positive slope emerges because larger x go with y=1.
Example 5 — Very Hard · Perfectly separable data
Problem: Two points (x,y)=(−1,0),(1,1), model z=bx (no intercept). Show the loss has no minimiser and explain.
Asked: Behaviour of L(b).
Concept: Separable data ⇒ MLE does not exist.
Approach: Write the loss.
Solution: At x=1,y=1: −lnσ(b)=ln(1+e−b). At x=−1,y=0: −ln(1−σ(−b))=−lnσ(b)=ln(1+e−b). L(b)=2ln(1+e−b): b=1: 0.6265; b=3: 0.0972; b=5: 0.0134; L→0 as b→∞ but L>0 for every finite b.
Final answer: The infimum 0 is never attained: b^=+∞.
Python check
print([round(2*np.log(1 + np.exp(-b)), 4) for b in (1, 3, 5, 10)]) # 0.6265 0.0972 0.0134 0.0001
Key lesson
On linearly separable data, unregularised logistic regression pushes the weights to infinity; use regularisation or early stopping.
Common mistakes
Using labels {−1,+1} with the {0,1} formulas.
Sign errors in the gradient (pi−yi).
Exam traps
Threshold 0.5 ⇔ z=0.
The model is a classifier despite “regression” in its name.
Derive cross-entropy from the Bernoulli likelihood.
Derive ∂L/∂βj.
Explain why the boundary is linear.
C28. Multinomial Logistic Regression and Softmax
Intuition
With k classes keep one score per class and turn the scores into probabilities that sum to 1 by exponentiating and normalising.
Formal definition
softmax(z)r=∑j=1kezjezr,y^r=p(yr∣X)=∑j=1keβj0+βjTXeβr0+βrTX.
Labels are one-hot vectors Yi=[0,…,1,…,0]. Per-sample loss with true class c:
Li=−∑jyjlny^j=−lny^c=−(βc0+βcTXi)+ln∑jeβj0+βjTXi.
The parameters form a k×(m+1) matrix (the lecture writes k×m without the bias).
Derivation of the gradient w.r.t. scores
∂zr∂y^j=y^j(δjr−y^r). Then ∂zr∂L=−∑jyjy^j1y^j(δjr−y^r)=−yr+y^r∑jyj=y^r−yr. ∎ (Same shape as the binary gradient p−y.)
Key insights
Binary logistic regression = softmax with 2 classes (Example 3).
Softmax is shift-invariant: softmax(z+c1)=softmax(z).
Predicted class = argmaxry^r (equivalently argmax of the scores).
Worked examples
Example 1 — Very Easy · Softmax of three scores
Problem: Softmax of z=(1,2,3).
Asked: Probabilities.
Concept: Softmax.
Approach: Exponentiate, normalise.
Solution:e1=2.718,e2=7.389,e3=20.086; sum =30.193. Probabilities: 0.0900,0.2447,0.6652.
Final answer:(0.090,0.245,0.665).
Key lesson
Outputs lie in (0,1) and sum to 1.
Example 2 — Easy · Cross-entropy
Problem: The true class is the second. Cross-entropy for Example 1?
Asked:L.
Concept:−lny^c.
Approach: Pick the true class.
Solution:−ln0.2447=1.4076.
Final answer:1.408.
Key lesson
Other classes’ probabilities matter only through the normalisation.
Example 3 — Moderate · Softmax contains the sigmoid
Problem: Show that softmax over (0,z) equals the binary logistic probabilities.
Asked: Equivalence.
Concept: Softmax generalises the sigmoid.
Approach: Write y^2.
Solution:y^2=e0+ezez=1+ezez=σ(z) and y^1=1+ez1.
Final answer: Identical to the binary formulas of C27.
Key lesson
Binary logistic is the k=2 case with one score set to 0 (using shift invariance).
Example 4 — Hard · Overflow-safe softmax
Problem: Scores (1000,1001,1002). Direct ez overflows. Compute softmax stably.
Asked: Probabilities.
Concept: Shift invariance.
Approach: Subtract the max.
Solution:z−1002=(−2,−1,0). e−2=0.1353,e−1=0.3679,e0=1; sum =1.5032. Probabilities: 0.0900,0.2447,0.6652 — identical to Example 1 (the scores differ by the same offsets).
Final answer:(0.090,0.245,0.665).
Python check
print(softmax([1, 2, 3]), softmax([1000, 1001, 1002])) # same: [0.09 0.2447 0.6652]print(np.exp(1000)) # inf (overflow warning without the shift)
Key lesson
Always subtract maxjzj before exponentiating.
Example 5 — Very Hard · The gradient on the scores
Problem: For Example 1 with the true class second, write ∂L/∂z and verify it sums to zero. Then explain the gradient step’s effect on each score.
Asked: Gradient vector and interpretation.
Concept:y^−y.
Approach:y^−y with y=(0,1,0).
Solution:∂L/∂z=(0.0900,0.2447−1,0.6652)=(0.090,−0.755,0.665). Sum =0 ✓ (both y^ and y sum to 1). A descent step lowersz1,z3 (wrong classes, positive gradient) and raisesz2 (true class, negative gradient) — the push is proportional to the error.
Generative (e.g. Naive Bayes, Gaussian discriminant analysis): learn what each class looks like, p(X∣w)p(w), then invert with Bayes.
Discriminative (e.g. logistic regression, SVM, perceptron): learn the boundary or p(w∣X) directly, without modelling X.
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
Generative
Discriminative
Models
p(X∣w),p(w)
p(w∣X) or boundary
Predicts via
Bayes’ rule
direct
Can sample X?
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:
p(w1∣X)=p1f1+p2f2p1f1=1+e−g(X)1,g=lnp2f2p1f1=wTX+w0
with w=Σ−1(μ1−μ2) (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.
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.; p(image∣dog) 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 Σ=I, μ1=(0,0), μ2=(2,2), equal priors. Compute p(w1∣X) at X=(1,0).
Asked: Posterior.
Concept: The generative posterior is logistic.
Approach:g=−2x1−2x2+4 (C18 Ex. 1).
Solution:g(1,0)=2. p=σ(2)=0.8808.
Final answer:0.881.
Python check
from scipy.stats import multivariate_normal as mvnf1, f2 = mvn([0, 0], np.eye(2)), mvn([2, 2], np.eye(2))print(f1.pdf([1, 0]) / (f1.pdf([1, 0]) + f2.pdf([1, 0])), sigmoid(2)) # both 0.8808
Key lesson
Gaussian generative model ⇒ logistic posterior.
Example 4 — Hard · Prove the logistic form
Problem: Prove p(w1∣X)=1/(1+e−g) with g=lnp2f2p1f1.
Asked: Algebra.
Concept: Bayes in log-odds form.
Approach: Divide numerator and denominator by p1f1.
Solution:p(w1∣X)=p1f1+p2f2p1f1=1+p1f1p2f21=1+e−g1. ∎ For equal-covariance Gaussians g 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 f with p(f∣w1)=0.6, p(f∣w2)=0.2, equal priors, appears twice (duplicate column). Compare Naive Bayes (generative) and logistic regression (discriminative) posteriors for an instance with f=1.
Asked: Two posteriors.
Concept: Calibration under redundancy.
Approach: Log-odds.
Solution: Truth: P(w1∣f=1)=0.80.6=0.75, log-odds ln3=1.0986. NB: each copy adds ln3 ⇒ 2.1972 ⇒ σ(2.1972)=0.90. Logistic regression fitted by maximum conditional likelihood: z=β0+(β1+β2)f; the likelihood depends only on β1+β2 and is maximised at β1+β2=1.0986 ⇒ posterior 0.75.