Unit 1 of 8 · about 4 hours · derive, implement

Least squares: residuals, normal equations and stable solvers

Least squares is the baseline every later model is compared against. Its two failure modes, singular designs and outlier sensitivity, recur in every fitting method after it.

You'll be able to

  • Derive the normal equations from the squared-error objective and state when the solution is unique.
  • Implement least squares three ways (normal equations, SVD least squares, minibatch gradient descent) with a gradient check, and match them on well-conditioned data.
  • Explain why squared loss punishes large residuals quadratically and when that sensitivity becomes a liability.

Covers

Linear regression, residuals and squared versus absolute lossNormal equations, stable solvers and gradient descent
1

Read

In this order, only the parts listed

0 of 6 done

  1. Linear regression: model, squared loss, analytic solution and minibatch SGDDive into Deep Learning - linear models slice

    Sections 3.1.1.1 to 3.1.1.4 (model, squared-error loss with the factor, analytic solution, minibatch SGD update) and 3.1.3 (Gaussian noise makes squared loss maximum likelihood)

  2. Linear regression from scratchDive into Deep Learning - linear models slice

    Sections 3.4: Defining the Model, Defining the Loss Function, Defining the Optimization Algorithm, Training

    D2L shows framework tabs only; there is no plain NumPy tab. Implement in NumPy first, as the section use note asks, and read the PyTorch tab only as a differential reference.

  3. Simple and multiple linear regressionAn Introduction to Statistical Learning with Python

    Chapter 3, Sections 3.1 to 3.2 (pp. 70-90): the RSS objective, least squares coefficient estimates and the multiple-regression setup

  4. Linear regression labAn Introduction to Statistical Learning with Python

    Simple Linear Regression and Multiple Linear Regression sections on the Boston data: fit with statsmodels OLS and read coefficients, standard errors and

  5. Ordinary least squares semantics and solverscikit-learn - linear models, discriminant analysis and naive Bayes

    Section 1.1.1 including 1.1.1.2: LinearRegression minimizes the residual sum of squares, stores coef_ and intercept_, and solves through the SVD of at cost

  6. Normal equation and batch gradient descentHands-On Machine Learning with Scikit-Learn and PyTorch - classification and linear models

    Book Chapter 4: The Normal Equation (printed pp. 138-141) and Batch Gradient Descent (pp. 145-148). Notebook 04 cells: The Normal Equation section (theta_best with the explicit inverse, then the np.linalg.lstsq and pseudoinverse cross-checks) and Gradient Descent (the batch loop: gradient 2/m X_b'(X_b theta - y), eta 0.1, 1000 epochs from a random start)

2

Focus on

  • D2L scales its per-example loss by while HoML differentiates the plain mean of squares with a gradient. The minimizer is identical but the largest stable learning rate differs by that constant.
  • has a unique solution only when has full column rank. With duplicate or nearly collinear columns the fitted values stay well determined but the coefficients do not: in the 1e-4 demo below both solvers return slopes near 229 and -228, and only their sum, 1.012, is pinned by the data.
  • The course notebooks show inv(X'X)@X'y to teach the formula; sklearn never forms that inverse and solves through the SVD instead.
Common mistakes · 3
  • Shipping inv(X'X)@X'y as the solver. Forming squares the condition number, so a design with near 1e8 makes numerically singular near in float64 while lstsq still minimizes the residual.
  • Hand-rolling a bias column while the differential test keeps fit_intercept=True. sklearn centers the columns, so your ones column becomes all zeros: it gets coefficient 0 and intercept_ takes the offset. Predictions agree but a coefficient-by-coefficient comparison fails. Drop the column or pass fit_intercept=False.
  • Reading the second Deep-ML 15 test as the exact solution. It expects [2.9699, 2.0078], the gradient-descent iterate after 1000 steps at lr 0.05; the exact minimizer is [3, 2]. Zero initialization and the exact update decide it.
3

Try it yourself

Closed-book, before checking anything

From , derive on paper. Then build the near-collinear demo in NumPy: default_rng(1), , standard normal, times standard normal noise, an intercept column, , drawn in that order. Show = 2.08e4 and = 4.34e8, its square. The explicit inverse and lstsq agree to about 1e-5, but both return about [3.002, 229.2, -228.2], not [3, 2, -1]. Then rebuild with default_rng(0), , and : = 1.8e8 and = 3.25e15, and the explicit inverse stops at residual norm 3.8314 while lstsq reaches the minimum, 3.7978.
4

Quiz yourself

Answer first, then mark it. Missed ones go to Review.

0 got · 0 missed

  1. 1.D2L multiplies its loss by and HoML does not. Why is the minimizer unchanged but the stable learning rate different?Answer

    The constant scales the loss and every gradient without moving the stationary point, so the optimum is identical. A fixed step size moves half as far per step under the convention, so its stability limit on is twice as large.

  2. 2.Two columns of are identical. What happens to , the coefficients and the predictions?Answer

    is singular so the coefficients are not unique. The fitted values stay unique as the projection onto the column space, and SVD-based solvers return the minimum-norm coefficient vector.

  3. 3. is 2.08e4. What is , and at what point does the explicit inverse break down?Answer

    About 4.34e8, the square of . The explicit inverse loses all precision once approaches , about 4.5e15 in float64, which needs only near 7e7. At 1.8e8 it no longer reaches the least-squares minimum.

  4. 4.One label is corrupted upward by 100. Why does the squared-loss fit move far, and which single change to the loss limits the damage?Answer

    The quadratic penalty lets that one residual dominate the objective. An absolute-error loss grows only linearly with it, so the fit moves far less.

5

Practice

  • Deep-ML 15: Linear Regression Using Gradient Descent

    Gradient descent on the mean squared error from zero initialization. Test 1 expects [1, 2]; test 2 pins the 1000-step iterate [2.9699, 2.0078] at lr 0.05 rather than the exact [3, 2]

    Pass both tests, then show your lstsq solution agrees with test 1 and explain why it cannot match test 2 exactly.

  • NeetCode ML: Linear Regression Forward and Linear Regression Training

    Math Foundations pair: implement the forward pass, then full training cold

    After the section gate, compare the learned weights against your lstsq fit on the same data before moving on.

You're done when

Your normal-equation and lstsq fits agree to 1e-8 on well-conditioned data, minibatch SGD with a decaying step lands within 1e-3 of them (a constant step leaves it rattling about 1e-2 away), a float64 gradient check passes, and you can say for each Deep-ML 15 test whether it pins the optimum or the optimization path.

Only when you can do this without notes.

Leads to

Notes

Resources · 4 for this unit, 3 more in the section

Also in this section

  • NeetCode ML - linear-model closing drillNeetCode · support

    After the section gate, solve Gradient Descent, Sigmoid and ReLU, Softmax, Cross-Entropy Loss, Linear Regression Forward and Linear Regression Training cold. Repeat only failed items from a blank file with changed values.

  • Deep-ML - linear and probabilistic model problemsDeep-ML · support

    Use 15 Linear Regression Using Gradient Descent, 106 Train Logistic Regression with Gradient Descent and 140 Bernoulli Naive Bayes Classifier as unit checks after the local implementation passes. Their tests were read in review; each card states what they pin. The local implementation remains the evidence.

  • Tom Mitchell - Generative and Discriminative Classifiers: Naive Bayes and Logistic RegressionTom Mitchell, Carnegie Mellon University · required

    Read Sections 2 (naive Bayes, the smoothed estimates (7) and (9), parameter counts), 3 (Gaussian naive Bayes implies the logistic form, gradient ascent, the penalty, the -class rules) and 4 (generative versus discriminative, Ng and Jordan rates). This is the CS446 reading for Lectures 6-8; rework each derivation on a hand-sized dataset.