L1 Regularization Penalty

~10 mincode completion

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

Examples

2x2 matrix, lambda=1

Input
l1_penalty([[1, -1], [2, -2]], 1)
Output
6

Row vector, lambda=0.5 halves the sum

Input
l1_penalty([[1, 2, 3]], 0.5)
Output
3

Zero weights: penalty is zero

Input
l1_penalty([[0, 0, 0]], 1)
Output
0

Hints

Hint 1

Sum with , and check which axis you are summing over.

Hint 2

Reach for abs rather than squared values.

Requirements

  • : Weight matrix (any shape)

  • lambda_: Regularization strength (>= 0)

  • Return Scalar: lambda_ * sum(|W|)

Constraints

  • Allowed library: NumPy only

  • Time limit: 200 ms, Memory: 64 MB

Where this shows up

~10 min

8 employers weight this skill

4 frontier labs, 2 big tech firms, 1 autonomy company, 1 enterprise vendor. Top match scores 81.

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…

The AI Mentor needs an account

It reads your code and the failing tests and nudges you toward the fix without handing you the answer. Free accounts get it on every problem you're working on today.