CD0011 Linear Regression Closed Form

Mode B · Build & Trace 30 Min NumPy 1.24+ 4 Linear-Algebra Blanks

Amazon’s delivery-time estimation team keeps its baseline deliberately boring: a closed-form least-squares fit over package and route features, written in raw NumPy so ops analysts can audit every coefficient without a sklearn dependency. Each row of X holds n numeric package and route features, and y is the observed delivery time in hours. You must implement ordinary least squares with an intercept in NumPy using the closed-form normal equation. scikit-learn, np.polyfit, and any gradient-descent loop are off limits.

The input X has shape (n_samples, n_features) with m rows and n features, and y has shape (n_samples,). Your function must return the coefficient vector beta of shape (n_features + 1,) with the intercept stored first, the in-sample predictions, and the coefficient of determination R^2. Expect the interviewer to push on numerical stability and on what your code does when the design matrix is singular.

Complete the 4 missing operations in the skeleton below and trace the exact array shape after each line. Then verify your fit against np.linalg.lstsq with np.testing.assert_allclose, estimate the flop and memory cost for a million-row training set, and explain when the closed form fails and what you would use instead.

Skeleton Code (Fill Blanks 1-4):

01  import numpy as np
02
03
04  def fit_ols(X: np.ndarray, y: np.ndarray):
05      """Closed-form OLS with intercept. X: (n_samples, n_features), y: (n_samples,)."""
06      X = np.asarray(X, dtype=np.float64)
07      y = np.asarray(y, dtype=np.float64).ravel()
08      n_samples, n_features = X.shape
09      # TODO (Blank 1): prepend an intercept column of ones
10      #                 X_design has shape (n_samples, n_features + 1); column 0 is the bias
11      X_design = ...
12      # TODO (Blank 2): solve the normal equations for beta, shape (n_features + 1,)
13      #                 must still return a beta when X is rank-deficient
14      beta = ...
15      # TODO (Blank 3): in-sample predictions and residuals, both (n_samples,)
16      y_hat = ...
17      resid = ...
18      # TODO (Blank 4): coefficient of determination R^2 (scalar)
19      r2 = ...
20      return beta, y_hat, r2
21
22
23  def predict(beta: np.ndarray, X_new: np.ndarray) -> np.ndarray:
24      """Apply fitted beta (intercept first) to new rows X_new: (k, n_features)."""
25      X_new = np.asarray(X_new, dtype=np.float64)
26      return beta[0] + X_new @ beta[1:]
Operator contract for closed-form OLS: inputs X of shape (n_samples, n_features) and y of shape (n_samples,) flow through four question-marked steps labeled Blank 1 to Blank 4 into outputs beta of shape (n+1,), y_hat of shape (n_samples,), and a scalar r2; below, boxes list the forbidden tools, the allowed NumPy building blocks, and the np.linalg.lstsq test oracle

Figure 1: The input and output contract is fixed, and the four linear-algebra steps in between are yours to write with plain NumPy.

Interactive NumPy Workspace: Switch to the split-screen workspace to fill Blanks 1-4 in the live editor and verify against the least-squares oracle.

Open in Colab ↗
Progressive Hints (Free · Zero Spoilers)
1Inspection Checklist (Where to Look)

(1) Intercept Convention: Line 26 reads the bias from beta[0], so the augmented design must agree with that column order and have shape (n_samples, n_features + 1).
(2) Linear-System Route: Decide which NumPy routine handles the (n + 1) \times (n + 1) system with the fewest flops and the smallest error, and what it does when the system is singular.
(3) Residual Geometry: For a correct fit with an intercept, the residuals are orthogonal to every design column and sum to zero.
(4) Baseline for R-Squared: The score compares your fit against a model that always predicts the mean of y; check that it gives 1 for a perfect fit and 0 for a mean-only fit.

2Visual Review Map (Figure 2)
Shape trace for fit_ols: the top row marks the target shapes of Blanks 1 and 2, from inputs X (n_samples, n_features) and y (n_samples,) to an (n_samples, n_features+1) design, an (n_features+1, n_features+1) system, and beta of shape (n+1,); the bottom row marks the target shapes of Blanks 3 and 4, y_hat and resid of shape (n_samples,) and a scalar r2, each with a question mark in place of the operation

Figure 2: The shape trace a strong candidate narrates aloud. Every blank shows the target shapes it must produce, and writing the operations that reach them is the exercise.

3Interviewer Nudge & Line Focus

Pin the exact input and output shape of each blank, and answer the check, before writing the NumPy call:

Blank 1 (Bias Column): np.ones(n_samples) is 1-D with shape (n_samples,) while X is 2-D. Which NumPy constructor stacks a 1-D vector as a column without an explicit reshape, and on which side must it go so that predict() reads the intercept, not a slope, from beta[0]?
Blank 2 (Normal-Equation Solve): The system matrix is only (n_features + 1, n + 1). Does computing its inverse and then multiplying cost more or fewer flops than factoring it once, and which route has the smaller error when the matrix is ill-conditioned? What should your code do when the factorization hits an exactly zero pivot?
Blank 3 (Predictions & Residuals): Which matrix-vector product gives shape (n_samples,)? If y had arrived as an (n_samples, 1) column, what shape would y - y_hat silently broadcast to, and which earlier line already protects you?
Blank 4 (R-Squared): Your score divides one sum of squares by another. Is the denominator built from y itself or from y after removing its mean, and what does your expression return when every target in the batch is identical?
Answer
Login to view more content
Log in to track your progress

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *