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:
-
mse_loss(y_true, y_pred) -> floatCompute the average squared residual acrossnpaired 1-D observations:MSE = (1 / n) * sum((y_true[i] - y_pred[i])^2)Return the result as a Pythonfloat. -
mse_gradient(y_true, y_pred) -> np.ndarrayCompute the 1-Dfloat64gradient vector ofmse_loss(y_true, y_pred)with respect toy_pred, having shape(n,):grad[i] = (2 / n) * (y_pred[i] - y_true[i]) -
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 onself, and initializeself.weights = Noneandself.bias = None.fit(X, y) -> LinearRegression: Given a 2-D design matrixXof shape(n, d)(n >= 1rows,d >= 1features) and a 1-D target vectoryof shape(n,), minimize unregularized MSE with gradient descent to learnself.weights(shape(d,)in original feature units) andself.bias(floatintercept), then returnself. 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 matrixXof shape(m, d)matching the fitted feature countd, return 1-D predictionsX @ self.weights + self.biasof shape(m,). Callingpredictbeforefitmust raiseRuntimeError.
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_lossandmse_gradientaccept 1-D sequences or NumPy arrays of matching lengthn >= 1containing only finite numbers; raiseValueErrorfor empty arrays, mismatched lengths, non-1-D shapes (including(n, 1)),NaN, orinf.- Convert integer inputs to
float64so squaring large 32-bit integers never wraps around, and avoid intermediate squaring overflow somse_lossstays finite whenever the true mean squared error fits infloat64(<= ~1.8e308), even for residuals near1e154. LinearRegression.__init__raisesValueErrorunlesslearning_rate > 0,max_iter >= 1, andtol >= 0.fitrequires 2-DXof shape(n, d)withn >= 1, d >= 1and 1-Dyof shape(n,)with finite values, raisingValueErrorotherwise.predictraisesRuntimeErrorif called beforefit, andValueErrorifXis not 2-D withdcolumns or contains non-finite values.- Typical sizes satisfy
1 <= n <= 10^4and1 <= d <= 100; each gradient step should run inO(n * d)time andO(n + d)working memory.
Step-by-step walkthrough
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:
weightsof shape(d,)in original feature units and a scalarfloatinterceptbias, supporting any feature countd >= 1without regularization in the base estimator. - Fail-fast validation: raise
ValueErrorimmediately on invalid shapes, empty arrays, length mismatches,NaN, orinfrather than returning silent wrong numbers.
Strict shape validation prevents one of the sneakiest bugs in NumPy. If
y_truehas shape(3,)andy_predholds the exact same numbers with column shape(3, 1), NumPy broadcasting (automatically stretching length-1 dimensions to match) turnsy_pred - y_trueinto a3 x 3grid 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
float64up front also prevents 32-bit integers from overflowing when squared (100,000^2 = 10^10, which wraps around the signed 32-bit limit2,147,483,647), and explicit emptiness/finiteness checks catch[],NaN, andinf.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- Vectorized NumPy arithmetic: we use standard array operations (
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 allnexamples: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.5Squaring
residuals ** 2directly fails on huge numbers. A 64-bit float (float64) maxes out near1.8e308, so squaring any residual larger thansqrt(1.8e308) ≈ 1.34e154overflows toinf. Even below that threshold, summing before dividing can overflow: ten residuals of1e154have squared sum10 * 1e308 = 1e309(inf), even though their true mean is1e308(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 multiplymax_residualback twice, groupingmax_residual * (max_residual * mean_scaled_sq)so the factormean_scaled_sq <= 1shrinksmax_residualfirst 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)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 predictionp_iaffects only thei-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): whenp_i > y_i(we predicted too high, like7.0vs4.0), the gradient entry+1.5is positive, so subtractingstep_size * gradpullsp_idownward towardy_i. Flipping it toy - pmakes training climb uphill and explode. - The
1 / nfactor: without dividing byn, 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- The sign
Propagate gradients to weights and bias via the chain rule
In linear regression, each row
iofXhasdfeatures, 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])frommse_gradient. To find howLchanges when we nudge weightw[j]or biasb, apply the chain rule (multiply how the loss changes with each prediction by how that prediction changes with the parameter, then sum over allnexamples):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 @ wfor predictions andX.T @ grad_predfor weight gradients), costingO(n * d)operations andO(n + d)working memory.Standardize features and target so gradient descent converges fast
Suppose feature 1 is apartment rooms (
1to5) and feature 2 is floor area (500to5,000). Changingw[1]by0.01swings predictions by50, whereas changingw[0]by0.01barely moves them by0.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 mean0and variance1. Standardizingyas well makes the stopping tolerancetolscale-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 checkmax == minin addition tostd == 0: in 64-bit floating point,np.full(50, 0.1).mean()rounds to0.09999999999999998, leaving a tiny fakestdof2.8e-17that would blow up weights by10^17when divided! Zeroing out constant columns directly and setting their scale divisor to1.0keeps their weight cleanly at0.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 foryalgebraically: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_stdBuild 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_ratecould still overshoot. Instead of guessing a tiny conservative rate, start atlearning_rate = 0.5and use backtracking line search: try the candidate step, and if it fails to lower the loss enough, halvestep_sizeand retry from the same point.Why check
candidate_loss > loss - 1e-4 * step_size * grad_norm_sq(Armijo sufficient decrease) rather than plaincandidate_loss > loss? Because on a quadratic bowl with curvatureL, a step of exact size2 / Ljumps cleanly across the valley to the symmetric opposite wall wherecandidate_loss == loss! Withcandidate_loss > loss, the optimizer would accept that jump and bounce back and forth forever (for example, on two identical features withlearning_rate = 0.5, or one feature withlearning_rate = 1.0). Requiring a tiny positive decrease catches exact valley-bounces immediately and halvesstep_sizeinto the sweet spot.Training stops as soon as the Euclidean norm of the standardized gradient
sqrt(||grad_w||^2 + grad_b^2)drops totolor below, or aftermax_itersteps.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, bVerify with a hand trace, closed-form solver, and finite differences
Verify the full pipeline with three complementary checks:
- Trace Example 2 by hand (
y = -2x + 5onx = [-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]- Compare against a least-squares linear solver (
np.linalg.lstsq): append a column of onesA = [X, 1]and solvemin ||A c - y||^2. Uselstsqrather thannp.linalg.inv(A.T @ A)becauselstsquses 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. - 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)matchesmse_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]- Trace Example 2 by hand (
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_lossandmse_gradient:O(n)time andO(n)extra space because we scan thenexamples 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 andO(n + d)working space because each iteration performs two matrix-vector multiplications across then x dmatrix (Z @ candidate_wfor predictions andZ.T @ grad_predfor weight gradients), storing vectors of lengthnandd. - Full
fit(X, y):O(k * n * d)time forkiterations andO(n * d)extra space to hold the standardized matrixZ. Herekgrows 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 increasesk. predict(X):O(m * d)time andO(m)output space to multiplymtest rows ofdfeatures byself.weightsand addself.bias.- Comparison with closed form: computing
A.T @ Aand solving it takesO(n * d^2 + d^3)time andO(d^2)space, which is faster whendis small and features are strongly correlated, while gradient descent wins whendis large.
Edge cases
- Empty input, mismatched lengths,
(n, 1)vs(n,), or 1-DX: rejected immediately withValueErrorso NumPy cannot returnnanon empty slices or broadcast(n, 1) - (n,)into an(n, n)pairwise matrix. - Integer arrays: converted to
float64before subtracting so 32-bit integer squares (like100,000^2) never wrap around into negative or truncated integers. - Very large residuals (
~1e154): dividing bymax_residualbefore squaring and multiplyingmax_residual * (max_residual * mean_scaled_sq)keepsmse_lossfinite whenever the true MSE fits insidefloat64(<= 1.8e308). - Constant feature column (including non-exact binary floats like
0.1): checked with bothmax == minandstd == 0, zeroed out explicitly, and givensafe_std = 1.0. Checkingstd == 0alone fails onnp.full(50, 0.1)because floating-point rounding inmean()leaves a2.8e-17residual std that would blow up unscaled weights. - Constant target
y: standardized to all zeros withsafe_std = 1.0, so the initial gradient atw = 0, b = 0is already zero and the model immediately predicts that exact constant. - Step size right on the
2 / Loscillation 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 halvesstep_sizeinstead of bouncing forever. - Nearly collinear features: when two features have correlation
0.9996(condition number ~5,000), gradient descent converges accurately given enough steps, whereasmax_iter = 10_000can stop slightly early without raising an error; inspectself.n_iter == self.max_iteror switch tolstsqfor tinyd.
Common mistakes
- Dropping
1 / nor flipping the sign inmse_gradient: omitting1 / nmakes the gradient scale up with dataset size so fixed step sizes diverge on large tables; writingy_true - y_predinstead ofy_pred - y_trueclimbs uphill. - Allowing
(n,)and(n, 1)arrays to broadcast:y_pred - y_truesilently 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
meanandstdon test data inpredict: test rows must use the training parameters mapped back to original units (or the training mean/std), never test-batch statistics. - Using
candidate_loss > lossfor backtracking: at the critical step2 / L, jumping to the opposite wall producescandidate_loss == lossand oscillates forever without shrinking the step size. - Inverting
X.T @ Xexplicitly (np.linalg.inv) as a reference: formingX.T @ Xsquares the condition number and crashes when two columns are collinear; use SVD/QR vianp.linalg.lstsq.
Alternative approaches
- Closed-form least squares via QR or SVD (
np.linalg.lstsq): computes the exact solution in a singleO(n * d^2)pass without step-size tuning or iteration limits; ideal wheneverdis at most a few thousand andXfits in memory. - Mini-batch stochastic gradient descent (SGD): estimates the gradient on small random batches of
Brows (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 + 1exact-arithmetic steps on linear least squares while keepingO(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||^2on the squared feature weights to shrink large weights and reduce overfitting, leaving the biasbunpenalized so predictions still center aroundmean(y). DifferentiatingMSE + lam * ||w||^2adds2 * lam * wto the weight gradient (grad_w = (2 / n) * X.T @ (X @ w + b - y) + 2 * lam * w) whilegrad_bstays unchanged. For centeredXandy, settinggrad_w = 0gives the closed formw = (X.T @ X + n * lam * I)^(-1) @ (X.T @ y)andb = mean(y) - mean(X) @ w(notice the factorn * lambecause MSE divides byn; forX.T @ X = 10,X.T @ y = 20,n = 5,lam = 0.2, OLS gives20 / 10 = 2.0whereas ridge gives20 / (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
dis modest (sayd <= 2,000), you can still compute the exact closed-form solution in one streaming pass over disk chunks by accumulatingX.T @ X(onlyd x dfloats),X.T @ y(dfloats), feature sums, and row countn. Whendis also huge, use mini-batch stochastic gradient descent (SGD) — reading shuffled batches ofBrows 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 aslr_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 the20), whereas mean absolute error (MAE) — the average of|y_pred - y_true|— is24 / 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 thresholddelta, 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), modellog(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 makesX.T @ Xsingular (determinant zero, non-invertible): for those two columnsX.T @ X = [[a, 2a], [2a, 4a]], whose determinant is4a^2 - 4a^2 = 0because infinitely many(w_1, w_2)pairs with the samew_1 + 2 * w_2yield identical predictions. Callingnp.linalg.inv(X.T @ X)either raisesLinAlgErroror explodes rounding noise into huge opposite weights like+10^15and-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 * Ishifts every eigenvalue up byn * lam > 0, guaranteeing an inverse), or use SVD-basednp.linalg.lstsq(which cleanly picks the unique minimum-norm weight vector, just like gradient descent initialized at zero).
Follow-up questions
- How does introducing an L2 ridge penalty alter the parameter gradients and the normal equations?
- What training strategy would you adopt if the feature table exceeds available RAM, and how does optimization behavior shift?
- In what regression settings is squared error ill-suited, and which alternative objectives would you choose?
- Why do normal equations break down when two predictor columns are collinear, and what remedies restore stability?
Similar questions
- Memory Layout Trade-Offs: Arrays vs. Linked Lists
- Unrolled Linked List Lookup and Insertion
- Low-Latency Tree Ensemble Inference
- Select Score Cutoff for Target Precision
- Payment Fraud Detection Under Class Imbalance and Drift
- Diagnosing and Fixing Overfitting in Supervised Learning