পাঠ ১০ · ৩২-এর মধ্যে · মডিউল ২

Monte Carlo methods — অভিজ্ঞতা থেকে শেখা

Monte Carlo methods — learning from complete episodes
৭ মিনিট পড়া উচ্চ · Advanced Python কোডসহ

এই পাঠে যা শিখবেন

  • MC prediction (V/Q evaluation) — sample average থেকে
  • First-visit বনাম every-visit MC — কোনটি কখন
  • MC control — ε-soft policy, exploring starts
  • Off-policy MC — importance sampling-এর pre-cursor

১ · Why MC — DP-এর সীমা

Value iteration, policy iteration — দু'টোই $P, R$ require করে। বাস্তব problem-এ ($P, R$ unknown):

  • Robot — physics complete model নেই।
  • Game — opponent unknown।
  • Recommendation — user behavior model নেই।

MC সমাধান — episode চালিয়ে অভিজ্ঞতা থেকে শেখা।

MC-এর central idea

$V^\pi(s) = \mathbb{E}_\pi[G_t \mid s_t = s]$। Expectation = sample average — যথেষ্ট sample হলে।

২ · First-visit MC prediction

Algorithm:

  1. Initialize $V(s) = 0$, $Returns(s) = []$ ∀$s$।
  2. প্রতি episode generate: $s_0, a_0, r_1, s_1, \ldots, s_T$।
  3. প্রতিটি state $s$-এর first occurrence-এ — return $G$ compute, append to $Returns(s)$।
  4. $V(s) = \text{mean}(Returns(s))$।

৩ · Every-visit MC

First-visit only first occurrence count করে। Every-visit — প্রতিটি occurrence count। Subtle:

  • First-visit: unbiased estimator।
  • Every-visit: biased কিন্তু consistent (sample বাড়লে → true)।
  • Practical-এ — every-visit সাধারণত more sample-efficient।

৪ · Incremental update

Sample list রাখা memory-costly। Running mean:

$$V_n(s) = V_{n-1}(s) + \frac{1}{n}[G - V_{n-1}(s)]$$

বা constant step:

$$V(s) \leftarrow V(s) + \alpha [G - V(s)]$$

$\alpha$ constant হলে — non-stationary tracking সম্ভব।

Episode trajectory → Returns G_t $s_0$ a₀ r₁=2 $s_1$ a₁ r₂=4 $s_2$ a₂ r₃=6 $s_3$ a₃ r₄=10 $s_T$ terminal প্রতিটি state-এর return ($\gamma=0.9$): G_3 = r_4 = 10 G_2 = r_3 + γ·G_3 = 6 + 0.9·10 = 15.0 G_1 = r_2 + γ·G_2 = 4 + 0.9·15 = 17.5 G_0 = r_1 + γ·G_1 = 2 + 0.9·17.5 = 17.75 প্রতিটি state-এ — সেই step থেকে শুরু করে এই episode-এর return। অনেক episode-এর গড় = $V^\pi(s)$ estimate।
এক episode-এর trajectory + প্রতিটি state-এর return G_t। অনেক episode-এর average → V^π estimate।

৫ · Python — first-visit MC prediction

Python · First-visit MC
import numpy as np
from collections import defaultdict

# Toy: 5-state random walk
# s_0 - s_1 - s_2 - s_3 - s_4 (terminal +1)
# random walk policy
n_states = 5
gamma = 1.0  # episodic, terminal +1

def episode():
    s = 2  # start middle
    traj = []
    while s not in [0, 4]:
        a = np.random.choice([-1, 1])
        s_next = s + a
        r = 1.0 if s_next == 4 else 0.0
        traj.append((s, r))
        s = s_next
    return traj

V = np.zeros(n_states)
returns = defaultdict(list)
np.random.seed(0)

for _ in range(5000):
    traj = episode()
    G = 0
    visited = set()
    # backward through trajectory
    for (s, r) in reversed(traj):
        G = r + gamma * G
        if s not in visited:  # first-visit
            returns[s].append(G)
            visited.add(s)

for s in range(1, 4):
    V[s] = np.mean(returns[s])

print("First-visit MC V estimate:")
for s in range(n_states):
    print(f"  V({s}) = {V[s]:.3f}")
# True values: 1/4, 2/4, 3/4 — analytical solution.

    
Random walk-এ V analytical: 1/4, 2/4, 3/4 — terminal-এর কাছে probability বেশি জিতার। MC estimate এই value-এর close — ৫০০০ episode যথেষ্ট।

৬ · MC control — Q estimation

$V$ থেকে policy বের করা যায় না (model-free)। তাই $Q$ estimate করতে হবে। MC control:

  1. Episode generate using current $\pi$।
  2. Each (s, a) first-visit-এ — $G$ compute, $Q(s, a)$ update।
  3. $\pi$ improve: $\pi(s) = \arg\max_a Q(s, a)$।

সমস্যা: greedy improvement-এ — কিছু (s, a) কখনো sampled হয় না। এই জন্য:

৭ · Exploring starts ও ε-soft policies

Exploring starts (ES): initial state ও action uniformly random। তত্ত্বে কাজ করে কিন্তু practical-এ infeasible।

ε-soft policies: $\pi(a|s) \ge \epsilon/|A|$ ∀$s, a$। সব action positive probability — সব sampled।

ε-greedy ε-soft-এর special case।

৮ · Off-policy MC ও importance sampling

Behavior policy $b$ (data collect) ≠ target policy $\pi$ (evaluate)। Importance sampling ratio:

