CSI 4106 Introduction to Artificial Intelligence
Version: Nov 29, 2026 19:41
With supervised learning, we learn from labelled examples. Reinforcement learning takes a different approach: learning which actions work well from the rewards they produce. Monte Carlo Tree Search gives us a gentle introduction to this idea. With a simulator of the rules, we can try possible continuations and use their outcomes to choose a move. We will build on familiar tree search and random sampling, without developing the full machinery of reinforcement learning.
Lecture 16 introduced AlphaGo as an example of search in reasoning. Lecture 22 showed why full game-tree search becomes impractical.
Could we estimate a position’s value by playing out a few possible continuations?
A Monte Carlo method uses random samples to estimate a numerical quantity.
How could we estimate the quality of a move without examining every possible continuation?
For each completed simulation:
A policy is a rule for choosing an action.
| Term | Role in our MCTS |
|---|---|
| Tree policy | Guides traversal of the stored tree and determines where expansion occurs. |
| Rollout policy (default policy) | Chooses actions during the temporary continuation beyond the stored tree—randomly here. |
| Value function | Estimates a position’s expected return from a stated player’s perspective. |
MCTS is a textbook example of an any-time algorithm:
Like BFS, DFS, and A^\star, MCTS explores a search space incrementally.
Both A^\star and MCTS use evaluation criteria to guide search:
A heuristic supplies an estimate; a policy specifies how to choose an action.
Similar to Simulated Annealing and Genetic Algorithms, MCTS incorporates a mechanism to balance exploration and exploitation.
MCTS stores only part of the possible game tree:
The walkthrough uses numerical returns for one decision-maker, with C=2.
For tic-tac-toe, game.evaluate(state) always returns X’s utility:
| Terminal outcome | X’s utility |
|---|---|
| X wins | +1 |
| Draw | 0 |
| O wins | -1 |
For a visited child i, UCT uses
\operatorname{UCT}(i)=\overline V_i+C\sqrt{\frac{\ln N}{n_i}}.
Initially, the stored tree has one node, the root S_0.
In the walkthrough, we add its children before the first selection.
MCTS gradually grows this partial tree, revisiting existing nodes and adding descendants as search proceeds.
Each stored node records its total return and visit count.
Their ratio gives the mean return, used in the selection score.
Visit counts also determine the exploration bonus.
\operatorname{UCT}(i)=\overline V_i+C\sqrt{\frac{\ln N}{n_i}}.
Let N=100 and C=\sqrt2. The means use the parent’s perspective.
| Child | Visits n_i | Mean \overline V_i | UCT score |
|---|---|---|---|
| A | 90 | 0.7 | ? |
| B | 10 | 0.5 | ? |
Which child gets the next simulation? Which action would the visit-first final rule play?
UCT scores are approximately 1.020 for A and 1.460 for B. The next simulation goes to B; the final-action rule chooses A.
| Smaller C may help when… | Larger C may help when… |
|---|---|
| Current estimates are relatively reliable. | Early returns are noisy. |
| Promising actions are easy to distinguish. | Alternatives need more investigation. |
Could an intermediate value make better use of the available simulations?
After a completed simulation, MCTS can return its current recommendation.
Lecture 24 connects the four stages to code and investigates simulation budgets, exploration, and persistent search.
The multi-armed bandit problem repeatedly chooses among actions with uncertain returns.
For a minimization problem, let \Delta E=E_{\text{new}}-E_{\text{old}}.
p=\exp(-\Delta E/T).
| Simulated annealing | MCTS with UCT |
|---|---|
| One current search trajectory | A branching stored search structure |
| Temperature is explicitly scheduled | C can remain fixed |
| Worsening changes may be accepted | Under-sampled actions receive a selection bonus |
Child 2 is selected instead of child 1 when
\overline V_2+C\sqrt{\frac{\ln N}{n_2}}> \overline V_1+C\sqrt{\frac{\ln N}{n_1}}.
Equivalently,
\overline V_2-\overline V_1> C\left(\sqrt{\frac{\ln N}{n_1}}- \sqrt{\frac{\ln N}{n_2}}\right).
n_values = np.arange(1, 10_001)
plt.figure(figsize=(8, 4))
plt.plot(n_values, np.log(n_values), label=r"$\ln N$")
plt.xlabel("N")
plt.ylabel(r"$\ln N$")
plt.title("The numerator grows slowly; it does not decrease")
plt.grid(True)
plt.legend()
plt.tight_layout()
plt.show()
plt.close()
print("ln(100), ln(1000), ln(10000):", np.log([100, 1000, 10000]))ln(100), ln(1000), ln(10000): [4.60517019 6.90775528 9.21034037]
def plot_exploration_bonus(max_visits):
"""Plot the bonus where child visits do not exceed parent visits."""
visits = np.arange(1, max_visits + 1)
parent_visits, child_visits = np.meshgrid(visits, visits)
bonus = math.sqrt(2) * np.sqrt(
np.log(parent_visits) / child_visits
)
bonus = np.ma.masked_where(child_visits > parent_visits, bonus)
fig, ax = plt.subplots(figsize=(7, 4))
contour = ax.contourf(
parent_visits, child_visits, bonus, levels=15, cmap="viridis"
)
fig.colorbar(contour, ax=ax, label="Exploration bonus")
ax.set_xlabel("Parent visits N")
ax.set_ylabel("Child visits n")
ax.set_title(f"Bonus for 1 ≤ n ≤ N ≤ {max_visits}")
fig.tight_layout()
plt.show()
plt.close(fig)
plot_exploration_bonus(10)Estimate \int_0^\pi\sin(x)\,dx=2 by averaging sampled function values.
def monte_carlo_integrate_visual_with_sticks(
f, a, b, n_samples, seed=None, true_value=None
):
"""Show uniform samples and successive Monte Carlo estimates."""
rng = np.random.default_rng(seed)
xs = rng.uniform(a, b, size=n_samples)
ys = f(xs)
cumulative_avg = np.cumsum(ys) / np.arange(1, n_samples + 1)
estimates = (b - a) * cumulative_avg
fig, axes = plt.subplots(1, 2, figsize=(11, 4))
grid = np.linspace(a, b, 400)
axes[0].plot(grid, f(grid), color="black", label="f(x)")
axes[0].vlines(xs, 0, ys, color="gray", alpha=0.3, linewidth=1)
axes[0].scatter(xs, ys, s=12, color="blue", label="Samples")
axes[0].set_title("Monte Carlo samples")
axes[0].set_xlabel("x")
axes[0].set_ylabel("f(x)")
axes[1].plot(estimates, label="Monte Carlo estimate")
if true_value is not None:
axes[1].axhline(
true_value, linestyle="--", color="red", label="True value"
)
axes[1].set_title("Successive integral estimates")
axes[1].set_xlabel("Number of samples")
axes[1].set_ylabel("Estimate")
for ax in axes:
ax.grid(True)
ax.legend()
fig.tight_layout()
plt.show()
plt.close(fig)
return estimates[-1]
estimate = monte_carlo_integrate_visual_with_sticks(
np.sin, 0.0, math.pi, 500, seed=123, true_value=2.0
)
print(f"Final estimate: {estimate:.6f}; true value: 2.0")Final estimate: 1.994396; true value: 2.0
def monte_carlo_integrate(f, a, b, n_samples, seed=None):
"""Estimate an integral using independent uniform samples."""
rng = random.Random(seed)
total = 0.0
for _ in range(n_samples):
total += f(rng.uniform(a, b))
return (b - a) * total / n_samples
for n in (100, 1_000, 10_000, 100_000):
estimate = monte_carlo_integrate(math.sin, 0.0, math.pi, n, seed=0)
print(
f"n = {n:6d}; estimate = {estimate:.6f}; "
f"absolute error = {abs(2.0 - estimate):.6f}"
)n = 100; estimate = 2.080957; absolute error = 0.080957
n = 1000; estimate = 1.992136; absolute error = 0.007864
n = 10000; estimate = 2.007041; absolute error = 0.007041
n = 100000; estimate = 1.996149; absolute error = 0.003851
Marcel Turcotte
School of Electrical Engineering and Computer Science (EECS)
University of Ottawa