Skip to content

← ML Foundations step 8 of 10

Easy Primitives

Implement L2 Regularization

L2 regularization adds a penalty for large weights to a training loss. Compute the penalty for the supplied weight vector; do not change the weights or perform an optimizer update.

Your task

Implement l2_regularization(weights, lambda_):

  • weights is a one-dimensional floating-point tensor.
  • lambda_ is a finite, nonnegative regularization strength.

Return the scalar tensor:

penalty = (lambda_ / 2) * sum(weights**2)

Sum over every weight. Do not take a square root or divide by the number of weights. Include the factor of one-half: other conventions can absorb it into the strength, but this exercise defines it explicitly.

Keep the result as a zero-dimensional tensor so it can be added to a loss and differentiated. Preserve the input. No data loss is supplied, so return only the regularization penalty, not a combined loss or a gradient vector.

Example

For weights = [1, -2, 3] and lambda_ = 0.1, the squared weights sum to 1 + 4 + 9 = 14. The penalty is 0.1 / 2 * 14 = 0.7. Positive and negative weights contribute equally when their magnitudes are equal. Zero strength or all-zero weights gives zero penalty.

How it affects training

The derivative of this penalty with respect to a weight w is lambda_ * w. Adding it to a data loss therefore adds that term to the weight's gradient. The one-half in the penalty cancels the factor of two from differentiating the square.

This function computes a loss term. An optimizer's weight-decay setting acts during an update and is not an operation to perform here. Return the penalty without modifying the weights.