$$\rho = \prod_t \frac{\pi(a_t | s_t)}{b(a_t | s_t)}$$

$V^\pi(s) \approx \mathbb{E}_b[\rho \cdot G]$।

Importance sampling ratio variance বিশাল — long horizon-এ explode। তাই off-policy MC stable নয়। TD এই সমস্যা কমায়।

৯ · MC vs DP — comparison

Python · Properties summary
# DP (Value Iteration):
#   - Model required (P, R)
#   - Bootstrap: V(s) updated from V(s')
#   - Synchronous full sweep
#   - Bias: low, Variance: low

# MC:
#   - Model-free
#   - No bootstrap: G is full return
#   - Episode-based, sample
#   - Bias: zero (first-visit), Variance: high
#   - Continuing task-এ কাজ করে না

# TD (পরের পাঠে):
#   - Model-free
#   - Bootstrap: V(s) updated from V(s')
#   - Online, single transition
#   - Bias: small, Variance: medium
print("MC vs DP — fundamental trade-off in model use ও variance.")

    
MC unbiased কিন্তু high variance। TD low variance কিন্তু biased। প্রকৃত RL এ দু'টোর সমন্বয় (n-step, TD(λ)) ব্যবহৃত হয়।

ভাবনার প্রশ্ন

প্র ০১First-visit বনাম every-visit MC — bias কেন আলাদা?

First-visit: প্রতি episode-এ এক state-এর প্রথম occurrence-এর return collect। Independent sample, unbiased।

Every-visit: এক episode-এ একই state বহুবার appear করলে — সব occurrence count। sample correlated (একই episode-এ)। Bias আছে।

Bias source: later visit-এর return earlier visit-নির্ভর। তাই i.i.d. না।

কিন্তু — sample বাড়লে bias → 0 (consistent)। Practice-এ — every-visit কম episode-এ converge।

Sutton-Barto (1998): দু'টিরই asymptotic same MSE।

প্র ০২MC কেন continuing task-এ কাজ করে না?

MC return $G_t = \sum_{k=0}^{T-t} \gamma^k r_{t+k+1}$ — episode শেষ ($T$) পর্যন্ত। continuing task-এ $T = \infty$।

সমস্যা:

  • সম্পূর্ণ return কখনো দেখা যায় না।
  • Update wait — স্থায়ী।
  • Online learning impossible।

সমাধান:

  • Truncate at $T_{\max}$ — bias আনে।
  • TD methods — bootstrap, episode-শেষ চাই না।
  • $n$-step return — limited horizon।
প্র ০৩Importance sampling-এর variance explosion কেন?

$\rho_T = \prod_{t=0}^{T-1} \pi(a_t|s_t)/b(a_t|s_t)$ — products of ratios।

যদি প্রতিটি ratio ~ 2 — $T = 100$ হলে $\rho = 2^{100}$। বিশাল variance।

Practical implications:

  • Off-policy MC long horizon-এ unusable।
  • Weighted importance sampling — slightly biased কিন্তু stable।
  • TD-এর off-policy version (Q-learning) এই issue কম।

কেন TD better: single-step IS ratio — variance bounded। multi-step trajectory product নয়।

প্র ০৪Blackjack-এ MC কেন popular textbook example?

Sutton-Barto Blackjack example — MC-এর perfect fit:

  • Episodic: প্রতি hand independent।
  • Short: 2-5 step max — IS variance manageable।
  • State space ছোট: ~200 states।
  • Reward sparse: +1/-1/0 only end — pure MC fit।
  • Model unknown technically: deck statistics complex — MC easier।

Discovery: MC-এ trained agent — basic strategy chart-এর সাথে match। MC সঠিক optimal policy পায়।

মূল উপলব্ধি: MC short-horizon episodic problem-এ excellent। MDP-এর প্রথম practical algorithm — production-এ rarely, কিন্তু educational গুরুত্বপূর্ণ।

অনুশীলন

  1. Compute G: trajectory $r_1=1, r_2=2, r_3=3, r_4=4$ (terminal)। $\gamma=0.9$। $G_0, G_1, G_2$ কত?

    $G_2 = 4$। $G_1 = 3 + 0.9 \cdot 4 = 6.6$। $G_0 = 2 + 0.9 \cdot 6.6 = 7.94$। (এখানে $r_1$ মানে state s_0 থেকে শুরু করে first reward).

    Wait — let me redo: $G_t = r_{t+1} + \gamma r_{t+2} + \ldots$। তাই $G_3 = r_4 = 4$। $G_2 = r_3 + \gamma G_3 = 3 + 3.6 = 6.6$। $G_1 = r_2 + \gamma G_2 = 2 + 5.94 = 7.94$। $G_0 = r_1 + \gamma G_1 = 1 + 7.146 = 8.146$।

  2. First vs every visit: trajectory s_0, s_1, s_0, s_1, s_2 (terminal)। state s_0-এর first-visit count vs every-visit count?

    First-visit: 1 sample (first occurrence at t=0)। Every-visit: 2 sample (t=0 ও t=2)।

  3. Code modify: উপরের MC-এ — every-visit MC implement করুন।
    for (s, r) in reversed(traj):
        G = r + gamma * G
        returns[s].append(G)  # no `visited` check

    প্রতিটি occurrence count — visited set বাদ।

আরও পড়ুন

পূর্ববর্তী পাঠ
পাঠ ০৯ · Policy Iteration