BLOGLLM Logo
Go Pro
Guest
Not signed in
All BlogsCoursesPracticeInterview prepSeriesTagsBookmarksPricing
Log in
All BlogsCoursesPracticeTagsBookmarksPricing
My PrepProblemsStudy PlansResearch PapersRoadmapInterviewContestsLeaderboardGames
Articles
Practice / Debug and fix15 of 16 in topic

870. Fix inverted dropout with the wrong scale

EasyDebug and fix Pro

Why it matters Dropout scale bugs make training and inference behave differently, which shows up as a model that scores worse after you turn dropout off.

The starter code below runs, but it has a realistic bug. Read the spec, find the bug and fix it. Keep the function name and signature.

inverted_dropout(x, keep_mask, p, training=True) should apply inverted dropout: during training, zero the dropped units and divide the kept ones by (1 - p) so the expected value is unchanged. At inference (training=False) it returns x unchanged.

Inputs: x is a list or ndarray of any shape. keep_mask has the same shape with 1 for kept units and 0 for dropped ones (it is given so the test is deterministic). p is the drop probability, 0 <= p < 1.

Return an ndarray of floats with the shape of x. No rounding.

Functiondef inverted_dropout(x, keep_mask, p, training=True)

Example 1

Input: inverted_dropout([1.0, 2.0, 3.0, 4.0], [1, 0, 1, 1], 0.5)

Output: [2.0, 0.0, 6.0, 8.0]

Example 2

Input: x = [[2.0, 2.0]], keep_mask = [[1, 1]], p = 0.2, training = False

Output: [[2.0, 2.0]]

Constraints

  • Python 3 with NumPy. Code runs in your browser.
  • Run checks the sample tests. Submit checks the full hidden test set (Pro).
Hint 1

What is the expected value of x * mask?

Hint 2

Divide, do not multiply, during training.

Hint 3

At inference return x untouched.

Common mistakes
  • Scaling the dropped units too.
  • Using p instead of 1 - p.
  • Applying dropout at inference.
Understand the idea

Inverted dropout scales up at training time so nothing has to change at inference. If each unit is kept with probability 1 - p, dividing by 1 - p keeps E[out] = x. The buggy code multiplies by 1 - p, which is the old non-inverted style, and also scales at inference, so both modes are wrong.

Shapes and data flow
x and keep_mask: same shape.
Topics
Debug and fix
Similar questions
  • Fix the softmax that returns nanEasy
  • Fix the LayerNorm that normalises the wrong axisEasy
  • Fix the cross-entropy that returns infEasy
  • Fix the F1 score that crashes on empty predictionsEasy
All Debug and fix problems
Report
870 / 903
Python 3solution.pyPython idle
1
2
3
4
5
6
7
8
import numpy as np
​
def inverted_dropout(x, keep_mask, p, training=True):
x = np.asarray(x, dtype=float)
m = np.asarray(keep_mask, dtype=float)
out = x * m * (1 - p)
return out if training else x * (1 - p)
​

Run checks these cases in your browser, no sign-in needed. Submit checks the full hidden test set with Pro.

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