L1 Regularization Gradient

~10 mincode completion

Implement l1_gradient(W, lambda_) that returns the gradient of the L1 penalty with respect to each element of .

Examples

Row vector with positive and negative entries, lambda=1

Input
l1_gradient([[1, -2, 3]], 1)
Output
[[1, -1, 1]]

Zero maps to zero; lambda=0.5 scales the result

Input
l1_gradient([[0, 5, -5]], 0.5)
Output
[[0, 0.5, -0.5]]

2x2 matrix with small lambda

Input
l1_gradient([[1, -1], [2, -2]], 0.1)
Output
[[0.1, -0.1], [0.1, -0.1]]

Hints

Hint 1

Work directly with the arguments , lambda_ and return the result rather than printing it.

Hint 2

Reach for sign W rather than l2 gradient 2W.

Requirements

  • : Weight matrix (any shape)

  • lambda_: Regularization strength

  • Return Gradient array of same shape as W: lambda_ * sign(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_gradient(W: np.ndarray, lambda_: float) -> np.ndarray:
    """
    Compute the gradient of L1 regularization w.r.t. each weight.

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

    Returns:
        Gradient array of same shape as W: lambda_ * sign(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.