601. Run Gaussian Thompson sampling from fixed noise draws
Why it matters Thompson sampling is a standard way to explore ads, recommendations and prompt variants online.
Thompson sampling picks the arm whose randomly drawn plausible mean is highest, so uncertain arms still get tried. With a Gaussian model the draws are easy to make reproducible.
Write gaussian_thompson(rewards, z). rewards is a (T, K) array: rewards[t, k] is what arm k would pay at round t. z is a (T, K) array of standard normal draws. Each arm starts with n = 0 pulls and sum s = 0. At round t, arm k's posterior is Normal(mean = s_k / (n_k + 1), std = 1 / sqrt(n_k + 1)), from a Normal(0, 1) prior and unit noise. Its sample is mean + std * z[t, k]. Pull the arm with the largest sample (lowest index on ties), receive rewards[t, arm], and update that arm's n and s. Return (pulls, std) where pulls is the list of pulled arms and std is the numpy array of final posterior stds 1 / sqrt(n_k + 1).
def gaussian_thompson(rewards, z)Example 1
Input: rewards [[1, 0], [1, 0], [1, 0]], z [[0.2, 0.1], [0, 0.3], [0.1, 0.1]]
Output: ([0, 0, 0], array([0.5, 1.]))
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
The posterior std shrinks like one over the square root of the pull count plus one.
Hint 2
Start n and s at zero for every arm.
Hint 3
Posterior mean s / (n + 1), posterior std 1 / sqrt(n + 1).
Hint 4
Use np.argmax, which already breaks ties toward the lowest index.
Common mistakes
- Using variance where the std belongs.
- Updating every arm instead of only the pulled one.
Understand the idea
Thompson sampling handles explore versus exploit by imagination: for each arm, draw one guess of its true mean from what you currently believe, then act as if that guess were true. Arms you know little about have wide beliefs, so sometimes their guess wins and they get tried.
arm 0 has been pulled once and paid 1, so with a Normal(0, 1) prior its posterior mean is 1 / 2 = 0.5 and std 1 / sqrt(2) = 0.71. Arm 1 is unpulled: mean 0, std 1. With draws z = 0 and 0.3 the samples are 0.5 and 0.3, so we pull arm 0.
Rule (unit noise, Normal(0, 1) prior): mean = sum / (n + 1), std = 1 / sqrt(n + 1), sample = mean + std * z, pick the largest.
It is widely used for online A/B allocation of ads, recommendations and LLM prompt variants.
Topics
Companies2
- Meta the topic appears in interview reports Machine Learning interview questions, page 10 (KatKat)
- Microsoft the topic appears in interview reports Microsoft Senior Applied Scientist (L63) Interview Experience
From public interview reports and guides. Not affiliated with or endorsed by these companies.