Build Linear Regression and MSE Loss Without Libraries
Machine LearningModel answerLast updated
Code mean squared error from scratch, then build a linear regression class with fit and predict methods using gradient descent.
Your task is to build a linear regression implementation without using any prebuilt regression or loss classes from machine learning libraries. You may use NumPy for array operations.
Part 1: Mean Squared Error
Create a function that computes the mean squared error between true values and predictions:
$$\text{MSE} = \frac{1}{n}\sum_{i=1}^{n}(y_i - \hat{y}_i)^2$$
Then derive and state the gradient of this loss with respect to the predictions $\hat{y}$.
Your function should:
- Accept two arrays of equal length
- Return a scalar loss value
- Handle edge cases like empty inputs or extreme values appropriately
Part 2: Linear Regression Class
Build a LinearRegression class with these methods:
fit(X, y): Train the model on feature matrixX(shape(n_samples, n_features)) and target vectory(shape(n_samples,))predict(X): Return predictions for new data
The model should learn both weights and a bias term by minimizing the MSE loss you defined in Part 1.
Implementation Requirements
- Use gradient descent to optimize the parameters
- Include input shape validation
- Discuss how you would verify correctness
- State the computational complexity per training iteration
Questions to Address
- How do you compute gradients with respect to weights and bias?
- What learning rate and stopping criteria will you use?
- Should features be normalized, and if so, how?
- When would you prefer a closed-form solution over gradient descent?
Hints
Hint 1
The MSE gradient with respect to predictions is (2/n)(ŷ - y). Use the chain rule to get weight and bias gradients.
Hint 2
Feature scaling to zero mean and unit variance stabilizes gradient descent and allows a single learning rate to work across features.
Hint 3
Test on data where you know the answer: a perfect linear relationship, or compare against the closed-form solution W = (X^T X)^(-1) X^T y.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Model Answer
Part 1: MSE Loss Function
import numpy as np
def mean_squared_error(y_true, y_pred):
"""
Compute mean squared error between true and predicted values.
Args:
y_true: array of shape (n,)
y_pred: array of shape (n,)
Returns:
scalar MSE value
"""
y_true = np.asarray(y_true)
y_pred = np.asarray(y_pred)
if y_true.shape != y_pred.shape:
raise ValueError("Shape mismatch: y_true and y_pred must have same shape")
if len(y_true) == 0:
raise ValueError("Cannot compute MSE on empty arrays")
diff = y_pred - y_true
return np.mean(diff ** 2)
Gradient Derivation:
The gradient of MSE with respect to predictions is:
$$\frac{\partial \text{MSE}}{\partial \hat{y}} = \frac{2}{n}(\hat{y} - y)$$
This comes from differentiating each squared term and applying the chain rule. The factor of 2 appears from the power rule, and we divide by n when taking the mean.
Part 2: Linear Regression Implementation
class LinearRegression:
def __init__(self, learning_rate=0.01, n_iterations=1000, tol=1e-6):
"""
Initialize linear regression with gradient descent.
Args:
learning_rate: step size for gradient descent
n_iterations: maximum training iterations
tol: loss change threshold for early stopping
"""
self.lr = learning_rate
self.n_iterations = n_iterations
self.tol = tol
self.weights = None
self.bias = None
self.feature_mean = None
self.feature_std = None
def _normalize_features(self, X, fit=False):
"""Standardize features to zero mean and unit variance."""
if fit:
self.feature_mean = np.mean(X, axis=0)
self.feature_std = np.std(X, axis=0)
# Avoid division by zero for constant features
self.feature_std[self.feature_std == 0] = 1.0
return (X - self.feature_mean) / self.feature_std
def fit(self, X, y):
"""
Train linear regression using gradient descent.
Args:
X: feature matrix of shape (n_samples, n_features)
y: target vector of shape (n_samples,)
"""
X = np.asarray(X)
y = np.asarray(y)
if X.ndim == 1:
X = X.reshape(-1, 1)
if len(X) != len(y):
raise ValueError("X and y must have same number of samples")
n_samples, n_features = X.shape
# Normalize features
X_norm = self._normalize_features(X, fit=True)
# Initialize parameters
self.weights = np.zeros(n_features)
self.bias = 0.0
prev_loss = float('inf')
for iteration in range(self.n_iterations):
# Forward pass: compute predictions
y_pred = X_norm @ self.weights + self.bias
# Compute loss
loss = mean_squared_error(y, y_pred)
# Check for convergence
if abs(prev_loss - loss) < self.tol:
break
prev_loss = loss
# Compute gradients
# Loss gradient w.r.t. predictions: (2/n)(y_pred - y)
error = y_pred - y
# Chain rule for weight gradient: X^T @ error / n
# We absorb the factor of 2 into the learning rate
grad_weights = (X_norm.T @ error) / n_samples
grad_bias = np.mean(error)
# Update parameters
self.weights -= self.lr * grad_weights
self.bias -= self.lr * grad_bias
return self
def predict(self, X):
"""
Make predictions on new data.
Args:
X: feature matrix of shape (n_samples, n_features)
Returns:
predictions of shape (n_samples,)
"""
if self.weights is None:
raise ValueError("Model must be fitted before calling predict")
X = np.asarray(X)
if X.ndim == 1:
X = X.reshape(-1, 1)
X_norm = self._normalize_features(X, fit=False)
return X_norm @ self.weights + self.bias
Key Design Decisions
Feature Scaling: I normalize features to have zero mean and unit variance during training. Without this, features with larger scales dominate the gradient, requiring very small learning rates that slow convergence on other features. The normalization parameters are stored and applied consistently at prediction time.
Learning Rate: A learning rate around 0.01–0.1 typically works for normalized features. Too large causes divergence; too small wastes iterations. For production code, consider adaptive methods like Adam or learning rate schedules.
Stopping Criterion: I use both a maximum iteration count and early stopping when loss change falls below a threshold. This balances training time with convergence guarantees.
Gradient Computation: The weight gradient comes from the chain rule: ∂MSE/∂w = (∂MSE/∂ŷ) · (∂ŷ/∂w) = (2/n)(ŷ - y) · X. The bias gradient is simply the mean error. I absorb the constant factor 2 into the learning rate.
Verification Strategy
Test on synthetic data with a known linear relationship:
# Generate perfect linear data
X_test = np.random.randn(100, 3)
true_weights = np.array([2.5, -1.0, 3.0])
true_bias = 1.5
y_test = X_test @ true_weights + true_bias + np.random.randn(100) * 0.01
model = LinearRegression(learning_rate=0.1, n_iterations=5000)
model.fit(X_test, y_test)
# Check learned parameters are close to true values
print("Learned weights:", model.weights)
print("True weights:", true_weights)
Alternatively, compare against the closed-form solution for small datasets:
# Closed-form: w = (X^T X)^(-1) X^T y
X_with_bias = np.column_stack([X_norm, np.ones(len(X_norm))])
closed_form = np.linalg.lstsq(X_with_bias, y, rcond=None)[0]
Complexity Analysis
Per iteration:
- Forward pass: O(n · d) for n samples and d features
- Gradient computation: O(n · d) for matrix-vector products
- Parameter update: O(d)
- Total: O(n · d) time, O(n · d) space for storing the feature matrix
Closed-form alternative: O(d³ + n · d²) time to solve the normal equations (X^T X)w = X^T y. Preferred when d is small and the exact solution is needed in one shot. Gradient descent is better when n or d is large, memory is limited, or you need online learning.
Common Mistakes to Avoid
- Wrong gradient sign: Forgetting the negative sign in the update rule or swapping (ŷ - y) with (y - ŷ)
- Missing bias term: Fitting only weights produces poor results when the target has non-zero mean
- No feature scaling: Causes slow convergence and requires manual learning rate tuning per feature
- Ignoring numerical stability: Very large learning rates cause overflow; check loss is decreasing