L2 Regularization Penalty
~10 mincode completion
Implement l2_penalty(weights, lambda_reg) that returns the L2 penalty term .
Examples
Standard case
- Input
- l2_penalty([1, 2, 3], 0.1)
- Output
- 1.4
Zero weights: penalty = 0
- Input
- l2_penalty([0, 0, 0], 1)
- Output
- 0
Sign does not matter: squares remove it
- Input
- l2_penalty([-1, 1, -1, 1], 0.5)
- Output
- 2
Hints
Hint 1
Sum with , and check which axis you are summing over.
Hint 2
Do not forget to lambda scaling. That step is easy to skip.
Requirements
weights: Weight vector (any shape)lambda_reg: Regularization strength (lambda)Return Scalar: lambda * sum(weights^2)
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_penalty(weights: np.ndarray, lambda_reg: float) -> float:
"""
Compute the L2 regularization penalty.
Args:
weights: Weight vector (any shape)
lambda_reg: Regularization strength (lambda)
Returns:
Scalar: lambda * sum(weights^2)
"""
# YOUR CODE HERE
pass