Have a go at it. The editor and the docs panel are open, and your code is saved as you type. Running it needs a free account — you’ll come back to exactly what you wrote.

L2 Regularization Penalty

~10 mincode completion

L2 Regularization (Weight Decay)

L2 regularization discourages large weights by adding a penalty term to the loss:

where (lambda) controls regularization strength. This is equivalent to weight decay, weights are nudged toward zero at each step.

Effect: L2 spreads weight values smoothly. In contrast, L1 encourages exactly-zero weights (sparse solutions).

Your task:

Implement l2_penalty(weights, lambda_reg) that returns the L2 penalty term .

Example Tests

Standard case

Input: {"weights":[1,2,3],"lambda_reg":0.1}

Expected: 1.4

Zero weights: penalty = 0

Input: {"weights":[0,0,0],"lambda_reg":1}

Expected: 0

Sign does not matter: squares remove it

Input: {"weights":[-1,1,-1,1],"lambda_reg":0.5}

Expected: 2

Python
import numpy as np

def l2_penalty(weights: np.ndarray, lambda_reg: float) -> float:
    """
    Compute the L2 regularization penalty.

    Args:
        weights:    Weight vector (any shape)
        lambda_reg: Regularization strength (lambda)

    Returns:
        Scalar: lambda * sum(weights^2)
    """
    # YOUR CODE HERE
    pass
Loading docs…