上下文老虎机:最好的动作取决于当前情境
Contextual bandits
在两个合成情境上运行disjoint LinUCB,用正确采样的回放日志评估冻结策略。
contextual-bandits“哪个按钮最好”可能问得不够具体
设一个推荐实验有两种可观察情境,出现频率相同。下表是合成奖励概率,不是真实用户数据:
| 情境 | 动作0 | 动作1 |
|---|---|---|
| 上下文0 | 0.8 | 0.3 |
| 上下文1 | 0.2 | 0.9 |
始终选动作0,期望奖励0.50;始终选动作1,期望奖励0.60。若上下文0选动作0,上下文1选动作1,期望奖励为0.85。缺少的不是更精确的全局平均,而是使用选择之前已经观察到的情境。
上下文老虎机(contextual bandit)先观察上下文,再选择动作,只收到该动作的奖励。Sutton与Barto将其介绍为学习情境与动作的关联;Li、Chu、Langford与Schapire的2010论文在推荐中形式化该问题,并给出LinUCB;Silver讲义明确了先情境、后动作的交互顺序。
特征描述动作发生前已知的内容
第t轮,为每个可选动作a观察d维特征向量x_(t,a)。特征可以描述情境、动作或二者交互。策略使用这些特征及过去选中反馈决定动作,不能把本轮结果提前放进输入。
在disjoint LinUCB中,每个动作有独立的一组未知系数theta_a,建模假设为条件均值奖励线性:
“disjoint”指动作之间不共享系数;在同一动作模型内,证据仍可在不同特征向量间泛化。教学实验中,两动作看到同样的one-hot向量:上下文0是[1,0],上下文1是[0,1]。两个独立坐标可以准确表示表格中的每一列。这个格外简单的模型不证明任意推荐奖励都是线性的。
为每个动作估计奖励模型
让D_a包含过去选中动作a时的特征行,y_a保存相应观测奖励。取正岭参数lambda,最小化平方误差加惩罚。展开梯度并令其为零,得到:
正lambda使A_a正定,即使尚无任何观测。初始零预测来自正则项与b_a=0,不是观察过失败。这里解线性系统,不显式构造逆矩阵。Li等人的独立模型使用相同的充分统计量结构,正则项为单位矩阵。
LinUCB选择预测均值加探索奖励最大的动作:
标量alpha≥0控制探索项。在当前设计矩阵中信息较少的特征方向,二次型较大。它不只是总拉取次数:同一方向上的两次观测,不一定能教会一个正交方向的奖励。
本演示将alpha作为调参。统计置信保证需要特征、噪声、参数大小及所选系数满足条件,单独写出这个平方根不会为任意自适应数据建立保证。分数可以超过Bernoulli奖励范围,不是裁剪后的概率。alpha为零时,规则变为按岭预测贪心选择。
选中动作a并观察奖励r后,只改变该动作的统计量:
这来自给D_a追加一行、给y_a追加一项;其他动作模型保持不变。零奖励仍要向A_a添加外积,因为它是一次观测,而不是缺失数据。
离线评估需要说明日志怎样产生
日志记录上下文、记录策略选择的动作及其观测奖励。目标策略可能选另一个动作,而对应奖励缺失。平均全部日志奖励是在评估记录策略;把未选结果当作零,则是在编造证据。
Li等人的回放方法在明确条件下提供简单解法:事件独立同分布,此处使用固定K个动作,并且日志动作均匀随机,与目标算法的随机化独立。对确定的冻结目标pi(x),只保留日志动作L与其匹配的事件。给定任意上下文和潜在奖励向量:
这里mathcal L表示概率分布。固定保留概率不改变上下文和目标奖励的分布。对学习中的策略,论文通过只在接受事件时更新保留历史来扩展论证;本程序评估冻结策略,没有实现那个自适应评估器。
为对应证明中的停止约定,应要求M个接受事件,而不是有限日志耗尽时悄悄改分母。若有足够长的独立同分布均匀日志流:
扫描次数的期望不保证在KM行后一定完成。有限实现会在流过早耗尽时报错。如果策略是观察同一评估集之后挑出来的,还需另行处理选择影响;这里先冻结策略,再用新种子评估。
非均匀匹配为什么可能有偏?
仍设两种上下文各占一半,目标按情境选择[0,1]。一个非均匀记录策略在两情境中分别以0.9和0.1概率匹配目标。保留下来的上下文比例变成0.9和0.1,所以:
增加行数不会消除这种偏差。非均匀日志需要适当校正,例如合适的拒绝采样,或满足覆盖假设的倾向概率评估。这些估计器不在本实现范围内;仅保存一个倾向概率字段,也不会自动校正不加权平均。
用选中奖励训练,用新日志评估
将程序保存为contextual.py,使用Python 3与NumPy运行。仓库检查环境采用NumPy 1.26.4。LinUCB对每个动作解两个线性系统,校验特征形状和有限性,只更新选中模型。合成环境、已知模型评估器与学习器各有明确职责。
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)))
import numpy as np
class LinUCB:
def __init__(self, arms, features, alpha=1., ridge=1.):
integer(arms, 'arms', 1); integer(features, 'features', 1)
self.alpha = finite(alpha, 'alpha', 0); ridge = finite(ridge, 'ridge', 0)
if ridge <= 0: raise ValueError('ridge must be positive')
self.A = np.repeat((ridge * np.eye(features))[None, :, :], arms, axis=0)
self.b = np.zeros((arms, features))
def features(self, x):
v = np.asarray(x, dtype=float)
if v.shape != self.b.shape or not np.isfinite(v).all(): raise ValueError('one finite feature vector per arm required')
return v
def scores(self, x, explore=True):
x = self.features(x); values = []
for a, v in enumerate(x):
theta = np.linalg.solve(self.A[a], self.b[a]); z = np.linalg.solve(self.A[a], v)
variance = float(v @ z)
if variance < -1e-10: raise ArithmeticError('positive-definite quadratic form failed')
values.append(float(v @ theta) + (self.alpha * math.sqrt(max(0., variance)) if explore else 0.))
return values
def select(self, x, explore=True):
return int(np.argmax(self.scores(x, explore)))
def observe(self, action, x, reward):
integer(action, 'action'); x = self.features(x); reward = finite(reward, 'reward', 0, 1)
if action >= len(self.b): raise ValueError('unknown action')
v = x[action]; self.A[action] += np.outer(v, v); self.b[action] += reward * v
def features(context):
integer(context, 'context')
if context not in (0, 1): raise ValueError('unknown context')
v = [0., 0.]; v[context] = 1.
return [list(v), list(v)]
def train(steps=2000, seed=0):
integer(steps, 'steps', 1); integer(seed, 'seed')
means = [[.8, .3], [.2, .9]]; contexts = random.Random(seed + 700001)
envs = [Bernoulli(row, seed + 1009 * c) for c, row in enumerate(means)]
learner = LinUCB(2, 2); loss = 0.; counts = [[0, 0], [0, 0]]
for _ in range(steps):
c = contexts.randrange(2); x = features(c); a = learner.select(x)
learner.observe(a, x, envs[c].pull(a)); counts[c][a] += 1
loss += max(means[c]) - means[c][a]
policy = [learner.select(features(c), explore=False) for c in range(2)]
return dict(policy=policy, counts=counts, pseudoregret=loss,
A=learner.A.tolist(), b=learner.b.tolist(),
predictions=[learner.scores(features(c), explore=False) for c in range(2)],
known_model_policy_value=sum(means[c][policy[c]] for c in range(2)) / 2)
def logged_events(size, seed):
integer(size, 'size'); integer(seed, 'seed')
rng = random.Random(seed + 700001); logger = random.Random(seed + 900001)
means = [[.8, .3], [.2, .9]]; envs = [Bernoulli(row, seed + c * 1009) for c, row in enumerate(means)]
for _ in range(size):
c = rng.randrange(2); a = logger.randrange(2)
yield c, a, envs[c].pull(a)
def replay(policy, events, accepted_target):
integer(accepted_target, 'accepted_target', 1)
if len(policy) != 2: raise ValueError('need two binary actions')
for a in policy:
integer(a, 'policy action')
if a not in (0, 1): raise ValueError('unknown policy action')
accepted = 0; total = 0.; scans = 0
for c, a, r in events:
integer(c, 'context'); integer(a, 'action'); r = finite(r, 'reward', 0, 1)
if c not in (0, 1) or a not in (0, 1): raise ValueError('invalid logged event')
scans += 1
if a == policy[c]:
accepted += 1; total += r
if accepted == accepted_target: return dict(accepted=accepted, scanned=scans, mean=total / accepted)
raise RuntimeError(f'log exhausted after {scans} rows with only {accepted} matches')
def demo():
runs = [train(seed=s) for s in range(12)]; policy = runs[0]['policy']
# This is fresh uniform logging, independent of training and policy selection.
evaluations = [replay(policy, logged_events(5000, 10000 + s), 400) for s in range(30)]
return dict(horizon=2000, seeds=list(range(12)), pseudoregret=summary([r['pseudoregret'] for r in runs]),
single_seed=runs[0], best_context_free_value=.6, context_oracle_value=.85,
replay=dict(policy=policy, target=400, seeds=list(range(10000, 10030)),
reward=summary([r['mean'] for r in evaluations]),
scans=summary([r['scanned'] for r in evaluations])),
biased_match_example=dict(target_value=.85, accepted_context_weights=[.9, .1], match_mean=.81))
if __name__ == '__main__':
import json
print(json.dumps(demo(), indent=2, allow_nan=False))
训练使用alpha1、ridge1、0—11共12个种子,每次2,000轮。上下文以二分之一概率采样;不同上下文、动作使用独立奖励流。在这些简单one-hot实例中,平均路径伪遗憾为3.05,标准误约0.988609,不代表一般LinUCB基准。种子0学习器的冻结贪心策略为[0,1],已知模型价值0.85;最佳不看上下文的价值为0.60。
独立评估用10000—10029的种子生成均匀日志,每次准确保留400个匹配事件。奖励估计均值为0.854,标准误约0.002417。平均扫描约804.933行,接近理论期望800。每条提供的流最多5,000行,这些运行均达到目标;若流耗尽,会报错,而不是把较短评估当作相同实验。
普通稠密求解O(d³),这里每轮扫描K个动作需O(Kd³)。更新一个外积O(d²),智能体保存O(Kd²)矩阵状态。one-hot例子很小,优化分解可减少重复工作,但当前代码没有宣称实现它们。冻结策略回放每个事件查一次表,在这个双上下文例子中仅需常数工作内存。
上下文必须可用,模型也必须适合
上下文老虎机建模即时奖励选择,不规划动作引起的未来外部状态变化。它仍会随时间学习,动作也改变收集到哪些信息。如果推荐会改变用户后续状态,而目标需要优化这些影响,即时奖励模型可能遗漏重要效果。
one-hot上下文允许分别估计,却不会自动泛化到未见情境。更丰富的特征可以泛化,错误线性模型也可能传播系统误差。共享或混合系数模型,是与本独立实现不同的选择。
均匀日志简化回放,但会丢弃许多行。真实日志可能有变化的动作集合、延迟结果、未记录的选择变量,或目标动作完全没有覆盖。迁移证明前应先核对这些条件。本文没有复现论文的Yahoo实验或其点击提升。
跟踪上下文怎样进入学习与评估
-
开头表格中,两个固定动作和最佳情境策略的期望奖励各是多少?
答案:固定动作0为
(0.8+0.2)/2=0.50,动作1为(0.3+0.9)/2=0.60;按上下文选[0,1]为(0.8+0.9)/2=0.85。 -
从
A=I、b=0开始,选中臂观察到特征[1,2]及奖励1,统计量和同一特征的预测均值怎样变化?答案:
A=[[2,2],[2,5]]、b=[1,2],解得系数[1/6,1/3],预测为1/6+2/3=5/6。另一个臂不变,探索项还要加在这个均值之外。 -
两动作均匀日志,要求400个接受事件,回放是否总在准确800行后停止?
答案:不是。800是期望扫描次数,匹配是随机的;应继续到接受400个事件,或报告有限日志耗尽。
-
非均匀记录策略为什么让例中结果为0.81,而不是0.85?
答案:匹配筛选保留上下文0的频率是上下文1的九倍,因此平均为
0.9×0.8+0.1×0.9=0.81,不是目标人群等权的0.85。应校正采样机制或用有依据的估计器,增加有偏样本不是修复办法。
学习与评估需要不同的证据
Li等人将逐臂岭模型连接到探索指数,并给出带明确日志条件的回放证明。工作稿与Silver讲义解释上下文怎样改变动作选择。以上原创程序在合成数据上核对机制;真实应用仍需分别为模型适用性、日志假设和奖励目标提供证据。
先判断,再看解释
日志不均匀选择动作,直接平均与目标策略匹配的奖励,保证无偏吗?
学习目标
- 计算逐臂岭估计,只更新选中的臂。
- 解释均匀日志下固定匹配数回放,展示非均匀筛选偏差。
先修与延伸
查看知识关联图 →参考文献
- A Contextual-Bandit Approach to Personalized News Article Recommendation
Lihong Li, Wei Chu, John Langford, Robert E. Schapire · 2010 - 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 PDF1 metadata/abstract,2§2.1,3§3.1 and5§4 including Algorithm3/Theorem1 proof; directly viewed4 Algorithm1 and§4 opening. Disjoint LinUCB and fixed accepted-count replay with i.i.d. events and uniform logging. Hybrid model and later experimental tables not audited; abstract12.5% is not a verified reproduction. Teaching alpha is a tuning parameter, not an unrestricted confidence guarantee. PDF60–61 §2.8 contextual action mapping and immediate-reward distinction from a full MDP. Read2026-09-23; implementation/replay sourced to Li2010. 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 disjoint ridge against batch regression and a hand inverse, chosen-only updates, shape domains, contextual versus fixed-action oracles, fixed accepted-count uniform replay, finite-log exhaustion and nonuniform matching bias. Toy alpha is a tuning parameter, not a general confidence guarantee.
- 核disjoint ridge对照批量回归和手算逆矩阵、仅选臂更新、形状定义域、情境与固定动作参照、固定接受数均匀回放、有限流耗尽及非均匀匹配偏差;教学alpha是调参,不是一般置信保证。
- 每题四张计算SVG,12数值/几何与30响应式组合通过;10张当前选定图核看,7张最终图直接查看,3张与此前所看图字节一致并实际核对;浏览器输入由插图前SHA绑定,完整页面验收另记。
核对的来源位置:
- A Contextual-Bandit Approach to Personalized News Article Recommendation · Read PDF1 metadata/abstract,2§2.1,3§3.1 and5§4 including Algorithm3/Theorem1 proof; directly viewed4 Algorithm1 and§4 opening. Disjoint LinUCB and fixed accepted-count replay with i.i.d. events and uniform logging. Hybrid model and later experimental tables not audited; abstract12.5% is not a verified reproduction. Teaching alpha is a tuning parameter, not an unrestricted confidence guarantee.
- Reinforcement Learning: An Introduction — second-edition working draft (2014–2015) · PDF60–61 §2.8 contextual action mapping and immediate-reward distinction from a full MDP. Read2026-09-23; implementation/replay sourced to Li2010.
- 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.
相关主题