BLOGLLM Logo
Go Pro
Guest
Not signed in
All BlogsCoursesPracticeInterview prepSeriesTagsBookmarksPricing
Log in
All BlogsCoursesPracticeTagsBookmarksPricing
My PrepProblemsStudy PlansResearch PapersRoadmapInterviewContestsLeaderboardGames
Articles
Practice / Neural networks6 of 18 in topic

262. Add L1 and L2 penalties and their gradients to weight matrices only

EasyNeural networks
Asked atMicrosoft

Why it matters Weight decay configs in real training scripts always exclude biases and normalisation parameters.

Regularisation is usually applied to weights but not to biases. A clean helper makes that rule explicit.

Write regularize(params, l1, l2). params is a dict from a name to an array. Only names ending with ".weight" are penalised. Return (penalty, grads) where penalty = sum over weights of l1 * sum(|w|) + 0.5 * l2 * sum(w^2) as a float, and grads is a dict with the same keys: l1 * sign(w) + l2 * w for weights (sign(0) = 0) and zeros of the same shape for every other key.

Functiondef regularize(params, l1, l2)

Example 1

Input: params = {"fc.weight": [1, -2], "fc.bias": [3]}, l1 = 0.1, l2 = 0.5

Output: penalty 1.55 and grads {"fc.weight": [0.6, -1.1], "fc.bias": [0]}

Example 2

Input: params = {'a.weight': [[0.0, 2.0], [-1.0, 0.0]], 'a.bias': [1.0, 1.0], 'norm.scale': [5.0]}, l1 = 0.2, l2 = 0.0

Output: (0.6, {'a.weight': [[0.0, 0.2], [-0.2, 0.0]], 'a.bias': [0.0, 0.0], 'norm.scale': [0.0]})

Example 3

Input: params = {'x.weight': [0.5, -0.5, 3.0]}, l1 = 0.0, l2 = 0.1

Output: (0.475, {'x.weight': [0.05, -0.05, 0.3]})

Constraints

  • Python 3 with NumPy. Code runs in your browser.
  • Your code must pass all 3 tests to be accepted.
Hint 1

Loop over items; branch on name.endswith('.weight').

Hint 2

np.sign returns 0 at 0, which is the usual subgradient.

Hint 3

The 0.5 makes the L2 gradient exactly l2 * w.

Hint 4

Return zeros_like for skipped keys.

Common mistakes
  • Penalising biases.
  • Forgetting the 0.5 and getting 2 * l2 * w as the gradient.
Understand the idea

Penalties pull weights toward zero so the model does not lean too hard on any single feature. L1 pulls with a constant force, so small weights get pushed all the way to 0. L2 pulls in proportion to the weight, so big weights shrink fast and small ones barely move. Biases only shift outputs, so penalising them does not reduce overfitting.

Worked example

w = [1, -2], l1 = 0.1, l2 = 0.5. L1 part 0.1 * 3 = 0.3. L2 part 0.5 * 0.5 * 5 = 1.25. Total 1.55. Gradient: 0.1 * [1, -1] + 0.5 * [1, -2] = [0.6, -1.1].

penalty = l1 * sum|w| + 0.5 * l2 * sum w^2, grad = l1 * sign(w) + l2 * w

Training recipes for ResNets and transformers apply weight decay to weight matrices only, using exactly this kind of name filter.

Topics
Neural networks
Companies1
  • Microsoft the topic appears in interview reports Microsoft Machine Learning Engineer Interview Questions | Screna AI

From public interview reports and guides. Not affiliated with or endorsed by these companies.

Similar questions
  • Backward pass of a dense layerEasy
  • Compute Xavier and He initialisation scales for dense and conv weightsEasy
  • Count the parameters of an MLPEasy
  • Find where early stopping haltsEasy
All Neural networks problems
Report
262 / 903
Python 3solution.pyPython idle
1
2
3
4
5
6
import numpy as np
​
def regularize(params, l1, l2):
# your code here
pass
​

Run checks these cases in your browser, no sign-in needed. Submit checks all 3 tests.

Ctrl/Cmd + Enter to run
© BlogLLM, Bengaluru, IndiaAboutTermsPrivacyRefundsDMCAContactRSS