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.

L1 Regularization Penalty

~10 mincode completion

L1 Regularization (Lasso)

L1 regularization adds a penalty proportional to the sum of absolute values of the weights:

Compared to L2 (Ridge):

| | L2 (Ridge) | L1 (Lasso) |

|---|---|---|

| Penalty | | |

| Effect | Shrinks weights evenly | Drives weights to exactly zero |

| Use case | General regularization | Feature selection / sparsity |

The L1 penalty encourages sparse solutions, many weights become exactly zero, which is useful for feature selection and model interpretability.

Your task:

Implement l1_penalty(W, lambda_) that returns the scalar L1 regularization term.

Example Tests

2x2 matrix, lambda=1

Input: {"W":[[1,-1],[2,-2]],"lambda_":1}

Expected: 6

Row vector, lambda=0.5 halves the sum

Input: {"W":[[1,2,3]],"lambda_":0.5}

Expected: 3

Zero weights: penalty is zero

Input: {"W":[[0,0,0]],"lambda_":1}

Expected: 0

Python
import numpy as np

def l1_penalty(W: np.ndarray, lambda_: float) -> float:
    """
    Compute the L1 regularization penalty.

    Args:
        W:       Weight matrix (any shape)
        lambda_: Regularization strength (>= 0)

    Returns:
        Scalar: lambda_ * sum(|W|)
    """
    # YOUR CODE HERE
    pass
Loading docs…