模仿学习:学会示范动作,为什么还会越走越偏?
Imitation learning
比较行为克隆与DAgger,亲自算出训练集零错误怎样变成闭环偏离,并审计专家查询预算。
imitation-learning预测下一步动作,不等于走完一段路
让新手看一批驾驶录像,再问“这个画面应该向哪边打方向”,属于监督学习。但新手真正开车后,前一次转向会改变下一帧画面。录像里的车总在路中间,新手却可能已经压线;此时即使录像上的预测准确率很高,也没回答怎样回到路中间。
模仿学习用示范行为学习决策。行为克隆(behavior cloning,BC)直接学观察到动作的映射;交互式模仿还会让学习者访问状态,请专家补充示范。逆强化学习先推断能解释行为的奖励,再规划策略,是另一种路线。模仿不要求每条示范都有数值奖励,也不意味着示范者总是最优。
关键区别是训练数据来自谁走出的路。BC主要看专家访问的状态;部署时需要在自己访问的状态上行动。DAgger把后者加入训练集,针对的是这个分布变化。分布与数据集聚合
本篇原创小任务只保留这条因果链:车有两条车道,16步后结束,车道0是目标。动作0保持车道,动作1翻转车道;每步有0.1概率发生额外翻转。示范者在车道0保持,在车道1修正。学习者使用“时间、车道”查表,没有图像识别或神经网络。
先看两个专家回合,共32个标签。所有已见状态的动作都记对,并不意味着所有恢复状态都见过。种子0下,BC在训练标签上零错误,部署时预计有6.05629步偏离车道;专家只有1.6步。下面会算出这个差别,而不是把“误差累积”当一句口号。
把示范误差与闭环代价分开
设示范集为状态与专家动作的配对。随机策略可用负对数似然训练;连续动作也可选回归损失,但平方误差会学条件均值,多个可行操作的均值未必可行。例如左右绕行都安全,平均成直行可能撞上障碍。必须先判断动作分布是否多峰,再选模型和损失。BC实现中的目标
本程序的标签确定,采用表格多数票最小化经验0-1错误;平票和未见状态都选0。这与上式属于同一直接模仿思路,但不是一次神经网络交叉熵训练。
令任务长度为T,策略访问第t步状态的分布为dπ的第t个分量。时间平均分布与专家分布上的动作错误率定义如下;时间相关任务可以把时间放进状态。
这是总体分布误差,不是有限训练集上的错误比例。若每步任务成本在0到1之间,最坏情况下,一次偏离会影响全部剩余步骤。把第t步之前首次偏离的概率用(t−1)ε一类的并合界控制,再逐步累计,就会得到二次量级。原论文采用的保证为:误差界条件
这个上界可能很松,不表示每个任务都会按平方增长。状态可快速恢复时,错误后果小得多。为了看清缺少的条件,设u上界控制“在学习者访问的状态偏离专家一步,再一直跟随专家”的额外成本;令εL是学习者自身分布上的动作错误率。逐步替换策略、使中间成本相消,可得:
这里Q是成本而非奖励;u可能随T增长。DAgger并没有删除任务的不可恢复性,也没有凭空证明u很小。
DAgger每轮用混合策略采集轨迹,对访问的每个状态请求专家标签,将新旧配对一起训练。混合系数控制执行谁的动作;即使执行学习者动作,标签仍应是专家对当时状态的回答。
并集在这里表示保留重复样本的聚合,不是去重后的集合。原论文将问题联系到无悔在线学习;条件涵盖损失、混合衰减和采样,并给出序列中存在好候选的结论,算法还建议验证选迭代。不能把它改写成“任何分类器训练六轮,最后一个策略必好”。本实验固定返回末轮,没有用评价结果选策略。算法3.1与保证范围
在本任务中,正确意图使下一步偏离概率为p,错误意图使它变为1−p。因此无需近似即可得到:
代入T=16、p=0.1和εL=0.348148,正好得到6.05629。示范者最优这一说法用于本例p小于0.5的条件;若执行器更可能翻转,控制问题就变了。
同样的标签预算,比较访问了哪些状态
程序只用Python标准库。先收集两个专家回合;接着比较两种扩充方式:DAgger每轮4个混合回合,β依次为1、1/2、1/4、1/8、1/16、1/32;专家增量基线每轮再采4个纯专家回合。两臂用对应的执行噪声流,混合随机数独立。每次都重拟合全部累计标签,评价使用精确概率传播,不额外采样真实回合。
"""Original finite recovery task: tabular BC and data aggregation. Python 3.11+."""
import json
import random
def expert(state):
return state[1] # action 1 flips the lane; lane 0 is desired
def validate(horizon, noise):
if not isinstance(horizon, int) or horizon < 1 or not 0 <= noise <= 1:
raise ValueError('Positive integer horizon and noise in [0,1] required')
def fit(data, horizon):
"""Empirical 0-1 risk minimizer; ties/unseen states choose action 0."""
counts = [[[0, 0] for lane in range(2)] for t in range(horizon)]
for (t, lane), label in data:
if not 0 <= t < horizon or lane not in (0, 1) or label not in (0, 1):
raise ValueError('Invalid labeled state')
counts[t][lane][label] += 1
policy = [[int(row[1] > row[0]) for row in step] for step in counts]
return policy, counts
def collect(policy, episodes, noise, beta, env_rng, mix_rng):
"""Query every visited state; beta changes execution, never the label."""
horizon = len(policy)
validate(horizon, noise)
if not 0 <= beta <= 1 or not isinstance(episodes, int) or episodes < 1:
raise ValueError('Invalid collection budget or mixture')
data, trace = [], []
for episode in range(episodes):
lane = 0
for t in range(horizon):
state = (t, lane)
label = expert(state)
intended = label if mix_rng.random() < beta else policy[t][lane]
flipped = int(env_rng.random() < noise)
next_lane = lane ^ intended ^ flipped
data.append((state, label))
trace.append(dict(episode=episode, state=list(state), label=label,
intended=intended, actuator_flip=flipped, next_lane=next_lane))
lane = next_lane
return data, trace
def evaluate(policy, noise):
"""Exact forward probabilities, used only for diagnostics, never for fitting."""
validate(len(policy), noise)
occupancy = [1.0, 0.0]
cost = mistakes = 0.0
for t, actions in enumerate(policy):
next_occupancy = [0.0, 0.0]
for lane, mass in enumerate(occupancy):
if actions[lane] not in (0, 1):
raise ValueError('Binary action required')
mistakes += mass * (actions[lane] != expert((t, lane)))
for flip, chance in ((0, 1 - noise), (1, noise)):
next_occupancy[lane ^ actions[lane] ^ flip] += mass * chance
cost += next_occupancy[1]
occupancy = next_occupancy
return dict(cost=cost, learner_distribution_error=mistakes / len(policy))
def train(seed=0, horizon=16, noise=.1, rounds=6, episodes_per_round=4):
validate(horizon, noise)
if not isinstance(rounds, int) or rounds < 0:
raise ValueError('Nonnegative round count required')
zero = [[0, 0] for _ in range(horizon)]
initial, initial_trace = collect(zero, 2, noise, 1., random.Random(seed), random.Random(seed + 1000))
bc, initial_counts = fit(initial, horizon)
data = list(initial)
more_expert = list(initial)
dagger = bc
expert_augmented = bc
curve, traces = [], []
env_rng, mix_rng = random.Random(seed + 2000), random.Random(seed + 3000)
# The comparison uses equal per-round actuator noise streams and equal queries.
reference_env, reference_mix = random.Random(seed + 2000), random.Random(seed + 4000)
for i in range(rounds):
beta = .5 ** i
fresh, trace = collect(dagger, episodes_per_round, noise, beta, env_rng, mix_rng)
data.extend(fresh)
extra, reference_trace = collect(zero, episodes_per_round, noise, 1., reference_env, reference_mix)
more_expert.extend(extra)
dagger, counts = fit(data, horizon)
expert_augmented, _ = fit(more_expert, horizon)
curve.append(dict(round=i + 1, beta=beta, labels=len(data),
dagger=evaluate(dagger, noise), expert_augmented=evaluate(expert_augmented, noise)))
traces.append(dict(dagger=trace, expert_augmented=reference_trace))
expert_policy = [[0, 1] for _ in range(horizon)]
return dict(seed=seed, horizon=horizon, noise=noise,
bc=evaluate(bc, noise), dagger=evaluate(dagger, noise),
expert_augmented=evaluate(expert_augmented, noise), expert=evaluate(expert_policy, noise),
initial_labels=len(initial), final_labels=len(data),
training_transitions_per_arm=len(data), final_policy=dagger,
initial_policy=bc, initial_counts=initial_counts,
known_training_error=sum(dagger[t][lane] != label for (t, lane), label in data) / len(data),
curve=curve, initial_trace=initial_trace, traces=traces)
def experiment(seed=0):
return train(seed)
if __name__ == '__main__':
result = experiment()
print(json.dumps({k: v for k, v in result.items() if k not in ('initial_trace', 'traces', 'initial_counts')}, indent=2))
查看运行摘要
{
"seed": 0,
"horizon": 16,
"noise": 0.1,
"bc": {
"cost": 6.0562949953421334,
"learner_distribution_error": 0.34814804651110415
},
"dagger": {
"cost": 1.680000000000001,
"learner_distribution_error": 0.00625
},
"expert_augmented": {
"cost": 1.920000000000001,
"learner_distribution_error": 0.02500000000000001
},
"expert": {
"cost": 1.6000000000000003,
"learner_distribution_error": 0.0
},
"initial_labels": 32,
"final_labels": 416,
"training_transitions_per_arm": 416,
"final_policy": [
[
0,
0
],
[
0,
0
],
[
0,
1
],
[
0,
1
],
[
0,
1
],
[
0,
1
],
[
0,
1
],
[
0,
1
],
[
0,
1
],
[
0,
1
],
[
0,
1
],
[
0,
1
],
[
0,
1
],
[
0,
1
],
[
0,
1
],
[
0,
1
]
],
"initial_policy": [
[
0,
0
],
[
0,
0
],
[
0,
0
],
[
0,
0
],
[
0,
0
],
[
0,
0
],
[
0,
0
],
[
0,
0
],
[
0,
0
],
[
0,
0
],
[
0,
0
],
[
0,
0
],
[
0,
0
],
[
0,
0
],
[
0,
0
],
[
0,
0
]
],
"known_training_error": 0.0,
"curve": [
{
"round": 1,
"beta": 1.0,
"labels": 96,
"dagger": {
"cost": 4.139832320000001,
"learner_distribution_error": 0.19842440000000008
},
"expert_augmented": {
"cost": 4.139832320000001,
"learner_distribution_error": 0.19842440000000008
}
},
{
"round": 2,
"beta": 0.5,
"labels": 160,
"dagger": {
"cost": 3.0594304000000014,
"learner_distribution_error": 0.11401800000000005
},
"expert_augmented": {
"cost": 3.2034304000000016,
"learner_distribution_error": 0.12526800000000007
}
},
{
"round": 3,
"beta": 0.25,
"labels": 224,
"dagger": {
"cost": 1.9040000000000012,
"learner_distribution_error": 0.02375000000000001
},
"expert_augmented": {
"cost": 2.064000000000001,
"learner_distribution_error": 0.03625000000000001
}
},
{
"round": 4,
"beta": 0.125,
"labels": 288,
"dagger": {
"cost": 1.680000000000001,
"learner_distribution_error": 0.00625
},
"expert_augmented": {
"cost": 1.920000000000001,
"learner_distribution_error": 0.02500000000000001
}
},
{
"round": 5,
"beta": 0.0625,
"labels": 352,
"dagger": {
"cost": 1.680000000000001,
"learner_distribution_error": 0.00625
},
"expert_augmented": {
"cost": 1.920000000000001,
"learner_distribution_error": 0.02500000000000001
}
},
{
"round": 6,
"beta": 0.03125,
"labels": 416,
"dagger": {
"cost": 1.680000000000001,
"learner_distribution_error": 0.00625
},
"expert_augmented": {
"cost": 1.920000000000001,
"learner_distribution_error": 0.02500000000000001
}
}
]
}每臂最终416个标签和416次转移,包含共享的32个初始标签;两臂合起来实际产生800次转移/专家查询。每臂重新拟合扫描的样本行数是32+96+160+224+288+352+416=1568。β变小不自动省标注,本程序每一步仍问专家。一次表格拟合为O(N+T),存储训练集O(N)、表格O(T);一次精确评价O(T),利用的是这个已知小任务的两个车道,不能据此推断实际驾驶的评价成本。
以下保留全部八个种子,指标为16步内预计偏离步数,越小越好。它们由已学策略的完整概率传播得到,不是少量测试回合的随机平均。
| 种子 | 初始BC | DAgger末轮 | 同预算专家增量 | 专家 |
|---|---|---|---|---|
| 0 | 6.05629 | 1.68 | 1.92 | 1.60 |
| 1 | 2.74240 | 1.60 | 1.60 | 1.60 |
| 2 | 3.43954 | 1.60 | 1.68 | 1.60 |
| 3 | 3.67258 | 1.68 | 1.68 | 1.60 |
| 4 | 3.83501 | 1.60 | 1.60 | 1.60 |
| 5 | 3.59885 | 1.60 | 1.60 | 1.60 |
| 6 | 3.31776 | 1.60 | 1.60 | 1.60 |
| 7 | 2.67840 | 1.60 | 1.60 | 1.60 |
DAgger两次没有达到专家代价,增加纯专家示范也经常达到相同结果。这个表支持“采集分布值得检查”,不支持“DAgger在所有同预算任务上更好”。全部轨迹保存在实验返回值;CLI省略较长的轨迹与初始计数,避免摘要淹没结果。
专家能不能回答恢复状态?
DAgger需要交互和补标。真实专家可能不知道怎样处理学习者造出的危险状态,反应延迟也会使标签与状态错位。只允许离线日志时,不能假装还能随时调用专家。动作本身有风险时,也需要受控采集环境;本例两车道只是数字状态。
若示范者看到的线索没有提供给学习者,同一观察可能对应不同正确动作。增加数据不能修补被隐藏的信息。示范质量不一致、多人风格混杂和动作多峰也可能让直接回归失效;应先检查观察和标签含义,而不是只增大模型。
本例的标签是无噪声且可完全查表的。它没有验证图像编码、连续操控或复杂模型的无悔性质;原论文游戏结果也没有在此复现。固定开源实现另有熵/L2损失、批处理和轨迹封装,本程序没有声称逐行对应这些实现。参考实现范围
先预测,再核对
-
某步DAgger访问车道1,学习者选保持0,专家选修复1,混合采样决定执行0。训练标签应存0还是1?
答案:存专家的1,并与动作前的车道1配对。执行0改变后续访问状态,不能因此把错误动作变成监督目标;下一状态的专家动作也不能错配到当前状态。
-
T=16、p=0.1,某策略自身分布动作错率为0.1,预计偏离多少步?这与训练集错率0矛盾吗?
答案:1.6+0.8×16×0.1=2.88步。不矛盾:训练集只包含有限访问状态,自身部署分布可能覆盖更多恢复状态。
-
把每轮β都设为0,能否宣称专家查询变为0?
答案:不能。β控制执行专家动作的概率,不控制标注频率;本程序仍为每个访问状态问专家。选择性查询是另一个算法改动,需要单独记录漏标和代价。
-
两臂各使用416个标签且共享32个初始标签,一共需要多少次环境转移?怎样避免挑最好种子?
答案:416+416−32=800。预先固定八个种子并保留所有结果,包括DAgger没有到达1.6的种子0和3;若要验证选迭代,必须另外设计选择集和最终评价,不能把本表同时当调参和最终测试。
从预测动作走向数据采集
BC把示范变成监督问题,适合作为第一条可检查基线。DAgger改变采集过程,问题是“学习者将遇到什么”;逆强化学习改变建模对象,问题是“什么奖励能解释这些选择”。它们不构成必然逐级更强的替代链。
读DAgger时,先对齐dπ、专家标签和被执行动作,再读成本界中的u与候选选择条件。原论文 阅读开源实现时,可跟踪收集器如何转发动作、如何保存专家标签,以及新数据如何进入BC训练器;不要只看算法名称。固定实现
先判断,再看解释
DAgger执行了学习者建议的动作后,训练集中应保存哪个动作作为标签?
学习目标
- 区分示范分布与策略自身访问分布,说明分类误差与任务代价之间还缺哪些条件。
- 从零实现BC与DAgger并比较同预算专家增量,分别记录执行动作、专家标签和评价成本。
先修与延伸
查看知识关联图 →参考文献
- A Reduction of Imitation Learning and Structured Prediction to No-Regret Online Learning — scoped conference paper
Stephane Ross; Geoffrey Gordon; Drew Bagnell · 2011 - imitation — fixed BC, DAgger and maximum causal entropy implementation reading
HumanCompatibleAI/imitation contributors · 2025
版本1 · 编写状态: 已完成记录中的技术复核
查看技术检查记录(AI)
Codex · 2026-09-24 · Single AI author. Scoped reading: Read physical pages2–4 of the official9-page PDF: expert/learner state distributions, conditions on quadratic and uT error bounds, mixed execution/expert labels/aggregation and validation selection. Later proofs and experiments not fully read; an existence guarantee is not a guarantee for any final iterate. Fixed2025-01-07 commit. Read122-line README,21-line MIT license, bc40–155, dagger210–291/425–459, mce_irl38–144/467–498. Execution versus expert labels and causal entropy distinguished. Reference only, no copying/execution or blanket verification of branches/terminal/discount conventions. 6 paired equations and four explained exercises. Expert/learner distributions, the conditional cost bounds, execution versus labels and equal-budget comparisons checked. Closed-form and exhaustive actuator calculations verify exact cost; evaluation replacement cannot alter fitting. All8seeds retain two final-iterate failures, and 416-per-arm/shared32/total800 queries are distinct. Not a neural BC or universal DAgger guarantee.
- 专家/学习者分布、条件性成本界、执行与标签及同预算比较逐项核;封闭式和噪声枚举核精确成本,替换评价不改拟合。八种子保留末轮两失败,416每臂/32共享/800总查询分开,不冒称神经BC或普适DAgger保证。
- 每题四张计算SVG,9数值/几何与12个当前响应式组合通过;六张当前选定图均直接实看,初次数值色标越界已修正并保留失败资产,资产与稿件SHA绑定,完整页面验收另记。
核对的来源位置:
- A Reduction of Imitation Learning and Structured Prediction to No-Regret Online Learning — scoped conference paper · Read physical pages2–4 of the official9-page PDF: expert/learner state distributions, conditions on quadratic and uT error bounds, mixed execution/expert labels/aggregation and validation selection. Later proofs and experiments not fully read; an existence guarantee is not a guarantee for any final iterate.
- imitation — fixed BC, DAgger and maximum causal entropy implementation reading · Fixed2025-01-07 commit. Read122-line README,21-line MIT license, bc40–155, dagger210–291/425–459, mce_irl38–144/467–498. Execution versus expert labels and causal entropy distinguished. Reference only, no copying/execution or blanket verification of branches/terminal/discount conventions.
相关主题