Ridge regression lossEasynumpyregressionregularizationridgeloss
Ridge regression loss
Background
Ridge regression is linear regression with an L2 penalty on the weights. The penalty discourages large coefficients, which reduces variance and stabilises the fit when features are correlated or the normal-equation system is near-singular. The ridge loss is the objective you minimise: mean squared error plus times the squared L2 norm of the weights.
Problem statement
Implement ridge_loss(X, w, y_true, alpha) that returns the ridge-regression objective:
Input
X—np.ndarrayof shape(n, d): the design matrix.w—np.ndarrayof shape(d,): the weight vector.y_true—np.ndarrayof shape(n,): the target values.alpha—float: the L2 regularisation strength.
Output
Returns a float: the mean-squared-error term plus the L2 penalty.
Examples
Example 1
Input: X = [[1, 1], [2, 1], [3, 1], [4, 1]], w = [0.2, 2], y_true = [2, 3, 4, 5], alpha = 0.1
Output: 2.204
Explanation: predictions give residuals , whose mean square is . The penalty is , so the loss is .
Constraints
- Use the mean squared error (divide by ), then add — the penalty is not averaged and has no factor of .
- Return a single
float. - Vectorise with numpy; tests compare with
atol=1e-6.
Notes
- The penalty is the only difference from plain MSE: as ridge becomes ordinary least squares, and as the weights are driven toward zero.
- Conventionally the intercept is not penalised; here every entry of
wis, so only fold a bias column intoX/wif you intend it to be regularised too.
Python
Loading...
This problem ships 4 hidden tests. They run in your browser via Pyodide — no backend, no submission queue. Press ▶ Run tests to execute.
- •Reference example equals 2.204
- •alpha = 0 reduces to mean squared error
- •Larger alpha increases the loss when weights are nonzero
- •Penalty term is exactly alpha * sum(w^2)