置信上界:不确定的臂为什么还能再试一次
Upper confidence bounds
由经验均值与不确定半径构造UCB1,核清初始化、全局时钟及gap倒数遗憾界。
ucb均值较低的臂,也可能值得下一次尝试
设两个臂分别拉了90次和10次,经验均值为0.55与0.40。第一个均值较高,但第二个依据的证据少得多。学习器应立即停止尝试它吗?
UCB1在各臂经验均值上加一个不确定半径。总计100次拉取后,两个半径约为0.3199与0.9597,指数约为0.8699与1.3597,因此选择第二个臂。奖励虽在[0,1],指数仍可以超过1:它是决策分数,不是奖励预测或裁剪后的概率。
Auer、Cesa-Bianchi与Fischer的2002论文给出UCB1及其有限时间期望遗憾界,Sutton与Barto解释更广泛的置信上界思想。这里采用原论文的具体系数和时钟约定,使实现与定理指向同一条规则。
先初始化,再给均值加半径
假设K≥2个臂,各臂内部奖励独立同分布、位于[0,1],不同臂的奖励序列也独立;臂a未知均值为mu_a。先各拉一次。此后n表示已经完成的总拉取次数,N_a(n)是该臂计数,hat_mu_a(n)是其经验均值。下一个动作为:
自然对数使用全局计数,分母使用局部计数。原论文图1明确将n定义为已经完成的次数。有些讲法以即将开始的轮次编号;不要在同一轨迹中偷偷换约定。这里精确同分时选择最小下标,尚未拉过的臂也先按下标顺序初始化。
平方根从哪里来?
对某个有界臂的固定前s个独立奖励,Hoeffding不等式给出两个单侧界:
让右侧等于n⁻⁴,解出半径:
这解释了分数的形式,却还没有证明随机、自适应样本计数下的置信结论。UCB选择会改变哪些奖励前缀被检查。论文定理1的证明处理了全部可能相关的前缀计数,而不是假装所选计数事先固定。
次优臂为什么会逐渐失去优势?
选一个最优臂a_*,对次优臂设Delta_a=mu_*−mu_a>0。如果已有很多样本的次优臂仍被选择,至少发生三件事之一:最优臂的经验均值异常低、该臂的均值异常高,或者其半径相对差距仍太大。在时域T内,满足下式便排除最后一种情况:
推理如下:若两种经验偏差都未发生,最优臂的上界指数高于其真均值,次优臂的指数则低于其真均值加两倍半径。当两倍半径已经放进差距,次优指数便不能超过最优指数。因此,后续额外选择必须由异常经验事件解释。
对每个时钟值n,最多考虑n²对前缀计数。两个量级为n⁻⁴的单侧概率合成至多2/n²,其总和有限。加上初始化和取整,可得论文的计数界:
分别乘差距再求和,得到期望遗憾保证:
它约束期望,不是承诺每次随机运行都满足该界。首项包含差距的倒数:均值越接近,虽然每次选错成本较小,区分它们却需要更多证据。Silver讲义PDF20底部定理却写成差距求和;原论文的陈述与证明解决了这个冲突。讲义上部的指数公式仍可用于理解。
该界依赖具体实例,接近同分时会较松;它并不是说所有臂都相等时实际遗憾发散。相等均值的差距为零,对遗憾贡献也为零。程序还接受单臂环境作为平凡零遗憾情形,与论文K≥2的定理分开。
奖励单位也是算法的一部分
若已知支持为[L,U]且U>L,先归一化奖励,再用这一形式的UCB1。等价地,在原单位下将半径乘奖励范围:
把归一化分数乘U−L再加L,即得到相同排序。如果奖励以几百为单位,却仍原样使用单位区间半径,探索规则就变了。高斯或重尾奖励需要适当方法与假设;公式长得相似,不会自动继承这个定理。
把时钟与指数组成直接打印出来
将这个标准库Python 3程序保存为ucb.py,运行python3 ucb.py。select先处理初始化,再调用scores;后者拒绝零计数输入,而不是把无穷大分数序列化。学习器只得到观测动作与奖励,合成均值[0.25,0.45,0.70]用于环境和评估器。
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 UCB1:
def __init__(self, arms):
integer(arms, 'arms', 1)
self.counts = [0] * arms; self.values = [0.] * arms
def scores(self):
n = sum(self.counts)
if not all(self.counts): raise ValueError('initialize every arm before computing finite scores')
return [q + math.sqrt(2 * math.log(n) / count) for q, count in zip(self.values, self.counts)]
def select(self):
for a, count in enumerate(self.counts):
if not count: return a
scores = self.scores()
return max(range(len(scores)), key=scores.__getitem__)
def observe(self, action, reward):
integer(action, 'action'); reward = finite(reward, 'reward', 0, 1)
if action >= len(self.values): raise ValueError('unknown action')
self.counts[action] += 1; self.values[action] += (reward - self.values[action]) / self.counts[action]
def regret_bound(means, horizon):
means = probabilities(means); integer(horizon, 'horizon', len(means))
gaps = [max(means) - x for x in means]
return 8 * math.log(horizon) * sum(1 / g for g in gaps if g > 0) + (1 + math.pi**2 / 3) * sum(gaps)
def run(seed, steps=800):
integer(steps, 'steps', 3); means = [.25, .45, .7]; env = Bernoulli(means, seed)
agent = UCB1(3); loss = 0.; rows = []
for t in range(steps):
scores = agent.scores() if all(agent.counts) else None
a = agent.select(); r = env.pull(a)
if t < 12: rows.append(dict(completed=t, counts=list(agent.counts), means=list(agent.values), scores=scores, action=a, reward=r))
agent.observe(a, r); loss += max(means) - means[a]
return dict(counts=agent.counts, estimates=agent.values, pseudoregret=loss, early=rows)
def demo():
runs = [run(s) for s in range(30)]; n = 100
means = [.55, .4]; counts = [90, 10]
return dict(horizon=800, seeds=list(range(30)), pseudoregret=summary([x['pseudoregret'] for x in runs]),
theorem_expected_bound=regret_bound([.25, .45, .7], 800), trivial_path_bound=800 * .45,
index_example=dict(completed=n, counts=counts, estimates=means,
radii=[math.sqrt(2 * math.log(n) / c) for c in counts],
scores=[q + math.sqrt(2 * math.log(n) / c) for q, c in zip(means, counts)]),
single_seed=runs[0])
if __name__ == '__main__':
import json
print(json.dumps(demo(), indent=2, allow_nan=False))
对0—29共30个种子,每次800次拉取,平均路径伪遗憾为40.63,标准误约1.34484。该实例的定理期望遗憾上界约335.7480。最大可能差距为0.45,所以更简单的路径界800×0.45=360也成立。观测均值低于理论界只能算一致性核对,不能证明定理。
前12次决策打印观察新奖励之前的计数、均值与分数。第四次决策记录中已有三次拉取,所有臂计数均为1,便于发现时钟偏移或误用当前奖励。
计算全部分数及最大值,每轮O(K);更新一个均值O(1)。智能体保存O(K)状态,短教学轨迹每保留一个检查点增加O(K)数据。m次、每次T轮的时间为O(mTK),包含分数扫描,而不只计算均值更新。
上界指数不是万能保险垫
定理假设固定奖励分布、有界且独立的抽样。非平稳性、相关反馈、有信息的删失或模型设定错误都可能破坏论证。经验区间逐渐变窄,不证明旧平均仍描述当前世界。
UCB会刻意重试看起来较差的臂,因此在短期简单实例上可能输给更激进的方法,同时在其假设模型类中保留有用保证。汤普森采样引入先验和后验采样,上下文老虎机可通过特征共享证据;它们的估计、假设和理论界需要分别说明。
相信曲线之前,先核半径
-
为什么计算有限分数之前必须处理没试过的臂?
答案:计数为零会导致半径除零,经验均值也无定义。各拉一次补齐实际观测,只初始化一个数字并不能替代。
-
两个臂各拉一次,奖励分别为1和0,按本文约定,下次指数中出现哪个对数?
答案:
ln(2),因为已完成两次拉取。分数为1+sqrt(2ln2)与sqrt(2ln2);若对数中误用某臂的局部计数,会错误地去掉探索项。 -
固定T,将一个正差距减半,次优计数界的首项怎样变化?
答案:
1/Delta²项变成四倍;再乘差距后,遗憾首项变成两倍。这解释了遗憾界为什么用差距倒数,而不是差距。 -
对
[0,100]奖励能否直接使用不变的实现,并保留同一定理?答案:不能。应先除以100归一化,或在原单位下把半径乘100。当前程序刻意拒绝
[0,1]之外的奖励,单纯移除检查不能修好算法单位。
置信论证还需要采样论证
Auer等人将集中不等式与自适应臂计数控制结合。教材工作稿介绍可调的更广泛UCB族,Silver将半径联系到乐观估计。本文实现原始单位区间UCB1,而非所有带UCB名字的方法。证明梗概遵循已读定理1的范围,没有实现UCB2或论文其他算法。
先判断,再看解释
很少被采样的臂经验均值较低,但UCB指数更高;UCB1选哪个?
学习目标
- 从已完成拉取计算指数,避免除零及混淆局部/全局计数。
- 说清随机有界奖励假设,区分定理与经验曲线。
先修与延伸
查看知识关联图 →参考文献
- Finite-time Analysis of the Multiarmed Bandit Problem
Peter Auer, Nicolò Cesa-Bianchi, Paul Fischer · 2002 - Reinforcement Learning: An Introduction — second-edition working draft (2014–2015)
Richard S. Sutton; Andrew G. Barto · 2015 - Lecture 9: Exploration and Exploitation
David Silver · 2015
版本1 · 编写状态: 已完成记录中的技术复核
查看技术检查记录(AI)
Codex · 2026-09-23 · Single AI author. Scoped reading: Read physical PDF1–3 and the Fact1/Theorem1 proof on8–9; directly viewed3. Fixed independent arm reward streams in[0,1], expected regret, initialization and completed-pull clock, inverse-gap bound and union over possible sample counts. No full UCB2/epsilon proof or original benchmark replication. PDF55–56 §2.6 UCB selection and limits; actual guarantee and clock convention follow Auer PDF3/8–9. Read2026-09-23; historical remarks are not current impossibility claims. 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. 7 paired equations and four explained exercises. Checked completed-pull clock, forced initialization, exact ties, mean-plus-radius arithmetic, inverse-gap expected bound, unit rescaling and count-derived loss. Within-arm IID and across-arm independence explicit; a fixed-prefix inequality is not treated as an adaptive confidence proof.
- 核已完成拉取时钟、初始化、同分、均值加半径、倒数gap期望界、单位缩放和计数损失;明确臂内i.i.d./跨臂独立,不把固定前缀不等式冒充自适应置信证明。
- 每题四张计算SVG,12数值/几何与30响应式组合通过;10张当前选定图核看,7张最终图直接查看,3张与此前所看图字节一致并实际核对;浏览器输入由插图前SHA绑定,完整页面验收另记。
核对的来源位置:
- Finite-time Analysis of the Multiarmed Bandit Problem · Read physical PDF1–3 and the Fact1/Theorem1 proof on8–9; directly viewed3. Fixed independent arm reward streams in[0,1], expected regret, initialization and completed-pull clock, inverse-gap bound and union over possible sample counts. No full UCB2/epsilon proof or original benchmark replication.
- Reinforcement Learning: An Introduction — second-edition working draft (2014–2015) · PDF55–56 §2.6 UCB selection and limits; actual guarantee and clock convention follow Auer PDF3/8–9. Read2026-09-23; historical remarks are not current impossibility claims.
- 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.
相关主题