Turn MCTS visit counts into a move policy with temperature

Why it matters Self-play agents like AlphaZero sample opening moves from this distribution and train their policy head toward it.

After a tree search, the root's visit counts say which moves the search liked. Self-play systems turn them into a probability distribution, sharpened or flattened by a temperature.

Write visits_to_policy(counts, tau). counts is a list of non-negative ints with at least one positive.
- If tau == 0: return a one-hot array on the most visited move (lowest index on ties).
- Otherwise: pi_i = counts_i ** (1 / tau) / sum_j counts_j ** (1 / tau). Compute it stably in log space so large counts with small tau do not overflow; moves with 0 visits get probability 0.
Return a numpy float array.

Signaturedef visits_to_policy(counts, tau)

Example

visits_to_policy([10, 30, 60], 1.0) gives array([0.1, 0.3, 0.6]).

Understand the idea

Monte Carlo tree search visits good moves more often, so the visit counts at the root are a better policy than the raw network guess. Temperature controls how strictly we follow them: high temperature spreads probability around for exploration, low temperature concentrates it on the top move.

Example: counts [10, 30, 60] at tau 1 give [0.1, 0.3, 0.6]. At tau 0.5 we square the counts first: [100, 900, 3600] out of 4600, so about [0.022, 0.196, 0.783], much sharper.

Rule: pi_i = N_i^(1/tau) / sum_j N_j^(1/tau); tau = 0 means pick argmax N.

In self-play training, early moves of each game use tau = 1 for variety and later moves use tau near 0. The policy network is trained with cross-entropy toward this pi.

solution.pyPython idle
Ctrl/Cmd + Enter runs sample tests

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

  • Sample 1: examplevisits_to_policy([10, 30, 60], 1.0)
  • Sample 2: sharpenvisits_to_policy([10, 30, 60], 0.5)
  • Test 3: flattenvisits_to_policy([1, 4, 0, 16], 2.0)
  • Test 4: greedy tiesvisits_to_policy([5, 9, 9], 0)
  • Test 5: overflowvisits_to_policy([800, 799, 3], 0.01)