汤普森采样:先抽一个可能的模型,再做选择
Thompson sampling
更新Beta-Bernoulli信念,采样成功概率,检验概率匹配并区分参数与结果。
thompson-sampling可能的成功率,不是想象出来的一次成功
两个陌生按钮都只返回0或1。开始时,对各自成功概率持独立均匀信念。试按钮0一次并成功后,它的后验均值变成三分之二,按钮1仍为二分之一。贪心规则此时会始终选按钮0,直到后续数据改变排序。
汤普森采样(Thompson sampling)问另一件事:若从当前信念为每个按钮抽一个可能的成功率,再选这个采样模型里较好的按钮,会怎样?按钮1仍可能赢得抽样。在此例中,按钮0以三分之二概率被选中,按钮1以三分之一概率被选中。
抽到的是0.63这类参数,不是虚构的0或1奖励。只有真实执行所选动作后得到的奖励才更新后验。Russo等人的教程特别强调这一区分,Silver探索讲义则将该规则解释为概率匹配。
更新信念、抽模型,再作一次决策
假设K个臂有固定但未知的Bernoulli成功概率theta_a。给定这些概率,各次及跨臂奖励独立。初始使用独立Beta先验,参数alpha_a,beta_a为正。单个臂的密度及归一化积分为:
alpha与beta必须严格为正,两者都为1时是均匀先验;它们不必是整数。该分布覆盖连续的成功概率,与只有两种结果的Bernoulli观测不同。
为什么成功会给alpha加一?
某臂观察到S次成功、F次失败时,Bernoulli似然将先验乘theta^S(1−theta)^F。合并指数得到:
只有被选臂产生新的奖励似然,所以在独立先验下,也只有它的参数改变。真实成功给alpha加一,真实失败给beta加一。未选臂既没有失败,也没有想象的观测。若参数在先验中相关,一个臂的反馈可能影响另一个臂,这个独立更新便不再代表完整后验。教程的Beta-Bernoulli例子明确采用独立模型。
Beta后验的均值和方差为:
均值来自对theta乘密度积分,得到B(alpha+1,beta)/B(alpha,beta)。同理,二阶矩为alpha(alpha+1)/[(alpha+beta)(alpha+beta+1)],减去均值平方即得方差。相同后验均值不代表相同不确定性:Beta(1,1)与Beta(10,10)均值都为二分之一,方差却分别是1/12和1/84。
动作分布来自整个后验
每轮为各臂采样一个参数,选最大样本对应的臂,观察真实奖励r,再只更新该臂:
独立连续Beta模型中,精确最大值同分的概率为零;有限精度代码仍需同分规则,这里在精确最大项中均匀抽取。若把参数样本换成后验均值,便得到另一种贪心算法。
设H为已观察历史。由于采样向量服从联合后验,选择某臂的概率等于该臂在后验中最优的概率:
这是指定贝叶斯模型内部的陈述。真实参数固定时,它不保证这一轮选到的臂确实最好。错误的先验或似然可能产生自信却错误的信念;概率匹配也没有声称最大化所有有限时域贝叶斯目标。
精确计算开头的概率
臂0成功一次后,后验为Beta(2,1),密度2x;臂1仍均匀分布,在x处的累积概率为x。对第一个样本积分:
这个结果恰好等于臂0后验均值,是均匀竞争者造成的特例。一般情况下,选择概率并不等于后验均值,也不等于把各均值归一化后的数值;所有竞争臂的后验分布都会参与。
信念抽样与奖励使用不同随机流
将这个标准库Python 3程序保存为thompson.py,运行python3 thompson.py。BetaAgent.select抽假设参数,observe接受真实二元奖励。实现拒绝小数奖励,因为采用的是Bernoulli似然;其他奖励模型需要相应更新,不能随意把小数当作成功计数,还称为同一模型。
import math
import random
import statistics
def integer(x, name, minimum=0):
if isinstance(x, bool) or not isinstance(x, int) or x < minimum:
raise ValueError(name + ' must be an integer >= ' + str(minimum))
return x
def finite(x, name, low=None, high=None):
if isinstance(x, bool) or not isinstance(x, (int, float)) or not math.isfinite(x):
raise ValueError(name + ' must be finite')
if (low is not None and x < low) or (high is not None and x > high):
raise ValueError(name + ' is outside its domain')
return float(x)
def probabilities(values):
p = [finite(v, 'probability', 0, 1) for v in values]
if not p:
raise ValueError('at least one arm is required')
return p
class Bernoulli:
"""The learner receives only pull(action), never the mean vector."""
def __init__(self, means, seed):
self._means = probabilities(means)
integer(seed, 'seed')
self._streams = [random.Random(seed + 104729 * a) for a in range(len(means))]
def pull(self, action):
integer(action, 'action')
if action >= len(self._means):
raise ValueError('unknown action')
return int(self._streams[action].random() < self._means[action])
def summary(values):
if len(values) < 2:
raise ValueError('at least two independent runs are needed for an SE')
return dict(mean=statistics.mean(values), se=statistics.stdev(values) / math.sqrt(len(values)))
class BetaAgent:
def __init__(self, arms, seed, prior=(1., 1.)):
integer(arms, 'arms', 1); integer(seed, 'seed')
if len(prior) != 2: raise ValueError('need two prior parameters')
a, b = [finite(x, 'prior', 0) for x in prior]
if min(a, b) <= 0: raise ValueError('prior parameters must be positive')
self.alpha = [a] * arms; self.beta = [b] * arms; self.rng = random.Random(seed)
def select(self, method='sample'):
if method == 'sample': values = [self.rng.betavariate(a, b) for a, b in zip(self.alpha, self.beta)]
elif method == 'mean': values = [a / (a + b) for a, b in zip(self.alpha, self.beta)]
else: raise ValueError('unknown posterior decision rule')
best = max(values)
return self.rng.choice([i for i, v in enumerate(values) if v == best])
def observe(self, action, reward):
integer(action, 'action'); reward = finite(reward, 'Bernoulli reward', 0, 1)
if action >= len(self.alpha) or reward not in (0., 1.): raise ValueError('need an existing arm and a binary reward')
self.alpha[action] += reward; self.beta[action] += 1 - reward
def moments(self):
return [dict(mean=a / (a + b), variance=a * b / ((a + b)**2 * (a + b + 1))) for a, b in zip(self.alpha, self.beta)]
def run(seed, method='sample', steps=800):
integer(steps, 'steps', 1); means = [.25, .45, .7]; env = Bernoulli(means, seed)
agent = BetaAgent(3, seed + 1000003); counts = [0] * 3; loss = 0.
for _ in range(steps):
a = agent.select(method); r = env.pull(a); agent.observe(a, r)
counts[a] += 1; loss += max(means) - means[a]
return dict(counts=counts, alpha=agent.alpha, beta=agent.beta, moments=agent.moments(), pseudoregret=loss)
def demo():
toy = BetaAgent(2, 51); toy.observe(0, 1)
selected = [toy.select() for _ in range(20000)]
comparisons = {name: summary([run(s, name)['pseudoregret'] for s in range(30)]) for name in ['sample', 'mean']}
return dict(horizon=800, seeds=list(range(30)), comparisons=comparisons,
posterior_example=dict(alpha=toy.alpha, beta=toy.beta, moments=toy.moments(),
draws=20000, sampled_probability_arm0=selected.count(0) / len(selected),
exact_probability_arm0=2 / 3), single_seed=run(0))
if __name__ == '__main__':
import json
print(json.dumps(demo(), indent=2, allow_nan=False))
开头后验实验作20,000次决策,但不收集新反馈,因此后验一直是Beta(2,1)与Beta(1,1)。种子51下,臂0被选频率为0.6635,接近精确概率2/3。单纯抽参数不能使模型更确定。
学习实验使用原创Bernoulli均值[0.25,0.45,0.70]、均匀先验、800轮及0—29共30个种子。参数随机化与逐臂奖励流分开。后验采样的平均路径伪遗憾为11.81,标准误约1.14172;后验均值贪心为54.1933,标准误约16.3361。这些是该实例的有限模拟结果,不是教程报告的实验,也不是普遍优越性定理。与相邻UCB、epsilon例子不同,这里没有强制每臂初始各拉一次,比较时必须计入这项协议差异。
每次决策抽K个Beta样本并扫描,保存O(K)参数,更新选中臂O(1)。称总时间O(K),需将分布抽样视作单位成本操作;标准库采样使用拒绝方法,内部随机抽取次数没有固定的最坏常数。模拟保存汇总与最终参数,而不是每条完整轨迹。
信念不确定性不能代替模型检查
Beta-Bernoulli共轭使本例容易计算;连续奖励、相关臂、变化中的概率与延迟结果都需要其他模型或明确近似。强先验可能主导有限数据,反复用想象奖励更新只会制造确定性,不会增加信息。
UCB在有界奖励假设下构造频率学派指数,汤普森采样根据后验随机决策。“贝叶斯”一词或一条学习曲线,都不能保证信念校准、有限时域最优规划或部署成功。上下文老虎机加入观测特征;忽略它们可能把不同奖励群体混成一个臂均值。
分清参数、观测与决策
-
从Beta(1,1)开始,某臂依次得到
1,0,1,后验和均值是什么?答案:Beta(3,2),均值3/5。两次成功给alpha加二,一次失败给beta加一;其他独立臂不变。
-
为什么Beta(2,1)样本超过独立均匀样本的概率为2/3?
答案:给定第一个样本x,均匀样本较小的概率为x;按密度
2x平均,从零到一积分2x²,得到2/3。 -
没观察奖励,连续调用
select20,000次,alpha和beta应改变吗?答案:不应改变。这些决策依据同一份证据。用采样参数或想象结果更新,会把不存在的数据计入后验并扭曲不确定性。
-
两个Beta后验均值相同、集中程度不同,均值贪心能否相同对待它们,而汤普森采样表现不同?
答案:可以。均值贪心只看均值,参数采样使用整个分布;不同方差影响它们超过其他臂的频率。选择概率还取决于竞争者,不能只看孤立臂的方差。
分清教程版本与主张
这里使用Russo等人明确的arXiv v3,日期为2020年7月;元数据另记2017预印本、2018期刊出版。实际核读覆盖Beta-Bernoulli构造和早期例子,并未涵盖整本教程的应用或后文定理。Silver讲义提供概率匹配视角。本文采用成功给alpha加一的约定,另一讲法即使改了参数名,也不能误把更新方向反过来。
先判断,再看解释
Beta-Bernoulli汤普森采样在选臂前抽取什么?
学习目标
- 只更新被选臂,推导其Beta后验矩。
- 解释概率匹配及其与后验均值贪心的区别。
先修与延伸
查看知识关联图 →参考文献
- A Tutorial on Thompson Sampling — arXiv v3
Daniel J. Russo, Benjamin Van Roy, Abbas Kazerouni, Ian Osband, Zheng Wen · 2020 - Lecture 9: Exploration and Exploitation
David Silver · 2015
版本1 · 编写状态: 已完成记录中的技术复核
查看技术检查记录(AI)
Codex · 2026-09-23 · Single AI author. Scoped reading: Read PDF1 and13–16 of explicit2020-07-14 arXivv3; metadata separately records first preprint2017 and journal2018. Beta-Bernoulli updating, parameter rather than outcome samples, probability matching and reported simulation conditions. Figure3.1 was not visually inspected; neither the10000-run experiments nor later theory chapters were replicated/audited. Author teaching page dates the course2015, not its2025 upload. Read PDF1,3–20,22,24–25,28,30,33; directly viewed20. Its bottom regret formula uses gaps instead of inverse gaps; use Auer Theorem1, not this slide, for the bound. Constant exploration, probability matching and contextual feedback only; no universal TS optimality claim. Alpha/beta success conventions follow Russo, not the reversed slide28/30 labels. Link-only, no slide reuse. 6 paired equations and four explained exercises. Checked positive priors, selected-only binary feedback, posterior moments by exact polynomial integration, parameter versus reward draws, probability matching, seeded control and posterior-mean greedy comparison. Repeated draws do not count as feedback; no universal Bayesian optimality claim.
- 核正先验、仅选臂二元反馈、多项式精确积分后验矩、参数与奖励抽样、概率匹配、固定种子控制及均值贪心对照;重复抽样不当新反馈,不宣称普遍贝叶斯最优。
- 每题四张计算SVG,12数值/几何与30响应式组合通过;10张当前选定图核看,7张最终图直接查看,3张与此前所看图字节一致并实际核对;浏览器输入由插图前SHA绑定,完整页面验收另记。
核对的来源位置:
- A Tutorial on Thompson Sampling — arXiv v3 · Read PDF1 and13–16 of explicit2020-07-14 arXivv3; metadata separately records first preprint2017 and journal2018. Beta-Bernoulli updating, parameter rather than outcome samples, probability matching and reported simulation conditions. Figure3.1 was not visually inspected; neither the10000-run experiments nor later theory chapters were replicated/audited.
- Lecture 9: Exploration and Exploitation · Author teaching page dates the course2015, not its2025 upload. Read PDF1,3–20,22,24–25,28,30,33; directly viewed20. Its bottom regret formula uses gaps instead of inverse gaps; use Auer Theorem1, not this slide, for the bound. Constant exploration, probability matching and contextual feedback only; no universal TS optimality claim. Alpha/beta success conventions follow Russo, not the reversed slide28/30 labels. Link-only, no slide reuse.
相关主题