Estimate prediction uncertainty with Monte Carlo dropout

Why it matters MC dropout is a common low-cost way to flag uncertain predictions in medical imaging and active learning.

Keeping dropout switched on at test time and averaging many passes gives a cheap uncertainty estimate.

Write mc_dropout_predict(x, W1, b1, W2, b2, masks, p). x is (n, d), W1 (d, h), b1 (h,), W2 (h, k), b2 (k,). masks is a (T, h) array of 0/1 keep flags, one row per pass, shared by all samples in that pass. For pass t: H = relu(x @ W1 + b1) * masks[t] / (1 - p), probs = softmax(H @ W2 + b2) over classes. Return (mean_probs, entropy): mean_probs is the (n, k) average over passes and entropy is the (n,) value -sum(m * log(m)) of mean_probs (use 0 * log 0 = 0).

Signaturedef mc_dropout_predict(x, W1, b1, W2, b2, masks, p)

Example

x = [[1, 1]], W1 = I (2x2), b1 = [0, 0], W2 = [[2, 0], [0, 2]], b2 = [0, 0], masks = [[1, 0], [0, 1]], p = 0.5 gives mean_probs [[0.5, 0.5]] and entropy [0.6931].

Understand the idea

Normally dropout is switched off at test time. If you leave it on, each pass sees a slightly different sub-network. When the passes agree, the model is confident; when they disagree, it is unsure. It is like asking several friends the same question and noticing whether they give the same answer.

Tiny example: hidden H = [1, 1], two passes keep unit 1 then unit 2 with p = 0.5, so H becomes [2, 0] and [0, 2]. With W2 = 2I the logits are [4, 0] and [0, 4]. The softmaxes are about [0.98, 0.02] and [0.02, 0.98], averaging to [0.5, 0.5], entropy log 2 = 0.693: maximum doubt.

Rule: mean_p = (1/T) sum_t softmax(f(x; mask_t)), entropy = -sum mean_p * log mean_p.

It is used for uncertainty in active learning and safety checks where retraining an ensemble is too costly.

Shapes and data flow

x (n,d) -> H (n,h) * mask (h,) -> logits (n,k); mean over T passes -> (n,k)
solution.pyPython idle
Ctrl/Cmd + Enter runs sample tests

Run checks the first 2 tests. Submit checks all 3.

  • Sample 1: examplemc_dropout_predict([[1.0, 1.0]], [[1.0, 0.0], [0.0, 1.0]], [0.0, 0.0], [[2.0, 0.0], [0.0, 2.0]], [0.0, 0.0]...
  • Sample 2: three passesmc_dropout_predict([[1.0, 0.5], [0.2, -1.0]], [[1.0, -1.0, 0.5], [0.5, 1.0, -0.5]], [0.0, 0.1, 0.0], [[1.0,...
  • Test 3: all keptmc_dropout_predict([[2.0, -1.0]], [[1.0, 0.0], [0.0, 1.0]], [0.0, 0.0], [[1.0, 0.0], [0.0, 1.0]], [0.0, 0.0...