v9.1.1
Menu

L2 Regularization Penalty

easyFREERegularization & TuningDeep LearningDeep Learning 1

Problem Statement

Calculate the L2 regularization term (weight decay) for a neural network.

Background

L2 regularization adds a penalty to the loss function based on the squared magnitude of weights:

L2term=λ2m∑∣∣W∣∣2L2_{term} = \frac{\lambda}{2m} \sum ||W||^2

Where:

  • λ\lambda (lambda) is the regularization strength
  • mm is the number of training examples
  • ∣∣W∣∣2||W||^2 is the sum of squared weights (Frobenius norm squared)

This encourages smaller weights, reducing overfitting.

Your Task

Write a function l2_penalty(weights_list, lambda_reg, m) that computes the L2 regularization term.

weights_list is a list of weight matrices (each as a list of lists).

Output Format

Return a float rounded to 4 decimal places.

Example

Input
weights_list=[[[3, 4]]], lambda_reg=1.0, m=1
Output
12.5
Reasoning
  • Inputs: weights_list holds a single weight matrix, a 1×21 \times 2 matrix with entries 33 and 44; the regularization strength is λ=1.0\lambda = 1.0 and there is m=1m = 1 training example.
  • Squared magnitude: every weight in every matrix contributes its square, so ∑∥W∥2=32+42=9+16=25\sum \|W\|^2 = 3^2 + 4^2 = 9 + 16 = 25. Matrix boundaries don't matter here: with several matrices, all their squares go into one total.
  • Scaling: the coefficient is λ2m=1.02⋅1=0.5\frac{\lambda}{2m} = \frac{1.0}{2 \cdot 1} = 0.5, so the penalty is 0.5×25=12.50.5 \times 25 = 12.5.
  • Output: a single float, 12.5, rounded to 4 decimal places (exact here, so nothing is lost).
  • Notice that the sign of a weight is irrelevant (squaring removes it), and that doubling mm halves the penalty: more training data means the regularizer pulls less hard relative to the data loss.

Constraints

  • 0 < lambda_reg <= 10
  • m >= 1
  • Each weight matrix is a 2D list

Learn this in

More from Deep Learning 1

solution.py

Test results

Sign in to run your code against the test cases.