Homework · Runs in your browser
Ridge, lasso and lambda selection in pure Python
Build the small pieces of the lesson in plain Python: mean squared error, the one-feature ridge and lasso weights, a bias-or-variance diagnosis rule, and a search for the best lambda on validation data. Edit starter.py, then run the tests. In the browser runner, press Run tests. In Colab or on your own machine, put starter.py and test_starter.py in one folder and run pytest. Nothing needs installing except pytest.
Hints:
- MSE: the mean of (y - prediction) squared.
- Ridge, one feature, no intercept: w = sum(xy) / (sum(xx) + lam).
- Lasso, one feature, no intercept: take s = sum(xy). Shrink its size by lam and stop at zero, keep the sign of s, then divide by sum(xx).
- Diagnosis: train error above the target means high bias. Otherwise a validation error more than max_gap above train means high variance. Otherwise good fit.
- Best lambda: fit on the training points for each candidate, score on the validation points, return the lambda with the lowest validation MSE (the first one wins a tie).
- Lesson check: x=[1,2,3], y=[2,4,5] gives 25/14 = 1.786 at lam=0 and 0.893 for ridge at lam=14.
Running the tests needs JavaScript. You can still read the starter code below and run it on your own machine with pytest.
Tab inserts 4 spaces. To move on with the keyboard, press Esc, then Tab. Shift+Tab always moves back.
Show a solution
Try it yourself first. This site is static, so the solution is sent to your browser with the page; it is hidden here, not secret.
def mse(y_true, y_pred):
"""Mean squared error between two equal-length lists."""
return sum((a - b) ** 2 for a, b in zip(y_true, y_pred)) / len(y_true)
def ridge_weight(x, y, lam):
"""Ridge weight for one feature, no intercept: minimise sum (y - w*x)^2 + lam * w^2."""
sxy = sum(a * b for a, b in zip(x, y))
sxx = sum(a * a for a in x)
return sxy / (sxx + lam)
def lasso_weight(x, y, lam):
"""Lasso weight for one feature, no intercept: minimise 0.5 * sum (y - w*x)^2 + lam * |w|."""
sxy = sum(a * b for a, b in zip(x, y))
sxx = sum(a * a for a in x)
shrunk = max(abs(sxy) - lam, 0.0)
sign = 1.0 if sxy >= 0 else -1.0
return sign * shrunk / sxx
def diagnose(train_err, val_err, target_err, max_gap):
"""Return "high bias", "high variance" or "good fit"."""
if train_err > target_err:
return "high bias"
if val_err - train_err > max_gap:
return "high variance"
return "good fit"
def best_lambda(x_train, y_train, x_val, y_val, lams):
"""Return the ridge lambda from lams with the lowest validation MSE."""
best, best_err = None, None
for lam in lams:
w = ridge_weight(x_train, y_train, lam)
err = mse(y_val, [w * a for a in x_val])
if best_err is None or err < best_err:
best, best_err = lam, err
return best
Show the tests (test_starter.py)
import math
from starter import best_lambda, diagnose, lasso_weight, mse, ridge_weight
X = [1, 2, 3]
Y = [2, 4, 5]
def test_mse_is_mean_of_squared_errors():
assert math.isclose(mse([1.0, 2.0, 3.0], [2.0, 2.0, 5.0]), 5 / 3), (
"errors are -1, 0, -2, so the squares are 1, 0, 4 and the mean is 5/3"
)
def test_ridge_with_zero_lambda_is_least_squares():
assert math.isclose(ridge_weight(X, Y, 0), 25 / 14), "lesson example: 25/14 = 1.786"
def test_ridge_shrinks_but_never_reaches_zero():
assert math.isclose(ridge_weight(X, Y, 14), 25 / 28), "lam=14 halves the weight"
w = ridge_weight(X, Y, 1000)
assert 0 < w < 0.03, "a huge lambda gives a tiny weight, but not exactly zero"
def test_lasso_subtracts_a_constant():
assert math.isclose(lasso_weight(X, Y, 7), 18 / 14), "(25 - 7) / 14"
def test_lasso_reaches_exactly_zero():
assert lasso_weight(X, Y, 25) == 0.0, "lam equal to sum(x*y) gives exactly 0"
assert lasso_weight(X, Y, 30) == 0.0, "past that point the weight stays at 0, not negative"
def test_lasso_keeps_the_sign_for_negative_relationships():
assert math.isclose(lasso_weight([1, 2, 3], [-2, -4, -5], 7), -18 / 14), (
"a negative relationship gives a negative weight of the same size"
)
def test_diagnose_high_bias():
assert diagnose(0.30, 0.29, target_err=0.12, max_gap=0.05) == "high bias", (
"train error above the target means the model cannot fit the data"
)
def test_diagnose_high_variance():
assert diagnose(0.03, 0.44, target_err=0.12, max_gap=0.05) == "high variance", (
"low train error with a large gap is overfitting"
)
def test_diagnose_good_fit():
assert diagnose(0.10, 0.12, target_err=0.12, max_gap=0.05) == "good fit"
def test_best_lambda_picks_the_validation_minimum():
lams = [0, 7, 14, 28, 140]
x_val = [1, 2, 3]
y_val = [1.2, 1.8, 3.1]
assert best_lambda(X, Y, x_val, y_val, lams) == 14, (
"validation MSE is 2.86, 0.19, 0.09, 0.82, 3.36, so lambda 14 wins"
)
def test_best_lambda_ties_go_to_the_first():
assert best_lambda([1.0], [1.0], [1.0], [1.0], [0, 0]) == 0
def test_diagnose_train_error_equal_to_target_is_not_bias():
assert diagnose(0.12, 0.13, target_err=0.12, max_gap=0.05) == "good fit", (
"bias needs train error strictly above the target"
)
def test_diagnose_gap_equal_to_max_gap_is_not_variance():
assert diagnose(0.05, 0.10, target_err=0.12, max_gap=0.05 + 1e-9) == "good fit", (
"variance needs the gap strictly above max_gap"
)
def test_diagnose_bias_wins_over_variance_when_both_hold():
assert diagnose(0.30, 0.90, target_err=0.12, max_gap=0.05) == "high bias", (
"check train error first: a model that cannot fit the training data has a bias problem"
)