Differentiate a validation loss through a ridge regression solution

Hyperparameter tuning by gradient descent needs the derivative of a validation loss with respect to the regularisation strength, through the solve itself.

Write ridge_lambda_grad(Xtr, ytr, Xva, yva, lam). The weights are w(lam) = (Xtr.T Xtr + lam I)^-1 Xtr.T ytr. The validation loss is L = mean((Xva @ w - yva) ** 2). Return (L, dL/dlam) using the identity dw/dlam = -(Xtr.T Xtr + lam I)^-1 w.

Signaturedef ridge_lambda_grad(Xtr, ytr, Xva, yva, lam)

Example

for any data, the returned derivative should match a finite difference of L in lam.

Understand the idea

To tune the ridge strength lam by gradient descent, you need how the validation loss changes as lam changes, and lam acts through the trained weights. Differentiate the system that defines the weights: A w = b with A = X^T X + lam I. Taking the derivative in lam gives A dw + w = 0, so dw/dlam = -A^-1 w. Worked example with one feature: Xtr = [[1], [1]], ytr = [1, 3], lam = 2. A = 1 + 1 + 2 = 4, b = 1 + 3 = 4, so w = 1. dw/dlam = -1 / 4 = -0.25. Validation: Xva = [[1]], yva = [2], prediction 1, L = (1 - 2)^2 = 1. dL/dw = 2 * (1 - 2) * 1 = -2. dL/dlam = -2 * -0.25 = 0.5. Rule: w = solve(A, Xtr^T ytr); dw = -solve(A, w); r = Xva w - yva; L = mean(r^2); dL/dlam = (2 / n_va) * r^T (Xva dw). Forgetting the solve and using dw = -w is only right when A is the identity. Used in gradient-based hyperparameter tuning.

solution.pyPython idle
Ctrl/Cmd + Enter runs sample tests

Run checks the first 2 tests. Submit checks the hidden tests with Pro.

  • Sample 1: randomridge_lambda_grad(_Xt, _yt, _Xv, _yv, 0.5)
  • Sample 2: matches finite difference(lambda h: (ridge_lambda_grad(_Xt, _yt, _Xv, _yv, 0.5 + h)[0] - ridge_lambda_grad(_Xt, _yt, _Xv, _yv, 0.5 -...