L1 Regularization Penalty

Easy
~10 min
code 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

Sign in to solve this problem

You can read the full problem statement above. Create a free account to run code in the browser, submit solutions, and track your progress.