1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387
| import numpy as np import scipy.stats as stats import matplotlib.pyplot as plt import matplotlib.style as style
style.use('seaborn-v0_8-whitegrid')
class BernoulliBandit: def __init__(self, n_arms, seed=None): self.rng = np.random.default_rng(seed) self.p = self.rng.uniform(0.0, 1.0, size=n_arms) self.n_arms = n_arms
def pull(self, arm): return 1 if self.rng.random() < self.p[arm] else 0
def ucb1(n_arms, steps, bandit, alpha=3.0, seed=None, record_ucb=True): """ UCB1: 选择 argmax_a [ mean[a] + sqrt(alpha * ln(t) / (2 * n[a])) ] alpha 常用 3.0,也可调节探索强度 """ rng = np.random.default_rng(seed)
counts = np.zeros(n_arms, dtype=int) means = np.zeros(n_arms, dtype=float) actions = np.zeros(steps, dtype=int) rewards = np.zeros(steps, dtype=float)
if record_ucb: mean_hist = np.zeros((steps, n_arms), dtype=float) delta_hist = np.zeros((steps, n_arms), dtype=float) ucb_hist = np.zeros((steps, n_arms), dtype=float) else: mean_hist = delta_hist = ucb_hist = None
t = 0 for a in range(n_arms): if t >= steps: break r = bandit.pull(a) counts[a] += 1 means[a] = r actions[t] = a rewards[t] = r
if record_ucb: delta = np.sqrt(alpha * np.log(t + 1) / (2 * counts)) ucb = means + delta mean_hist[t] = means delta_hist[t] = delta ucb_hist[t] = ucb t += 1
for t in range(t, steps): delta = np.sqrt(alpha * np.log(t) / (2 * counts)) ucb = means + delta
if record_ucb: mean_hist[t] = means delta_hist[t] = delta ucb_hist[t] = ucb
a = int(np.argmax(ucb)) r = bandit.pull(a)
counts[a] += 1 means[a] += (r - means[a]) / counts[a]
actions[t] = a rewards[t] = r
return actions, rewards, counts, means, mean_hist, delta_hist, ucb_hist
def thompson_sampling(n_arms, steps, bandit, seed=None, record_posteriors=True): """ Thompson Sampling: 为每个臂维护一个 Beta 分布。 """ rng = np.random.default_rng(seed)
beta_params = np.ones((n_arms, 2), dtype=float) actions = np.zeros(steps, dtype=int) rewards = np.zeros(steps, dtype=float)
if record_posteriors: posterior_hist = np.zeros((steps, n_arms, 2), dtype=float) else: posterior_hist = None
for t in range(steps): samples = rng.beta(beta_params[:, 0], beta_params[:, 1])
if record_posteriors: posterior_hist[t] = beta_params.copy()
a = int(np.argmax(samples)) r = bandit.pull(a)
beta_params[a, 0] += r beta_params[a, 1] += (1 - r)
actions[t] = a rewards[t] = r counts = (beta_params[:, 0] + beta_params[:, 1] - 2).astype(int) estimated_means = beta_params[:, 0] / (beta_params[:, 0] + beta_params[:, 1])
return actions, rewards, counts, estimated_means, posterior_hist
def plot_ucb1_results(bandit, actions, rewards, counts, mean_hist, ucb_hist): """ 功能强大的可视化函数,为每个臂单独绘制 UCB 演化图。 """ T = len(rewards) n_arms = bandit.n_arms true_p = bandit.p best_arm = np.argmax(true_p) time_steps = np.arange(1, T + 1) colors = plt.cm.viridis(np.linspace(0, 1, n_arms))
n_plots = n_arms + 2 n_cols = 2 n_rows = int(np.ceil(n_plots / n_cols))
fig, axes = plt.subplots(n_rows, n_cols, figsize=(16, 4 * n_rows)) axes = axes.flatten() fig.suptitle('UCB1 Algorithm Analysis (Individual Arm View)', fontsize=20)
for a in range(n_arms): ax = axes[a] ax.axhline(y=true_p[a], color='gray', ls=':', lw=2, label=f'True p={true_p[a]:.3f}') ax.plot(time_steps, mean_hist[:, a], color=colors[a], ls='-', label='Estimated Mean') ax.fill_between(time_steps, mean_hist[:, a], ucb_hist[:, a], color=colors[a], alpha=0.3, label='Uncertainty (UCB-Mean)')
title = f'Arm {a} Analysis' if a == best_arm: title += ' (Best Arm)' ax.set_facecolor('gold') ax.patch.set_alpha(0.15) ax.set_title(title) ax.set_xlabel('Time Steps') ax.set_ylabel('Value') ax.legend(loc='lower right') ax.grid(True, which='both', linestyle='--', linewidth=0.5)
ax_regret = axes[n_arms] best_p = true_p.max() instant_regret = best_p - true_p[actions] cumulative_regret = np.cumsum(instant_regret)
ax_regret.plot(time_steps, cumulative_regret, color='crimson') ax_regret.set_title('Cumulative Pseudo-Regret Over Time') ax_regret.set_xlabel('Time Steps') ax_regret.set_ylabel('Cumulative Regret') ax_regret.text(T * 0.05, cumulative_regret[-1] * 0.8, f'Total Regret: {cumulative_regret[-1]:.2f}', fontsize=12)
ax_counts = axes[n_arms + 1] arm_indices = np.arange(n_arms) bar_colors = [colors[i] for i in arm_indices] bars = ax_counts.bar(arm_indices, counts, color=bar_colors, edgecolor='black') ax_counts.set_title('Total Pull Counts per Arm') ax_counts.set_xlabel('Arm Index') ax_counts.set_ylabel('Number of Pulls') ax_counts.set_xticks(arm_indices) ax_counts.bar_label(bars, label_type='edge') bars[best_arm].set_color('gold') bars[best_arm].set_edgecolor('black') ax_counts.legend([bars[best_arm]], [f'Best Arm ({best_arm})'])
for i in range(n_plots, len(axes)): axes[i].axis('off')
plt.tight_layout(rect=[0, 0, 1, 0.96]) plt.savefig("source/_drafts/多臂老虎机问题/ucb1.png") plt.show()
def plot_thompson_sampling_results(bandit, actions, rewards, counts, posterior_hist, title=None): """ Visualizes the results of the Thompson Sampling algorithm.
- For each arm: plots the evolution of the Beta posterior distribution at different time steps. - Plots the cumulative pseudo-regret over time. - Plots the total pull counts for each arm. Args: bandit (BernoulliBandit): The bandit environment. actions (np.array): The sequence of actions taken. rewards (np.array): The sequence of rewards received. counts (np.array): The final pull counts for each arm. posterior_hist (np.array): History of posterior parameters (alpha, beta) for each arm. title (str, optional): The main title for the plot. """ T = len(rewards) n_arms = bandit.n_arms true_p = bandit.p best_arm = np.argmax(true_p) time_steps = np.arange(1, T + 1) arm_colors = plt.cm.viridis(np.linspace(0, 1, n_arms))
n_plots = n_arms + 2 n_cols = 2 if n_arms > 1 else 1 n_rows = int(np.ceil(n_plots / n_cols))
fig, axes = plt.subplots(n_rows, n_cols, figsize=(16, 4 * n_rows)) axes = axes.flatten() fig.suptitle(title or 'Thompson Sampling Analysis', fontsize=20)
if T > 10: t_points = np.logspace(1, np.log10(T - 1), num=4, dtype=int) else: t_points = np.linspace(0, T - 1, num=min(T, 4), dtype=int) time_colors = plt.cm.cividis_r(np.linspace(0.2, 1, len(t_points))) x_pdf = np.linspace(0, 1, 300)
for a in range(n_arms): ax = axes[a] ax.axvline(true_p[a], color='black', ls='--', lw=2, label=f'True p={true_p[a]:.3f}') for i, t in enumerate(t_points): alpha, beta = posterior_hist[t, a] if alpha > 0 and beta > 0: pdf = stats.beta.pdf(x_pdf, alpha, beta) ax.plot(x_pdf, pdf, color=time_colors[i], label=f't={t+1}')
plot_title = f'Arm {a}: Posterior Distribution' if a == best_arm: plot_title += ' (Best Arm)' ax.set_facecolor('gold') ax.patch.set_alpha(0.15)
ax.set_title(plot_title) ax.set_xlabel('Success Probability p') ax.set_ylabel('Probability Density') ax.set_xlim(0, 1) ax.set_ylim(bottom=0) ax.legend(loc='upper right') ax.grid(True, which='both', linestyle='--', linewidth=0.5)
ax_regret = axes[n_arms] best_p = true_p.max() instant_regret = best_p - true_p[actions] cumulative_regret = np.cumsum(instant_regret)
ax_regret.plot(time_steps, cumulative_regret, color='crimson') ax_regret.set_title('Cumulative Pseudo-Regret Over Time') ax_regret.set_xlabel('Time Steps') ax_regret.set_ylabel('Cumulative Regret') ax_regret.text(T * 0.05, cumulative_regret[-1] * 0.8, f'Total Regret: {cumulative_regret[-1]:.2f}', fontsize=12) ax_regret.grid(True)
ax_counts = axes[n_arms + 1] arm_indices = np.arange(n_arms) bars = ax_counts.bar(arm_indices, counts, color=arm_colors, edgecolor='black') ax_counts.set_title('Total Pull Counts per Arm') ax_counts.set_xlabel('Arm Index') ax_counts.set_ylabel('Number of Pulls') ax_counts.set_xticks(arm_indices) ax_counts.bar_label(bars, label_type='edge') bars[best_arm].set_color('gold') bars[best_arm].set_edgecolor('black') ax_counts.legend([bars[best_arm]], [f'Best Arm ({best_arm})'])
for i in range(n_plots, len(axes)): axes[i].axis('off')
plt.tight_layout(rect=[0, 0, 1, 0.96]) plt.savefig("source/_drafts/多臂老虎机问题/ts.png") plt.show()
if __name__ == "__main__": N = 4 T = 5000 bandit = BernoulliBandit(n_arms=N, seed=0)
actions, rewards, counts, means, mean_hist, delta_hist, ucb_hist = ucb1( n_arms=N, steps=T, bandit=bandit, alpha=3.0, seed=0, record_ucb=True )
best_arm = int(np.argmax(bandit.p)) best_p = bandit.p[best_arm] total_reward = rewards.sum() regret = T * best_p - total_reward
print("True p per arm:", np.round(bandit.p, 3)) print("Best arm:", best_arm, "best p:", round(best_p, 3)) print("Pull counts:", counts) print("Estimated means:", np.round(means, 3)) print("Total reward:", int(total_reward)) print("Pseudo-regret (from true p):", round(regret, 2))
plot_ucb1_results(bandit, actions, rewards, counts, mean_hist, ucb_hist)
actions, rewards, counts, estimated_means, posterior_hist = thompson_sampling( n_arms=N, steps=T, bandit=bandit, seed=0, record_posteriors=True )
best_arm = int(np.argmax(bandit.p)) best_p = bandit.p[best_arm] total_reward = rewards.sum() regret = T * best_p - total_reward
print("Algorithm: Thompson Sampling") print("True p per arm:", np.round(bandit.p, 3)) print("Best arm:", best_arm, "best p:", round(best_p, 3)) print("Total pull counts:", counts) print("Estimated means (from posteriors):", np.round(estimated_means, 3)) print("Total reward:", int(total_reward)) print("Pseudo-regret:", round(regret, 2))
plot_thompson_sampling_results( bandit=bandit, actions=actions, rewards=rewards, counts=counts, posterior_hist=posterior_hist, title="Thompson Sampling Analysis" )
|