L2 Regularization Gradient
~10 mincode completion
Implement l2_gradient(weights, lambda_reg) that returns .
Examples
Standard gradient
- Input
- l2_gradient([1, 2, 3], 0.1)
- Output
- [0.2, 0.4, 0.6]
Zero weights: zero gradient
- Input
- l2_gradient([0, 0], 5)
- Output
- [0, 0]
lambda=0.5: 2*0.5=1 so gradient equals weights
- Input
- l2_gradient([-1, 2, -3], 0.5)
- Output
- [-1, 2, -3]
Hints
Hint 1
Work directly with the arguments weights, lambda_reg and return the result rather than printing it.
Hint 2
Do not forget to the factor of 2. That step is easy to skip.
Requirements
weights: Weight vector (any shape)lambda_reg: Regularization strength (lambda)Return Gradient vector: 2 lambda_reg weights
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 l2_gradient(weights: np.ndarray, lambda_reg: float) -> np.ndarray:
"""
Compute the gradient of the L2 penalty w.r.t. weights.
Args:
weights: Weight vector (any shape)
lambda_reg: Regularization strength (lambda)
Returns:
Gradient vector: 2 * lambda_reg * weights
"""
# YOUR CODE HERE
pass