#172Weight decay — the L2 penalty termEasyNeural NetworksOverfittingRegularization
Weight decay — the L2 penalty term
Background
L2 regularization (weight decay) discourages large weights by adding a penalty to the loss:
Smaller weights mean smoother, simpler decision boundaries that generalise better. Here you compute just the penalty term.
Problem statement
Implement l2_penalty(W, lam) returning for a weight array of any shape.
Input
W— array-like of weights (vector or matrix).lam—float, the regularization strength .
Output
Returns a Python float: times the sum of squared weights.
Examples
Example 1
Input: W = [[1, 2], [3, 4]], lam = 0.1
Output: 3.0
Explanation: .
Example 2 — no regularization
Input: W = [3, 4], lam = 0.0
Output: 0.0
Constraints
- Sum the squares of all entries of
W, then multiply bylam. - Return a plain
float.
Notes
- Biases are usually left out of weight decay; here we apply it to whatever
Wyou pass. The gradient of this term is , which is what "decays" the weights each step.
Python
Loading...
▶ Run executes the 3 visible sample tests below in your browser. Submit runs the full suite — including hidden tests — on the server for an official verdict.
- •example matrix penalty
- •reference vector penalty
- •sample zero lambda