Vectorized MSE and Linear Regression

Medium · Machine Learning · Machine Learning Engineer · Technical Screen

Problem Statement

Implement mean squared error (MSE), its gradient with respect to predicted values, and a multi-feature linear regression estimator trained via gradient descent using only NumPy array arithmetic (without calling pre-packaged regression models or loss utilities from external libraries).

Specifically, implement the following functions and class:

  1. mse_loss(y_true, y_pred) -> float Compute the average squared residual across n paired 1-D observations: MSE = (1 / n) * sum((y_true[i] - y_pred[i])^2) Return the result as a Python float.

  2. mse_gradient(y_true, y_pred) -> np.ndarray Compute the 1-D float64 gradient vector of mse_loss(y_true, y_pred) with respect to y_pred, having shape (n,): grad[i] = (2 / n) * (y_pred[i] - y_true[i])

  3. LinearRegression(learning_rate: float = 0.5, max_iter: int = 10_000, tol: float = 1e-6)

    • __init__: Validate hyperparameters (learning_rate > 0, max_iter >= 1, tol >= 0), store them on self, and initialize self.weights = None and self.bias = None.
    • fit(X, y) -> LinearRegression: Given a 2-D design matrix X of shape (n, d) (n >= 1 rows, d >= 1 features) and a 1-D target vector y of shape (n,), minimize unregularized MSE with gradient descent to learn self.weights (shape (d,) in original feature units) and self.bias (float intercept), then return self. Training must converge reliably even when columns span wildly different numeric magnitudes or offsets, contain constant values, have a constant target vector, or include linearly dependent features.
    • predict(X) -> np.ndarray: Given a 2-D feature matrix X of shape (m, d) matching the fitted feature count d, return 1-D predictions X @ self.weights + self.bias of shape (m,). Calling predict before fit must raise RuntimeError.

Examples

Example 1

Input:
  y_true = [2.0, -1.0, 4.0, 0.0]
  y_pred = [1.0, -1.0, 7.0, -2.0]

Output:
  mse_loss(y_true, y_pred)     -> 3.5
  mse_gradient(y_true, y_pred) -> array([-0.5, 0.0, 1.5, -1.0])

Walk-through: Subtracting y_true from y_pred gives residuals [-1.0, 0.0, 3.0, -2.0]. Their squares are [1.0, 0.0, 9.0, 4.0], so the mean over n = 4 elements is 14.0 / 4 = 3.5. Multiplying each residual by 2 / 4 = 0.5 gives [-0.5, 0.0, 1.5, -1.0].

Example 2

Input:
  X     = [[-2.0], [-1.0], [0.0], [1.0], [2.0]]
  y     = [9.0, 7.0, 5.0, 3.0, 1.0]
  X_new = [[3.0], [-4.0]]

Output:
  model = LinearRegression().fit(X, y)
  model.weights        -> array([-2.0])
  model.bias           -> 5.0
  model.predict(X_new) -> array([-1.0, 13.0])

Walk-through: All five points lie on y = -2.0 * x + 5.0, so zero loss occurs at weights = [-2.0] and bias = 5.0. Predicting on x = 3.0 and x = -4.0 yields -1.0 and 13.0.

Example 3

Input:
  X     = [[1.0, 0.0], [0.0, 2.0], [2.0, 1.0], [3.0, 3.0]]
  y     = [7.0, 0.0, 9.5, 10.5]
  X_new = [[2.0, 2.0], [0.0, 0.0]]

Output:
  model = LinearRegression().fit(X, y)
  model.weights        -> array([4.0, -1.5])
  model.bias           -> 3.0
  model.predict(X_new) -> array([8.0, 3.0])

Walk-through: Every row follows y = 4.0 * x_0 - 1.5 * x_1 + 3.0. Evaluating that plane at [2.0, 2.0] gives 8.0 - 3.0 + 3.0 = 8.0, and [0.0, 0.0] returns the intercept 3.0.

Constraints

  • mse_loss and mse_gradient accept 1-D sequences or NumPy arrays of matching length n >= 1 containing only finite numbers; raise ValueError for empty arrays, mismatched lengths, non-1-D shapes (including (n, 1)), NaN, or inf.
  • Convert integer inputs to float64 so squaring large 32-bit integers never wraps around, and avoid intermediate squaring overflow so mse_loss stays finite whenever the true mean squared error fits in float64 (<= ~1.8e308), even for residuals near 1e154.
  • LinearRegression.__init__ raises ValueError unless learning_rate > 0, max_iter >= 1, and tol >= 0.
  • fit requires 2-D X of shape (n, d) with n >= 1, d >= 1 and 1-D y of shape (n,) with finite values, raising ValueError otherwise.
  • predict raises RuntimeError if called before fit, and ValueError if X is not 2-D with d columns or contains non-finite values.
  • Typical sizes satisfy 1 <= n <= 10^4 and 1 <= d <= 100; each gradient step should run in O(n * d) time and O(n + d) working memory.

