"""Independent NumPy multi-armed bandit exploration vs exploitation lab: epsilon-greedy, UCB, Thompson Sampling & decay."""
import json
import platform
import numpy as np
def epsilon_greedy_select(rng: np.random.Generator, q_values: np.ndarray, epsilon: float) -> int:
if rng.random() < epsilon:
return int(rng.integers(0, len(q_values)))
max_q = np.max(q_values)
best = np.where(q_values == max_q)[0]
return int(rng.choice(best))
class UCBBandit:
def __init__(self, n_actions: int, c: float = 2.0):
self.n_actions = n_actions
self.c = c
self.Q = np.zeros(n_actions, dtype=np.float64)
self.N = np.zeros(n_actions, dtype=np.int64)
self.total_steps = 0
def select_action(self, rng: np.random.Generator) -> int:
self.total_steps += 1
unvisited = np.where(self.N == 0)[0]
if len(unvisited) > 0:
return int(rng.choice(unvisited))
ucb = self.Q + self.c * np.sqrt(np.log(self.total_steps) / self.N)
return int(np.argmax(ucb))
def update(self, action: int, reward: float) -> None:
self.N[action] += 1
self.Q[action] += (reward - self.Q[action]) / self.N[action]
class ThompsonBandit:
def __init__(self, n_actions: int):
self.alpha = np.ones(n_actions, dtype=np.float64)
self.beta = np.ones(n_actions, dtype=np.float64)
self.N = np.zeros(n_actions, dtype=np.int64)
def select_action(self, rng: np.random.Generator) -> int:
samples = rng.beta(self.alpha, self.beta)
return int(np.argmax(samples))
def update(self, action: int, reward: int) -> None:
self.N[action] += 1
if reward == 1:
self.alpha[action] += 1.0
else:
self.beta[action] += 1.0
def run_cases():
cases = []
# 1. Epsilon-greedy sampling distribution & blind uniform exploration + tie-breaking
rng = np.random.default_rng(42)
q_demo = np.array([1.5, 2.8, 2.3])
n_draws = 12000
counts = np.zeros(3, dtype=np.int64)
for _ in range(n_draws):
counts[epsilon_greedy_select(rng, q_demo, epsilon=0.2)] += 1
freqs = counts / n_draws
# Theoretical: arm1 = 0.8 + 0.2/3 = 0.8667; arm0 = arm2 = 0.2/3 = 0.0667
tie_counts = np.zeros(3, dtype=np.int64)
for _ in range(3000):
tie_counts[epsilon_greedy_select(rng, np.array([2.0, 2.0, 1.0]), epsilon=0.0)] += 1
c1_ok = bool(
abs(freqs[1] - (0.8 + 0.2 / 3.0)) < 0.015
and abs(freqs[0] - freqs[2]) < 0.015
and tie_counts[2] == 0
and abs(tie_counts[0] / 3000.0 - 0.5) < 0.03
)
cases.append(dict(
name="epsilon_greedy_distribution_and_blind_exploration",
inputs=dict(q_values=[1.5, 2.8, 2.3], epsilon=0.2, n_draws=n_draws),
prerequisites="ε-贪心策略概率分配理论值校验、平局随机打破与盲目均匀探索验证",
action="验证 ε=0.2 时最优动作 1 频率接近 0.8667,且次优动作 2 与差动作 0 探索频率几乎相等(均约 0.0667)。",
expected=dict(arm1_freq_matches_theory=True, blind_equal_suboptimal_explore=True, tie_broken_evenly=True),
actual=dict(
arm1_freq_matches_theory=bool(abs(freqs[1] - (0.8 + 0.2 / 3.0)) < 0.015),
blind_equal_suboptimal_explore=bool(abs(freqs[0] - freqs[2]) < 0.015),
tie_broken_evenly=bool(tie_counts[2] == 0 and abs(tie_counts[0] / 3000.0 - 0.5) < 0.03),
),
measurements=dict(
empirical_freqs=[round(float(f), 4) for f in freqs],
tie_counts=tie_counts.tolist(),
),
passed=c1_ok,
))
# 2. UCB on 3-arm Bernoulli bandit [0.1, 0.5, 0.9], c=2, 1000 steps
rng2 = np.random.default_rng(2026)
true_3 = [0.1, 0.5, 0.9]
ucb3 = UCBBandit(n_actions=3, c=2.0)
tot_ucb3 = 0
for _ in range(1000):
a = ucb3.select_action(rng2)
r = 1 if rng2.random() < true_3[a] else 0
ucb3.update(a, r)
tot_ucb3 += r
c2_ok = bool(np.all(ucb3.N >= 1) and int(np.argmax(ucb3.N)) == 2 and tot_ucb3 > 750 and abs(ucb3.Q[2] - 0.9) < 0.05)
cases.append(dict(
name="ucb_three_arm_bandit_convergence",
inputs=dict(true_means=true_3, c=2.0, steps=1000),
prerequisites="三臂伯努利老虎机运行 UCB(c=2) 1000 步的计数、估值与总奖励验证",
action="验证所有臂均被探索、最优臂 2 占主导、Q[2] 收敛至 0.9 附近且总奖励高于 750。",
expected=dict(all_arms_visited=True, best_arm_dominant=True, reward_gt_750=True, q2_accurate=True),
actual=dict(
all_arms_visited=bool(np.all(ucb3.N >= 1)),
best_arm_dominant=bool(int(np.argmax(ucb3.N)) == 2),
reward_gt_750=bool(tot_ucb3 > 750),
q2_accurate=bool(abs(ucb3.Q[2] - 0.9) < 0.05),
),
measurements=dict(
total_reward=int(tot_ucb3),
arm_counts=ucb3.N.tolist(),
q_estimates=[round(float(v), 4) for v in ucb3.Q],
),
passed=c2_ok,
))
# 3. Thompson Sampling Beta(1,1) posterior update & low regret on 5-arm bandit
true_5 = np.array([0.1, 0.2, 0.8, 0.5, 0.3])
steps_5 = 2000
rng3 = np.random.default_rng(2026)
ts5 = ThompsonBandit(5)
ts_rew = 0
for _ in range(steps_5):
a = ts5.select_action(rng3)
r = 1 if rng3.random() < true_5[a] else 0
ts5.update(a, r)
ts_rew += r
post_means = ts5.alpha / (ts5.alpha + ts5.beta)
optimal_expected = float(steps_5 * np.max(true_5))
ts_regret = round(optimal_expected - ts_rew, 2)
c3_ok = bool(int(np.argmax(ts5.N)) == 2 and ts5.N[2] > 1700 and abs(post_means[2] - 0.8) < 0.04 and ts_rew > 1500)
cases.append(dict(
name="thompson_sampling_beta_posterior",
inputs=dict(true_means=true_5.tolist(), prior="Beta(1, 1)", steps=steps_5),
prerequisites="五臂老虎机上汤普森采样的 Beta 共轭后验更新与最优臂识别",
action="验证 2000 步后最优臂 2 被选超 1700 次、Beta 后验均值收敛至 0.8 附近且总奖励 >1500。",
expected=dict(best_arm_is_2=True, arm2_pulls_gt_1700=True, posterior_mean_accurate=True, total_reward_gt_1500=True),
actual=dict(
best_arm_is_2=bool(int(np.argmax(ts5.N)) == 2),
arm2_pulls_gt_1700=bool(int(ts5.N[2]) > 1700),
posterior_mean_accurate=bool(abs(post_means[2] - 0.8) < 0.04),
total_reward_gt_1500=bool(ts_rew > 1500),
),
measurements=dict(
total_reward=int(ts_rew),
expected_regret=ts_regret,
arm_counts=ts5.N.tolist(),
posterior_means=[round(float(v), 4) for v in post_means],
),
passed=c3_ok,
))
# 4. 5-arm comparison (static eps=0.1, decaying eps, UCB c=2, Thompson) + non-stationary adaptation
def eval_strategies(n_trials: int = 20):
totals = dict(eps_static=[], eps_decay=[], ucb_c2=[], thompson=[])
for seed in range(n_trials):
r_gen = np.random.default_rng(1000 + seed)
# Shared Bernoulli draw matrix for fair low-variance comparison across strategies
draws = (r_gen.random((steps_5, 5)) < true_5).astype(np.int64)
# Static eps=0.1
q_s, n_s = np.zeros(5), np.zeros(5, dtype=np.int64)
s_tot = 0
for t in range(steps_5):
a = epsilon_greedy_select(r_gen, q_s, 0.1)
rew = int(draws[t, a])
n_s[a] += 1
q_s[a] += (rew - q_s[a]) / n_s[a]
s_tot += rew
totals["eps_static"].append(s_tot)
# Decaying eps: 0.4 -> 0.01
q_d, n_d = np.zeros(5), np.zeros(5, dtype=np.int64)
d_tot = 0
for t in range(steps_5):
eps_t = max(0.01, 0.4 * (0.996 ** t))
a = epsilon_greedy_select(r_gen, q_d, eps_t)
rew = int(draws[t, a])
n_d[a] += 1
q_d[a] += (rew - q_d[a]) / n_d[a]
d_tot += rew
totals["eps_decay"].append(d_tot)
# UCB c=2
u = UCBBandit(5, c=2.0)
u_tot = 0
for t in range(steps_5):
a = u.select_action(r_gen)
rew = int(draws[t, a])
u.update(a, rew)
u_tot += rew
totals["ucb_c2"].append(u_tot)
# Thompson
ts = ThompsonBandit(5)
ts_tot = 0
for t in range(steps_5):
a = ts.select_action(r_gen)
rew = int(draws[t, a])
ts.update(a, rew)
ts_tot += rew
totals["thompson"].append(ts_tot)
return {k: round(float(np.mean(v)), 2) for k, v in totals.items()}
avg_rewards = eval_strategies(20)
# Non-stationary check: best arm swaps from arm 0 (0.85 -> 0.15) to arm 1 (0.15 -> 0.85) at step 500
rng_ns = np.random.default_rng(77)
def run_nonstationary(eps: float, alpha: float = 0.1):
q = np.zeros(2)
post_shift_rew = 0
for t in range(1000):
probs = [0.85, 0.15] if t < 500 else [0.15, 0.85]
a = epsilon_greedy_select(rng_ns, q, eps) if t >= 2 else t
r = 1 if rng_ns.random() < probs[a] else 0
q[a] += alpha * (r - q[a])
if t >= 600:
post_shift_rew += r
return post_shift_rew
ns_pure_greedy = run_nonstationary(eps=0.0)
ns_const_eps = run_nonstationary(eps=0.1)
c4_ok = (
avg_rewards["thompson"] > avg_rewards["eps_static"]
and avg_rewards["eps_decay"] > avg_rewards["eps_static"]
and avg_rewards["ucb_c2"] > 1350.0
and ns_const_eps > ns_pure_greedy + 100
)
cases.append(dict(
name="five_arm_strategy_comparison_and_decay",
inputs=dict(true_means=true_5.tolist(), steps=steps_5, trials=20, nonstationary_shift_step=500),
prerequisites="20 次重复对照比较静态/衰减 ε-贪心、UCB(c=2) 与汤普森采样,并测试非平稳环境持续探索",
action="验证衰减 ε-贪心与汤普森采样平均累积奖励高于静态 ε=0.1,且非平稳切换后保持 ε=0.1 显著胜过纯开采。",
expected=dict(thompson_beats_static=True, decay_beats_static=True, const_eps_adapts_nonstationary=True),
actual=dict(
thompson_beats_static=(avg_rewards["thompson"] > avg_rewards["eps_static"]),
decay_beats_static=(avg_rewards["eps_decay"] > avg_rewards["eps_static"]),
const_eps_adapts_nonstationary=(ns_const_eps > ns_pure_greedy + 100),
),
measurements=dict(
mean_2000step_rewards=avg_rewards,
nonstationary_post600_greedy=int(ns_pure_greedy),
nonstationary_post600_eps01=int(ns_const_eps),
),
passed=c4_ok,
))
payload = dict(
version=platform.python_version(),
numpy=np.__version__,
system=platform.system(),
cases=cases,
)
print(json.dumps(payload, ensure_ascii=False))
if __name__ == "__main__":
run_cases()
本例需在 Windows x64 CPU、CPython 3.12.14、NumPy 2.5.4、SciPy 1.18.1、scikit-learn 1.9.1、pandas 3.1.0、Matplotlib 3.11.2。 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程
运行环境:Windows x64 CPU、CPython 3.12.14、NumPy 2.5.4、SciPy 1.18.1、scikit-learn 1.9.1、pandas 3.1.0、Matplotlib 3.11.2。
入口文件:projects/ml-exploration-exploitation-lab/explore-exploration-exploitation.py
本地运行步骤快速上手
- 点击上方“保存源码”保存为
explore-exploration-exploitation.py,或下载右侧课程工程包。 - 确认本地已准备 Windows x64 CPU、CPython 3.12.14、NumPy 2.5.4、SciPy 1.18.1、scikit-learn 1.9.1、pandas 3.1.0、Matplotlib 3.11.2。。
- 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载
课程关联工程包(登记关联58章) · 含当前章节或实例 · mbskycom202612a449.zip
课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a468.zip