Step-by-step walkthrough

  1. Pin down the contract and guard array shapes

    Before writing arithmetic, verify the exact interface and input invariants our three components enforce:

    • Vectorized NumPy arithmetic: we use standard array operations (@, +, mean, std) without calling pre-built regression classes or loss functions.
    • Optimization strategy: gradient descent (iteratively stepping parameters opposite the slope of the loss), while keeping a linear-algebra least-squares solve as an independent test oracle.
    • Model parameters: weights of shape (d,) in original feature units and a scalar float intercept bias, supporting any feature count d >= 1 without regularization in the base estimator.
    • Fail-fast validation: raise ValueError immediately on invalid shapes, empty arrays, length mismatches, NaN, or inf rather than returning silent wrong numbers.

    Strict shape validation prevents one of the sneakiest bugs in NumPy. If y_true has shape (3,) and y_pred holds the exact same numbers with column shape (3, 1), NumPy broadcasting (automatically stretching length-1 dimensions to match) turns y_pred - y_true into a 3 x 3 grid of every pairwise difference instead of three zeros:

    y_pred (3, 1)   -   y_true (3,)    ->   broadcast (3, 3) grid!
       [[2],                                [[ 0, -3, -6],
        [5],        -   [2, 5, 8]      ->    [ 3,  0, -3],   mean of squares = 108 / 9 = 12.0 (should be 0.0!)
        [8]]                                 [ 6,  3,  0]]
    

    Casting both arrays to float64 up front also prevents 32-bit integers from overflowing when squared (100,000^2 = 10^10, which wraps around the signed 32-bit limit 2,147,483,647), and explicit emptiness/finiteness checks catch [], NaN, and inf.

    import numpy as np
    
    
    def _validate_targets(y_true, y_pred):
        """Validate and return (targets, predictions) as matching non-empty 1-D float64 arrays."""
        # Cast to float64 up front so integer inputs (such as int32) never wrap around when squared.
        targets = np.asarray(y_true, dtype=np.float64)
        predictions = np.asarray(y_pred, dtype=np.float64)
    
        # Reject non-1-D shapes: subtracting (n,) from (n, 1) would silently broadcast to (n, n).
        if targets.ndim != 1 or predictions.ndim != 1:
            raise ValueError("y_true and y_pred must be 1-D arrays")
        if targets.shape != predictions.shape:
            raise ValueError(
                f"length mismatch: {targets.shape[0]} targets vs {predictions.shape[0]} predictions"
            )
        if targets.size == 0:
            raise ValueError("MSE of an empty array is undefined")
        if not (np.all(np.isfinite(targets)) and np.all(np.isfinite(predictions))):
            raise ValueError("inputs must not contain NaN or infinity")
    
        return targets, predictions
    
  2. Compute MSE loss safely without overflow

    A residual is the signed prediction error on one example, r_i = y_pred[i] - y_true[i]. The mean squared error (MSE) squares each residual so positive and negative errors cannot cancel out, then averages them across all n examples:

    MSE = (1 / n) * sum_{i=1..n} (y_pred[i] - y_true[i])^2
    
    Walk through Example 1:
      y_true    = [ 2.0, -1.0,  4.0,  0.0]
      y_pred    = [ 1.0, -1.0,  7.0, -2.0]
      residuals = [-1.0,  0.0,  3.0, -2.0]
      squares   = [ 1.0,  0.0,  9.0,  4.0]  ->  MSE = (1 + 0 + 9 + 4) / 4 = 14 / 4 = 3.5
    

    Squaring residuals ** 2 directly fails on huge numbers. A 64-bit float (float64) maxes out near 1.8e308, so squaring any residual larger than sqrt(1.8e308) ≈ 1.34e154 overflows to inf. Even below that threshold, summing before dividing can overflow: ten residuals of 1e154 have squared sum 10 * 1e308 = 1e309 (inf), even though their true mean is 1e308 (perfectly finite!).

    We avoid both traps by dividing every residual by max_residual = max(|r_i|) before squaring. Every scaled entry now sits inside [-1, 1], so its square is in [0, 1] and can never overflow. At the end we multiply max_residual back twice, grouping max_residual * (max_residual * mean_scaled_sq) so the factor mean_scaled_sq <= 1 shrinks max_residual first before the second multiplication.

    def mse_loss(y_true, y_pred) -> float:
        """Mean squared error: (1/n) * sum((y_true - y_pred)^2)."""
        targets, predictions = _validate_targets(y_true, y_pred)
    
        # residuals: shape (n,), signed prediction error on each example
        residuals = predictions - targets
        max_residual = float(np.max(np.abs(residuals)))
    
        # Return 0.0 for an exact fit, or inf if a single subtraction overflowed float64.
        if max_residual == 0.0 or not np.isfinite(max_residual):
            return max_residual
    
        # Scale residuals into [-1, 1] before squaring so large errors (~1e154) cannot overflow.
        scaled_residuals = residuals / max_residual
        mean_scaled_sq = float(np.mean(scaled_residuals ** 2))
    
        # Multiply (max_residual * mean_scaled_sq) first: since mean_scaled_sq <= 1, this stays
        # finite whenever the true mean fits in float64 even if max_residual**2 alone would overflow.
        return max_residual * (max_residual * mean_scaled_sq)
    
  3. Derive the MSE gradient with respect to predictions

    A gradient is a vector of partial derivatives telling us how fast the loss changes when we nudge each input slightly. Because MSE = (1/n) * ((p_1 - y_1)^2 + (p_2 - y_2)^2 + ...), changing prediction p_i affects only the i-th squared term:

    L(p) = (1 / n) * sum_{k=1..n} (p_k - y_k)^2
    
    Differentiate with respect to a single p_i:
      dL / dp_i = (1 / n) * d/dp_i [ (p_i - y_i)^2 ]
                = (1 / n) * 2 * (p_i - y_i)
                = (2 / n) * (p_i - y_i)
    

    On Example 1 (residuals = [-1.0, 0.0, 3.0, -2.0], n = 4), the gradient is (2 / 4) * [-1.0, 0.0, 3.0, -2.0] = [-0.5, 0.0, 1.5, -1.0]. Notice why every piece of (2 / n) * (p - y) matters:

    • The sign (p - y): when p_i > y_i (we predicted too high, like 7.0 vs 4.0), the gradient entry +1.5 is positive, so subtracting step_size * grad pulls p_i downward toward y_i. Flipping it to y - p makes training climb uphill and explode.
    • The 1 / n factor: without dividing by n, you get the gradient of the sum of squared errors, which grows linearly with dataset size — a learning rate that works for 100 rows would blow up on 100,000 rows.
    def mse_gradient(y_true, y_pred) -> np.ndarray:
        """Gradient of mse_loss with respect to y_pred: (2/n) * (y_pred - y_true), shape (n,)."""
        targets, predictions = _validate_targets(y_true, y_pred)
        num_examples = targets.size
        residuals = predictions - targets
    
        # Differentiating (1/n) * sum((p_i - y_i)^2) with respect to p_i gives (2/n) * (p_i - y_i).
        return (2.0 / num_examples) * residuals
    
  4. Propagate gradients to weights and bias via the chain rule

    In linear regression, each row i of X has d features, and the model predicts a weighted sum plus a bias:

    pred[i] = X[i, 0] * w[0] + X[i, 1] * w[1] + ... + X[i, d-1] * w[d-1] + b
    in matrix form:  pred = X @ w + b     shapes: (n, d) @ (d,) + scalar -> (n,)
    

    We already have grad_pred[i] = dL / d(pred[i]) from mse_gradient. To find how L changes when we nudge weight w[j] or bias b, apply the chain rule (multiply how the loss changes with each prediction by how that prediction changes with the parameter, then sum over all n examples):

    Since d(pred[i]) / dw[j] = X[i, j]  and  d(pred[i]) / db = 1:
    
      dL / dw[j] = sum_{i=1..n} (dL / d(pred[i])) * X[i, j]  ->  grad_w = X.T @ grad_pred   shape (d,)
      dL / db    = sum_{i=1..n} (dL / d(pred[i])) * 1        ->  grad_b = sum(grad_pred)    scalar
    
    Mini hand check: X = [[1], [3]], y = [3, 9], starting at w = [0], b = 0:
      pred      = [0, 0]
      grad_pred = (2 / 2) * ([0, 0] - [3, 9]) = [-3, -9]
      grad_w    = [1 * (-3) + 3 * (-9)] = [-30]
      grad_b    = (-3) + (-9) = -12
    Direct calculus check at b = 0: L(w) = ((w - 3)^2 + (3w - 9)^2) / 2 -> dL/dw = (2(w-3) + 6(3w-9)) / 2 = -30 at w = 0. Matches!
    

    Each iteration needs just two matrix-vector products (X @ w for predictions and X.T @ grad_pred for weight gradients), costing O(n * d) operations and O(n + d) working memory.

  5. Standardize features and target so gradient descent converges fast

    Suppose feature 1 is apartment rooms (1 to 5) and feature 2 is floor area (500 to 5,000). Changing w[1] by 0.01 swings predictions by 50, whereas changing w[0] by 0.01 barely moves them by 0.05. Plotted in weight space, the MSE surface becomes a razor-thin canyon instead of a round bowl:

    Unscaled features (narrow canyon):             Standardized features (round bowl):
      w[1] ^  ====================                   w_s[1] ^      . - ~ - .
           |   \  zig-zag bounce /                          |    /     \     \
           |    *---------------> slow crawl                |   |       *     |  direct step!
           |   /                 \                          |    \           /
           +-----------------------> w[0]                   +--------` - '------> w_s[0]
    

    Standardization subtracts each column's mean and divides by its standard deviation (z = (x - mean) / std), giving every non-constant feature mean 0 and variance 1. Standardizing y as well makes the stopping tolerance tol scale-free (whether targets are in tiny decimals or millions).

    Two practical details matter when standardizing: 1. Constant columns: a column where every row is identical has true spread 0. Notice we check max == min in addition to std == 0: in 64-bit floating point, np.full(50, 0.1).mean() rounds to 0.09999999999999998, leaving a tiny fake std of 2.8e-17 that would blow up weights by 10^17 when divided! Zeroing out constant columns directly and setting their scale divisor to 1.0 keeps their weight cleanly at 0.0. 2. Unscaling back to original units: once gradient descent learns (w_scaled, b_scaled) predicting (y - y_mean) / y_std = ((X - x_mean) / x_std) @ w_scaled + b_scaled, solve for y algebraically:

    y_hat = y_mean + y_std * ( sum_j w_scaled[j] * (X[:, j] - x_mean[j]) / x_std[j] + b_scaled )
          = sum_j [ y_std * w_scaled[j] / x_std[j] ] * X[:, j]
            + [ y_mean + y_std * b_scaled - sum_j (y_std * w_scaled[j] / x_std[j]) * x_mean[j] ]
    
    Therefore:
      weights = y_std * w_scaled / x_std
      bias    = y_mean + y_std * b_scaled - sum(weights * x_mean)
    
    def _standardize(values):
        """Center and scale values to zero mean and unit variance; constant columns become zeros."""
        mean = values.mean(axis=0)
        std = values.std(axis=0)
    
        # Check max == min in addition to std == 0: in float64, np.full(50, 0.1).mean() has a 1-ulp
        # rounding error, giving a tiny non-zero std (~2.8e-17) that would blow up unscaled weights.
        is_constant = (values.max(axis=0) == values.min(axis=0)) | (std == 0.0)
        exact_mean = np.where(is_constant, values.max(axis=0), mean)
        centered = np.where(is_constant, 0.0, values - exact_mean)
        safe_std = np.where(is_constant, 1.0, std)
        standardized = centered / safe_std
        return standardized, exact_mean, safe_std
    
  6. Build the backtracking gradient descent loop and model class

    Even on standardized data, correlated features can steepen the curvature along their shared direction, so a fixed learning_rate could still overshoot. Instead of guessing a tiny conservative rate, start at learning_rate = 0.5 and use backtracking line search: try the candidate step, and if it fails to lower the loss enough, halve step_size and retry from the same point.

    Why check candidate_loss > loss - 1e-4 * step_size * grad_norm_sq (Armijo sufficient decrease) rather than plain candidate_loss > loss? Because on a quadratic bowl with curvature L, a step of exact size 2 / L jumps cleanly across the valley to the symmetric opposite wall where candidate_loss == loss! With candidate_loss > loss, the optimizer would accept that jump and bounce back and forth forever (for example, on two identical features with learning_rate = 0.5, or one feature with learning_rate = 1.0). Requiring a tiny positive decrease catches exact valley-bounces immediately and halves step_size into the sweet spot.

    Training stops as soon as the Euclidean norm of the standardized gradient sqrt(||grad_w||^2 + grad_b^2) drops to tol or below, or after max_iter steps.

    class LinearRegression:
        def __init__(self, learning_rate: float = 0.5, max_iter: int = 10_000, tol: float = 1e-6):
            if learning_rate <= 0 or max_iter < 1 or tol < 0:
                raise ValueError("need learning_rate > 0, max_iter >= 1 and tol >= 0")
            self.learning_rate = learning_rate
            self.max_iter = max_iter
            self.tol = tol
            self.weights = None
            self.bias = None
            self.n_iter = 0
    
        def fit(self, X, y) -> "LinearRegression":
            X = np.asarray(X, dtype=np.float64)
            y = np.asarray(y, dtype=np.float64)
            if X.ndim != 2:
                raise ValueError("X must be 2-D with shape (n, d)")
            if y.ndim != 1 or y.shape[0] != X.shape[0]:
                raise ValueError("y must be 1-D with one target per row of X")
            if X.shape[0] == 0 or X.shape[1] == 0:
                raise ValueError("cannot fit on an empty dataset")
            if not (np.all(np.isfinite(X)) and np.all(np.isfinite(y))):
                raise ValueError("X and y must not contain NaN or infinity")
    
            Z, x_mean, x_std = _standardize(X)
            t, y_mean, y_std = _standardize(y)
    
            w_scaled, b_scaled = self._gradient_descent(Z, t)
    
            self.weights = y_std * w_scaled / x_std
            self.bias = float(y_mean + y_std * b_scaled - np.sum(self.weights * x_mean))
            return self
    
        def predict(self, X) -> np.ndarray:
            if self.weights is None:
                raise RuntimeError("call fit before predict")
            X = np.asarray(X, dtype=np.float64)
            if X.ndim != 2 or X.shape[1] != self.weights.shape[0]:
                raise ValueError(f"X must have shape (m, {self.weights.shape[0]})")
            if not np.all(np.isfinite(X)):
                raise ValueError("X must not contain NaN or infinity")
            return X @ self.weights + self.bias
    
        def _gradient_descent(self, Z, t):
            w = np.zeros(Z.shape[1], dtype=np.float64)
            b = 0.0
            step_size = self.learning_rate
            pred = Z @ w + b
            loss = mse_loss(t, pred)
            self.n_iter = 0
    
            for _ in range(self.max_iter):
                grad_pred = mse_gradient(t, pred)
                grad_w = Z.T @ grad_pred
                grad_b = float(np.sum(grad_pred))
                grad_norm_sq = float(grad_w @ grad_w) + grad_b * grad_b
    
                if np.sqrt(grad_norm_sq) <= self.tol:
                    break
    
                candidate_w = w - step_size * grad_w
                candidate_b = b - step_size * grad_b
                if np.array_equal(candidate_w, w) and candidate_b == b:
                    break
    
                candidate_pred = Z @ candidate_w + candidate_b
                self.n_iter += 1
    
                if not np.all(np.isfinite(candidate_pred)):
                    step_size /= 2.0
                    continue
                candidate_loss = mse_loss(t, candidate_pred)
                if candidate_loss > loss - 1e-4 * step_size * grad_norm_sq:
                    step_size /= 2.0
                    continue
    
                w = candidate_w
                b = candidate_b
                pred = candidate_pred
                loss = candidate_loss
    
            return w, b
    
  7. Verify with a hand trace, closed-form solver, and finite differences

    Verify the full pipeline with three complementary checks:

    1. Trace Example 2 by hand (y = -2x + 5 on x = [-2, -1, 0, 1, 2]):
    x = [-2, -1, 0, 1, 2] -> x_mean = 0.0,  x_std = sqrt(2),      Z[:, 0] = [-2, -1, 0, 1, 2] / sqrt(2)
    y = [ 9,  7, 5, 3, 1] -> y_mean = 5.0,  y_std = 2 * sqrt(2),  t       = [ 2,  1, 0, -1, -2] / sqrt(2)
    
    Iteration 1 (from w = [0.0], b = 0.0, step_size = 0.5):
      pred = [0, 0, 0, 0, 0],  grad_pred = (2 / 5) * (-t)
      grad_w = Z.T @ grad_pred = -(2 / 5) * sum(Z[:, 0] * t) = -(2 / 5) * (-5) = [2.0],  grad_b = 0.0
      candidate_w = [0.0] - 0.5 * [2.0] = [-1.0],  candidate_b = 0.0,  candidate_loss = 0.0  (accepted!)
    
    Iteration 2: grad_w = [0.0], grad_b = 0.0 -> norm 0.0 <= 1e-6 -> stop!
    Unscale:
      weights = (2 * sqrt(2)) * [-1.0] / sqrt(2) = [-2.0]
      bias    = 5.0 + 0.0 - (-2.0) * 0.0         = 5.0
      predict([[3.0], [-4.0]])                   = [-1.0, 13.0]
    
    1. Compare against a least-squares linear solver (np.linalg.lstsq): append a column of ones A = [X, 1] and solve min ||A c - y||^2. Use lstsq rather than np.linalg.inv(A.T @ A) because lstsq uses SVD and stays accurate even when features are collinear. Always compare fitted predictions first — when two columns are collinear, infinitely many weight vectors produce the exact same optimal predictions.
    2. Numerical gradient check (central finite differences): nudge one entry p[i] by +-h (h = 1e-6) and check that (mse_loss(y, p + h*e_i) - mse_loss(y, p - h*e_i)) / (2 * h) matches mse_gradient(y, p)[i] to roughly 6 significant digits.
    def closed_form_reference(X, y):
        A = np.column_stack([X, np.ones(X.shape[0])])
        coef = np.linalg.lstsq(A, y, rcond=None)[0]
        return coef[:-1], coef[-1]
    
  8. Complete solution

    import numpy as np
    
    
    def _validate_targets(y_true, y_pred):
        """Validate and return (targets, predictions) as matching non-empty 1-D float64 arrays."""
        # Cast to float64 up front so integer inputs (such as int32) never wrap around when squared.
        targets = np.asarray(y_true, dtype=np.float64)
        predictions = np.asarray(y_pred, dtype=np.float64)
    
        # Reject non-1-D shapes: subtracting (n,) from (n, 1) would silently broadcast to (n, n).
        if targets.ndim != 1 or predictions.ndim != 1:
            raise ValueError("y_true and y_pred must be 1-D arrays")
        if targets.shape != predictions.shape:
            raise ValueError(
                f"length mismatch: {targets.shape[0]} targets vs {predictions.shape[0]} predictions"
            )
        if targets.size == 0:
            raise ValueError("MSE of an empty array is undefined")
        if not (np.all(np.isfinite(targets)) and np.all(np.isfinite(predictions))):
            raise ValueError("inputs must not contain NaN or infinity")
    
        return targets, predictions
    
    
    def mse_loss(y_true, y_pred) -> float:
        """Mean squared error: (1/n) * sum((y_true - y_pred)^2)."""
        targets, predictions = _validate_targets(y_true, y_pred)
    
        # residuals: shape (n,), signed prediction error on each example
        residuals = predictions - targets
        max_residual = float(np.max(np.abs(residuals)))
    
        # Return 0.0 for an exact fit, or inf if a single subtraction overflowed float64.
        if max_residual == 0.0 or not np.isfinite(max_residual):
            return max_residual
    
        # Scale residuals into [-1, 1] before squaring so large errors (~1e154) cannot overflow.
        scaled_residuals = residuals / max_residual
        mean_scaled_sq = float(np.mean(scaled_residuals ** 2))
    
        # Multiply (max_residual * mean_scaled_sq) first: since mean_scaled_sq <= 1, this stays
        # finite whenever the true mean fits in float64 even if max_residual**2 alone would overflow.
        return max_residual * (max_residual * mean_scaled_sq)
    
    
    def mse_gradient(y_true, y_pred) -> np.ndarray:
        """Gradient of mse_loss with respect to y_pred: (2/n) * (y_pred - y_true), shape (n,)."""
        targets, predictions = _validate_targets(y_true, y_pred)
        num_examples = targets.size
        residuals = predictions - targets
    
        # Differentiating (1/n) * sum((p_i - y_i)^2) with respect to p_i gives (2/n) * (p_i - y_i).
        return (2.0 / num_examples) * residuals
    
    
    def _standardize(values):
        """Center and scale values to zero mean and unit variance; constant columns become zeros."""
        mean = values.mean(axis=0)
        std = values.std(axis=0)
    
        # Check max == min in addition to std == 0: in float64, np.full(50, 0.1).mean() has a 1-ulp
        # rounding error, giving a tiny non-zero std (~2.8e-17) that would blow up unscaled weights.
        is_constant = (values.max(axis=0) == values.min(axis=0)) | (std == 0.0)
        exact_mean = np.where(is_constant, values.max(axis=0), mean)
        centered = np.where(is_constant, 0.0, values - exact_mean)
        safe_std = np.where(is_constant, 1.0, std)
        standardized = centered / safe_std
        return standardized, exact_mean, safe_std
    
    
    class LinearRegression:
        def __init__(self, learning_rate: float = 0.5, max_iter: int = 10_000, tol: float = 1e-6):
            """
            learning_rate: initial step size for gradient descent on standardized data.
            max_iter: maximum number of gradient steps.
            tol: stop once the standardized gradient norm is at or below tol.
            """
            if learning_rate <= 0 or max_iter < 1 or tol < 0:
                raise ValueError("need learning_rate > 0, max_iter >= 1 and tol >= 0")
            self.learning_rate = learning_rate
            self.max_iter = max_iter
            self.tol = tol
            # weights: shape (d,) in original feature units; bias: scalar float intercept
            self.weights = None
            self.bias = None
            self.n_iter = 0
    
        def fit(self, X, y) -> "LinearRegression":
            """
            Learn self.weights and self.bias by minimizing MSE via gradient descent.
            X: shape (n, d), one row per example. y: shape (n,). Returns self.
            """
            X = np.asarray(X, dtype=np.float64)
            y = np.asarray(y, dtype=np.float64)
            if X.ndim != 2:
                raise ValueError("X must be 2-D with shape (n, d)")
            if y.ndim != 1 or y.shape[0] != X.shape[0]:
                raise ValueError("y must be 1-D with one target per row of X")
            if X.shape[0] == 0 or X.shape[1] == 0:
                raise ValueError("cannot fit on an empty dataset")
            if not (np.all(np.isfinite(X)) and np.all(np.isfinite(y))):
                raise ValueError("X and y must not contain NaN or infinity")
    
            # Phase 1: Standardize features Z (shape (n, d)) and target t (shape (n,)) so all
            # non-constant columns share unit scale and a single step size works across features.
            Z, x_mean, x_std = _standardize(X)
            t, y_mean, y_std = _standardize(y)
    
            # Phase 2: Minimize MSE on the standardized problem (t_hat = Z @ w_scaled + b_scaled).
            w_scaled, b_scaled = self._gradient_descent(Z, t)
    
            # Phase 3: Map standardized parameters back to original units using
            # y_hat = y_mean + y_std * (((X - x_mean) / x_std) @ w_scaled + b_scaled).
            self.weights = y_std * w_scaled / x_std
            self.bias = float(y_mean + y_std * b_scaled - np.sum(self.weights * x_mean))
            return self
    
        def predict(self, X) -> np.ndarray:
            """X: shape (m, d). Returns predictions of shape (m,)."""
            if self.weights is None:
                raise RuntimeError("call fit before predict")
            X = np.asarray(X, dtype=np.float64)
            if X.ndim != 2 or X.shape[1] != self.weights.shape[0]:
                raise ValueError(f"X must have shape (m, {self.weights.shape[0]})")
            if not np.all(np.isfinite(X)):
                raise ValueError("X must not contain NaN or infinity")
            return X @ self.weights + self.bias
    
        def _gradient_descent(self, Z, t):
            """Minimize mse_loss(t, Z @ w + b) with backtracking gradient descent from zeros."""
            # w: shape (d,), weights for standardized columns; b: scalar standardized bias
            w = np.zeros(Z.shape[1], dtype=np.float64)
            b = 0.0
            step_size = self.learning_rate
            pred = Z @ w + b
            loss = mse_loss(t, pred)
            self.n_iter = 0
    
            for _ in range(self.max_iter):
                # Chain rule through pred = Z @ w + b: d(pred_i)/dw_j = Z[i, j], d(pred_i)/db = 1.
                grad_pred = mse_gradient(t, pred)
                grad_w = Z.T @ grad_pred
                grad_b = float(np.sum(grad_pred))
                grad_norm_sq = float(grad_w @ grad_w) + grad_b * grad_b
    
                # Stop once the Euclidean length of the full parameter gradient is within tolerance.
                if np.sqrt(grad_norm_sq) <= self.tol:
                    break
    
                candidate_w = w - step_size * grad_w
                candidate_b = b - step_size * grad_b
    
                # If step_size shrank below float64 precision, no smaller step can move w or b.
                if np.array_equal(candidate_w, w) and candidate_b == b:
                    break
    
                candidate_pred = Z @ candidate_w + candidate_b
                self.n_iter += 1
    
                # Halve step_size if predictions overflowed or failed Armijo sufficient decrease.
                # Requiring a small positive drop (instead of candidate_loss > loss) prevents endless
                # oscillation when step_size equals 2 / L and jumps to the exact same loss across the bowl.
                if not np.all(np.isfinite(candidate_pred)):
                    step_size /= 2.0
                    continue
                candidate_loss = mse_loss(t, candidate_pred)
                if candidate_loss > loss - 1e-4 * step_size * grad_norm_sq:
                    step_size /= 2.0
                    continue
    
                w = candidate_w
                b = candidate_b
                pred = candidate_pred
                loss = candidate_loss
    
            return w, b
    

    ✅ Submit now — all tests should pass.

Intuition & how it works

Think of training a linear regression model like walking blindfolded to the lowest point of a smooth bowl-shaped valley. At each step, gradient descent (an optimization loop that repeatedly steps opposite the direction of steepest ascent) feels the slope under your feet using the mean squared error (MSE) — the average of the squared gaps between predicted values and true targets — and takes a step downhill.

Running raw gradient descent with a fixed step size directly on unscaled inputs fails in practice for three reasons. First, if one feature is measured in thousands (like floor area) and another in tiny decimals, the valley stretches into a narrow canyon where any step small enough not to bounce off the steep walls crawls millions of times along the flat floor. Second, a naive np.mean((y_pred - y_true) ** 2) silently produces bogus numbers when a (n, 1) column vector broadcasts against a (n,) flat vector, or overflows to inf when squaring large residuals above 1.34e154. Third, even with rescaled features, a fixed step size can overshoot or bounce endlessly across the valley when features are correlated.

Our solution fixes all three: it validates 1-D/2-D shapes strictly, rescales residuals by their maximum before squaring, standardizes (centers to mean zero and scales to unit standard deviation) both X and y before running backtracking gradient descent, and algebraically maps the learned parameters back to original units. For example, on y_true = [2, -1, 4, 0] and y_pred = [1, -1, 7, -2], the residuals are [-1, 0, 3, -2], so mse_loss returns (1 + 0 + 9 + 4) / 4 = 3.5 and mse_gradient returns (2 / 4) * [-1, 0, 3, -2] = [-0.5, 0.0, 1.5, -1.0]. When fitting y = -2x + 5 on x = [-2, -1, 0, 1, 2], standardization turns y into the exact negative of x on unit scale, one gradient step of 0.5 lands directly on w_scaled = -1, b_scaled = 0, and unscaling recovers weights = [-2.0] and bias = 5.0.

Complexity

  • mse_loss and mse_gradient: O(n) time and O(n) extra space because we scan the n examples a constant number of times to compute the residual array, its maximum magnitude, and the average square.
  • One gradient descent step: O(n * d) time and O(n + d) working space because each iteration performs two matrix-vector multiplications across the n x d matrix (Z @ candidate_w for predictions and Z.T @ grad_pred for weight gradients), storing vectors of length n and d.
  • Full fit(X, y): O(k * n * d) time for k iterations and O(n * d) extra space to hold the standardized matrix Z. Here k grows roughly linearly with the condition number (the ratio of the steepest curvature to the flattest non-zero curvature of the loss surface) of the feature correlation matrix; standardization eliminates bad scaling across units, though strong correlation between features still increases k.
  • predict(X): O(m * d) time and O(m) output space to multiply m test rows of d features by self.weights and add self.bias.
  • Comparison with closed form: computing A.T @ A and solving it takes O(n * d^2 + d^3) time and O(d^2) space, which is faster when d is small and features are strongly correlated, while gradient descent wins when d is large.

Edge cases

  • Empty input, mismatched lengths, (n, 1) vs (n,), or 1-D X: rejected immediately with ValueError so NumPy cannot return nan on empty slices or broadcast (n, 1) - (n,) into an (n, n) pairwise matrix.
  • Integer arrays: converted to float64 before subtracting so 32-bit integer squares (like 100,000^2) never wrap around into negative or truncated integers.
  • Very large residuals (~1e154): dividing by max_residual before squaring and multiplying max_residual * (max_residual * mean_scaled_sq) keeps mse_loss finite whenever the true MSE fits inside float64 (<= 1.8e308).
  • Constant feature column (including non-exact binary floats like 0.1): checked with both max == min and std == 0, zeroed out explicitly, and given safe_std = 1.0. Checking std == 0 alone fails on np.full(50, 0.1) because floating-point rounding in mean() leaves a 2.8e-17 residual std that would blow up unscaled weights.
  • Constant target y: standardized to all zeros with safe_std = 1.0, so the initial gradient at w = 0, b = 0 is already zero and the model immediately predicts that exact constant.
  • Step size right on the 2 / L oscillation boundary: Armijo sufficient decrease (candidate_loss <= loss - 1e-4 * step_size * grad_norm_sq) catches steps that jump across the bowl to the exact same loss (candidate_loss == loss) and halves step_size instead of bouncing forever.
  • Nearly collinear features: when two features have correlation 0.9996 (condition number ~5,000), gradient descent converges accurately given enough steps, whereas max_iter = 10_000 can stop slightly early without raising an error; inspect self.n_iter == self.max_iter or switch to lstsq for tiny d.

Common mistakes

  • Dropping 1 / n or flipping the sign in mse_gradient: omitting 1 / n makes the gradient scale up with dataset size so fixed step sizes diverge on large tables; writing y_true - y_pred instead of y_pred - y_true climbs uphill.
  • Allowing (n,) and (n, 1) arrays to broadcast: y_pred - y_true silently produces an (n, n) matrix whose average looks plausible while being completely wrong.
  • Training without feature standardization: when features span different orders of magnitude, a step size small enough for the largest feature barely moves weights on the smallest feature.
  • Forgetting to unscale weights, or re-computing mean and std on test data in predict: test rows must use the training parameters mapped back to original units (or the training mean/std), never test-batch statistics.
  • Using candidate_loss > loss for backtracking: at the critical step 2 / L, jumping to the opposite wall produces candidate_loss == loss and oscillates forever without shrinking the step size.
  • Inverting X.T @ X explicitly (np.linalg.inv) as a reference: forming X.T @ X squares the condition number and crashes when two columns are collinear; use SVD/QR via np.linalg.lstsq.

Alternative approaches

  • Closed-form least squares via QR or SVD (np.linalg.lstsq): computes the exact solution in a single O(n * d^2) pass without step-size tuning or iteration limits; ideal whenever d is at most a few thousand and X fits in memory.
  • Mini-batch stochastic gradient descent (SGD): estimates the gradient on small random batches of B rows (O(B * d) per step), allowing training on datasets far larger than RAM.
  • Conjugate gradient (CG) or L-BFGS: uses curvature history to pick search directions that cut across narrow valleys instead of zig-zagging, converging in at most d + 1 exact-arithmetic steps on linear least squares while keeping O(n * d) matrix-vector memory.

Follow-up questions

  • How does introducing an L2 ridge penalty alter the parameter gradients and the normal equations? L2 regularization (ridge regression) adds a penalty lam * ||w||^2 on the squared feature weights to shrink large weights and reduce overfitting, leaving the bias b unpenalized so predictions still center around mean(y). Differentiating MSE + lam * ||w||^2 adds 2 * lam * w to the weight gradient (grad_w = (2 / n) * X.T @ (X @ w + b - y) + 2 * lam * w) while grad_b stays unchanged. For centered X and y, setting grad_w = 0 gives the closed form w = (X.T @ X + n * lam * I)^(-1) @ (X.T @ y) and b = mean(y) - mean(X) @ w (notice the factor n * lam because MSE divides by n; for X.T @ X = 10, X.T @ y = 20, n = 5, lam = 0.2, OLS gives 20 / 10 = 2.0 whereas ridge gives 20 / (10 + 1) = 1.818). Always apply the penalty to standardized weights so features measured in smaller numbers are not penalized more heavily.
  • What training strategy would you adopt if the feature table exceeds available RAM, and how does optimization behavior shift? If the feature count d is modest (say d <= 2,000), you can still compute the exact closed-form solution in one streaming pass over disk chunks by accumulating X.T @ X (only d x d floats), X.T @ y (d floats), feature sums, and row count n. When d is also huge, use mini-batch stochastic gradient descent (SGD) — reading shuffled batches of B rows from disk and updating weights with noisy batch gradients, using feature means and standard deviations computed in a streaming pass (Welford's algorithm). Because each mini-batch gradient has random sampling noise around the true gradient, a constant learning rate no longer converges to the exact minimum — it bounces inside a small noise ball around the optimum unless you decay the learning rate over time (such as lr_0 / sqrt(step)). Likewise, the batch gradient norm never hits zero, so stop by tracking validation MSE on a held-out chunk (early stopping) instead.
  • In what regression settings is squared error ill-suited, and which alternative objectives would you choose? Because MSE squares every error, a single extreme outlier or mislabeled row can hijack the entire fit: on residuals [1, 1, 1, 1, 20], MSE is (4 + 400) / 5 = 80.8 (99% driven by the 20), whereas mean absolute error (MAE) — the average of |y_pred - y_true| — is 24 / 5 = 4.8. For heavy-tailed noise or corrupted labels, use MAE (which estimates the conditional median) or Huber loss (smoothly quadratic near zero and linear past a threshold delta, combining outlier resistance with smooth gradients). When over-predicting and under-predicting carry asymmetric business costs (such as inventory stocking), use quantile (pinball) loss; when positive targets span orders of magnitude (such as property values or compensation), model log(y) or use Poisson/Gamma deviance.
  • Why do normal equations break down when two predictor columns are collinear, and what remedies restore stability? Collinearity means one column is an exact linear combination of others (for example x_2 = 2 * x_1), which makes X.T @ X singular (determinant zero, non-invertible): for those two columns X.T @ X = [[a, 2a], [2a, 4a]], whose determinant is 4a^2 - 4a^2 = 0 because infinitely many (w_1, w_2) pairs with the same w_1 + 2 * w_2 yield identical predictions. Calling np.linalg.inv(X.T @ X) either raises LinAlgError or explodes rounding noise into huge opposite weights like +10^15 and -5 * 10^14. You can fix it in three ways: drop or combine the redundant feature, add L2 ridge regularization (X.T @ X + n * lam * I shifts every eigenvalue up by n * lam > 0, guaranteeing an inverse), or use SVD-based np.linalg.lstsq (which cleanly picks the unique minimum-norm weight vector, just like gradient descent initialized at zero).

Follow-up questions

Similar questions

More Indeed interview questions

All 3 Indeed questions →