逆强化学习:从选择推断奖励,能推断到哪一步?
Inverse reinforcement learning
从奖励歧义到最大熵特征匹配,枚举四条路线学习偏好,再检验换一张地图后是否仍选对。
inverse-rl同一条路线,可以有不同的理由
一个人每天绕远走公园,是喜欢树荫、讨厌拥挤,还是不知道近路?路线给出了行为证据,却没有直接给出奖励。逆强化学习(inverse reinforcement learning,IRL)先建立环境与决策者的模型,再找能解释观察行为的奖励函数。学得奖励后,可以用规划或强化学习产生策略。
普通强化学习给定奖励,问怎样行动;IRL给定行为,问哪些奖励与行为相容。行为克隆直接预测动作,也可以完成模仿,不必先推断奖励。IRL额外引入的奖励模型可能帮助复用偏好,但同时增加动力学、特征和决策模型的假设。问题与歧义
本篇用一个明确虚构的两步路线图。每段路有遮阴分数、拥挤分数和步数三个特征;四条路线的总特征分别为(0,0,2)、(0,1,2)、(1,1,2)、(2,0,2)。示范者偏好遮阴、回避拥挤,但会随机选择。程序根据128条示范学习前两个权重,再给它一张改变了一段路线特征的地图。
先不要问“恢复出的奖励是否完全正确”。所有路线都走两步,给每一步奖励加相同常数,只会给四条路线同时加相同总分,选择概率不变。数据无论增加多少,也无法从这组等长路线识别这个常数。
行为约束奖励,并不唯一指定奖励
先看一种理想化设定:有限状态、已知转移、完整确定性专家策略、仅依赖状态的奖励,且折扣严格介于0与1之间。专家策略诱导的转移矩阵为Pπ,任一备选动作的转移矩阵为Pa。策略最优要求,在每个状态执行专家动作不差于偏离一步后继续跟专家。利用贝尔曼方程可写成:有限MDP的式4
两个动作的当前状态奖励相同,比较时抵消;正的γ也可以约去。这是对R的线性不等式。R全为0时任何策略都满足,常数奖励也会产生歧义。有限示范、随机专家、动作相关奖励或未知转移不能不加修改地套这个式子。本篇主程序采用另一种模型:有限确定路线上的随机选择,不运行上述线性规划。
最大熵路线模型在匹配示范的期望特征时,选择尽量少添加额外偏好的分布。令F是沿路线累加的特征,约束包括概率和为1及期望特征给定。对熵加拉格朗日乘子,关于每个路径概率求导,会得到log概率等于线性特征分数加常数;归一化后得到:确定路径模型
这里初始状态固定,候选集合是所有合法的有限确定路径,温度固定为1。不是给每个已观察路径单独打分后只在示范中归一化;没被示范的合法路线也必须进入Z。有限集合保证Z有限,本例没有无限循环路径的收敛问题。
示范平均特征记作F横线。最大化示范似然等价于最小化下式。程序加L2惩罚,只作用于前两维;第三维常数权重固定为0。
对log分配函数求导,导数就是模型的期望特征;再求导,得到特征的协方差。这同时给出优化方向和凸性检查:
协方差半正定,所以负对数似然是凸函数,对数似然是凹函数。作者更正版第3页在最大化L后使用了“convex”措辞;这里按上述符号推导,不照搬那句话。无正则且达到有限内部最优时,模型矩与经验矩相等;有正则时,两者相差λMθ,不能再声称精确特征匹配。原文梯度及版本说明
同样要区别两种歧义。固定长度时,加常数不改变概率;如果温度也未知,只能从分数与温度的比值推断偏好尺度。仅有最优动作而没有选择频率时,正比例缩放也保留动作排序。
若温度已固定为1,单独放大θ通常会让分布更尖,并不保留所有选择概率。正则化或把常数设为0选定的是一个代表,不是额外发现了真实动机。
枚举路线适合核对,但路径数量随时域可能指数增长。确定性无环图上,可以从终点向后累积余下路线的总权重。用V表示其对数,边奖励为rθ,终点没有额外动作:
这样得到的局部动作概率连乘,等于完整路径的全局概率。仅对即时奖励做softmax则漏掉后续可选路线。在随机动力学中,还必须防止把不可控的幸运结果当作可选行为。温度1的有限时域最大因果熵控制采用期望未来软价值:
期望V与log期望exp(V)一般不同。假设只有一个动作,环境公平随机给奖励0或2;控制者不能改变各1/2的概率。若直接用exp奖励重权这两个结果,会把好结果概率改成约0.880797,造出不存在的控制能力。2008作者稿对随机路径另作近似假设;最大因果熵代码也有独立的时域约定,两者不能直接混称。作者随机路径假设、固定因果熵实现
奖励还有与动力学相关的等价变换。加势函数差分后,折扣和会望远镜相消:
固定起点、末端势为0时,所有策略回报平移相同量,排序不变。末端条件不能省略;变长任务和不同终点势需重新分析。本程序只把它作为独立算术反例,主拟合仍是固定两步、未折扣的路线模型。
学四条路线,再改一条边
程序只用Python标准库,生成示范的权重为(0.7,−0.5,0),仅用于造数据与评价;拟合函数看不到它。128条示范用于训练,另512条来自独立随机流,只作留出评价。固定800步梯度下降,步长0.15,L2系数0.01;没有按留出结果选步数或种子。
"""Original finite deterministic MaxEnt IRL. Enumerated paths; Python 3.11+."""
import json
import math
import random
# Each edge is (next state, three additive features). State 3 is terminal.
GRAPH = {0: [(1, (0., 0., 1.)), (2, (1., 0., 1.))],
1: [(3, (0., 0., 1.)), (3, (0., 1., 1.))],
2: [(3, (0., 1., 1.)), (3, (1., 0., 1.))]}
TRUE_WEIGHTS = (.7, -.5, 0.) # used only by the demonstrator and evaluation
def dot(a, b):
if len(a) != len(b):
raise ValueError('Feature dimensions differ')
return sum(x * y for x, y in zip(a, b))
def logsumexp(values):
if not values or not all(math.isfinite(x) for x in values):
raise ValueError('Nonempty finite scores required')
maximum = max(values)
return maximum + math.log(sum(math.exp(x - maximum) for x in values))
def paths(graph=GRAPH, state=0, visited=()):
if state == 3:
return [((), (0., 0., 0.))]
if state in visited or state not in graph or not graph[state]:
raise ValueError('Acyclic graph ending in terminal state 3 required')
output = []
for action, (next_state, features) in enumerate(graph[state]):
if len(features) != 3 or not all(math.isfinite(x) for x in features):
raise ValueError('Three finite edge features required')
for actions, rest in paths(graph, next_state, visited + (state,)):
output.append(((action,) + actions, tuple(x + y for x, y in zip(features, rest))))
return output
def distribution(weights, features):
scores = [dot(weights, f) for f in features]
normalizer = logsumexp(scores)
return [math.exp(x - normalizer) for x in scores], normalizer
def objective_gradient(weights, observed, features, l2=.01):
if not observed or not math.isfinite(l2) or l2 < 0:
raise ValueError('Nonempty demonstrations and nonnegative regularizer required')
if any(not isinstance(i, int) or not 0 <= i < len(features) for i in observed):
raise ValueError('Invalid demonstrated path')
probabilities, normalizer = distribution(weights, features)
empirical = [sum(features[i][k] for i in observed) / len(observed) for k in range(3)]
expected = [sum(p * f[k] for p, f in zip(probabilities, features)) for k in range(3)]
# The constant feature is fixed to zero, not recovered from demonstrations.
penalty = .5 * l2 * sum(x * x for x in weights[:2])
loss = normalizer - dot(weights, empirical) + penalty
gradient = [expected[k] - empirical[k] + (l2 * weights[k] if k < 2 else 0.) for k in range(3)]
return loss, gradient, empirical, expected
def fit(observed, features, steps=800, rate=.15, l2=.01):
if not isinstance(steps, int) or steps < 1 or not math.isfinite(rate) or rate <= 0:
raise ValueError('Positive optimization budget required')
weights, history = [0., 0., 0.], []
for i in range(steps):
loss, gradient, _, _ = objective_gradient(weights, observed, features, l2)
if i % 100 == 0:
history.append(dict(step=i, loss=loss))
for k in range(2):
weights[k] -= rate * gradient[k]
loss, gradient, empirical, expected = objective_gradient(weights, observed, features, l2)
history.append(dict(step=steps, loss=loss))
return dict(weights=weights, loss=loss, gradient=gradient, empirical=empirical,
expected=expected, history=history, gradient_steps=steps)
def soft_plan(weights, graph=GRAPH):
"""Independent backward dynamic programming; deterministic DAG only."""
paths(graph) # validate acyclicity and edge dimensions before recursion
values, policy = {3: 0.}, {}
def backward(state):
if state not in values:
q = [dot(weights, f) + backward(nxt) for nxt, f in graph[state]]
values[state] = logsumexp(q)
policy[state] = [math.exp(x - values[state]) for x in q]
return values[state]
backward(0)
return values, policy
def sample(probabilities, n, rng):
if not isinstance(n, int) or n < 1 or any(x < 0 for x in probabilities) or not math.isclose(sum(probabilities), 1.):
raise ValueError('Positive sample count and normalized probabilities required')
return rng.choices(range(len(probabilities)), weights=probabilities, k=n)
def experiment(seed=0):
items = paths()
features = [f for _, f in items]
true_p, _ = distribution(TRUE_WEIGHTS, features)
observed = sample(true_p, 128, random.Random(seed))
heldout = sample(true_p, 512, random.Random(seed + 1000))
learned = fit(observed, features)
estimated, _ = distribution(learned['weights'], features)
_, policy = soft_plan(learned['weights'])
changed = {s: list(edges) for s, edges in GRAPH.items()}
changed[1][1] = (3, (3., 1., 1.))
new_features = [f for _, f in paths(changed)]
choice = max(range(4), key=lambda i: dot(learned['weights'], new_features[i]))
new_rewards = [dot(TRUE_WEIGHTS, f) for f in new_features]
return dict(seed=seed, actions=[list(a) for a, _ in items], features=features,
demo_counts=[observed.count(i) for i in range(4)], true_probabilities=true_p,
estimated_probabilities=estimated, root_policy=policy[0], fit=learned,
heldout_nll=-sum(math.log(estimated[i]) for i in heldout) / len(heldout),
uniform_nll=math.log(4), exact_kl=sum(p * math.log(p / q) for p, q in zip(true_p, estimated)),
transfer_choice=choice, transfer_true_rewards=new_rewards,
transfer_regret=max(new_rewards) - new_rewards[choice],
demonstrations=128, heldout_demonstrations=512, enumerated_paths=4)
if __name__ == '__main__':
print(json.dumps(experiment(), indent=2))
查看运行摘要
{
"seed": 0,
"actions": [
[
0,
0
],
[
0,
1
],
[
1,
0
],
[
1,
1
]
],
"features": [
[
0.0,
0.0,
2.0
],
[
0.0,
1.0,
2.0
],
[
1.0,
1.0,
2.0
],
[
2.0,
0.0,
2.0
]
],
"demo_counts": [
13,
6,
20,
89
],
"true_probabilities": [
0.1452826705669086,
0.08811839402376027,
0.1774486545432975,
0.5891502808660336
],
"estimated_probabilities": [
0.09858227756262193,
0.05712916218008818,
0.15145162807439086,
0.692836932182899
],
"root_policy": [
0.1557114397427101,
0.8442885602572898
],
"fit": {
"weights": [
0.9749515798481871,
-0.5455767972283652,
0.0
],
"loss": 0.9257967592560096,
"gradient": [
8.238670794191716e-09,
2.2282195385678327e-08,
0.0
],
"empirical": [
1.546875,
0.203125,
2.0
],
"expected": [
1.537125492440189,
0.20858079025447904,
2.0
],
"history": [
{
"step": 0,
"loss": 1.3862943611198906
},
{
"step": 100,
"loss": 0.9258526920335607
},
{
"step": 200,
"loss": 0.9257986242006041
},
{
"step": 300,
"loss": 0.9257968212471186
},
{
"step": 400,
"loss": 0.9257967613154878
},
{
"step": 500,
"loss": 0.9257967593244208
},
{
"step": 600,
"loss": 0.9257967592582793
},
{
"step": 700,
"loss": 0.9257967592560824
},
{
"step": 800,
"loss": 0.9257967592560096
}
],
"gradient_steps": 800
},
"heldout_nll": 1.099143178098365,
"uniform_nll": 1.3862943611198906,
"exact_kl": 0.027128098811312874,
"transfer_choice": 1,
"transfer_true_rewards": [
0.0,
1.5999999999999996,
0.19999999999999996,
1.4
],
"transfer_regret": 0.0,
"demonstrations": 128,
"heldout_demonstrations": 512,
"enumerated_paths": 4
}程序枚举四条路径求分配函数,并另用反向递推核对路径概率。每次梯度计算重新扫描N条示范和M条候选路径,d维特征下K步复杂度为O(K(N+M)d),并非预先缓存经验矩的优化实现。soft_plan为验证输入先调用完整路径枚举,因此该函数整体也不能宣称只有线性图遍历开销;其反向递推部分可以复用子问题,实际大图应另做不枚举路径的合法性检查。
种子0的四条示范计数为13、6、20、89。学习到的前两权重约为0.97495、−0.54558,并非造数据的0.7、−0.5。模型路线概率约为0.09858、0.05713、0.15145、0.69284;根动作概率约为0.15571、0.84429。L2与有限样本共同影响结果。
接着把路线01最后一段的特征从(0,1,1)改为(3,1,1),其他边不变。新四路线的真实分数是0、1.6、0.2、1.4,因此最优路线从11变为01。这里保持奖励特征的意义与真实权重不变,只改已知地图特征;这是假设明确的迁移测试。
| 种子 | 遮阴权重 | 拥挤权重 | 原地图精确KL | 新地图选择 | 真实遗憾 |
|---|---|---|---|---|---|
| 0 | 0.97495 | −0.54558 | 0.02713 | 01 | 0.0 |
| 1 | 0.69902 | −0.75802 | 0.00618 | 11 | 0.2 |
| 2 | 0.71817 | −0.49724 | 0.00011 | 01 | 0.0 |
| 3 | 0.78629 | −0.67945 | 0.00829 | 01 | 0.0 |
| 4 | 0.57619 | −0.29846 | 0.01428 | 01 | 0.0 |
| 5 | 0.58390 | −0.65259 | 0.00390 | 11 | 0.2 |
| 6 | 0.82363 | −0.28815 | 0.00469 | 01 | 0.0 |
| 7 | 0.54421 | −0.64699 | 0.00674 | 11 | 0.2 |
KL方向为真实示范分布相对于学得分布,只因我们知道造数据规则才可精确计算。八个种子的留出负对数似然都优于均匀基线log4;但种子1、5、7在新图仍选错,因为路线01相对11的优势由两个权重之和决定,微小差异会改变排序。拟合原行为不错,不等于迁移决策可靠。
拟合的是假设下的偏好
可辨识性、数据量与模型错误是不同问题。第三维常数即使有无限数据也无法在这个任务识别;前两维虽可影响分布,却受有限采样影响;若遮阴/拥挤特征漏掉专家在意的因素,再精确的优化也可能学错解释。
奖励模型还依赖对专家信息和理性的假设。未知地图、习惯、误操作或不同目标都能产生相似行为。把每次行动解释为稳定奖励下的最优选择,可能只是在拟合错误决策模型。此处用随机指数族生成示范,是可检验的教学设定,不是人的普遍心理定律。
原环境中等价的奖励,换环境后可能不再等价;任务奖励若改变,重用旧权重也没有理由正确。特征计量单位变化会改变权重数值与正则化效果。报告行为拟合、偏好歧义和实际迁移结果,比只报告“学出一个奖励”更有意义。
本程序不是Ng/Russell线性规划、论文道路导航系统或完整最大因果熵库的复现;随机动力学只做不可控结果的反例,未训练随机IRL。原始示范与程序里的真实奖励也不能被偷渡到拟合过程。
识别什么,仍缺什么?
-
四条路线长度都是2,每步奖励都加7,原最大熵路径概率如何变化?常数权重设为0意味着发现了真实常数吗?
答案:每条总分都加14,分子与分配函数同乘exp14,概率不变。设0只固定一个代表,不是从选择中识别出真实常数;长度不同时不能沿用这个结论。
-
某维经验平均特征为1.2,模型平均为0.9,θ=0.5,λ=0.1,该维正则化负对数似然梯度是多少?步长0.2后权重变为多少?
答案:梯度0.9−1.2+0.1×0.5=−0.25;梯度下降得到0.5−0.2×(−0.25)=0.55。权重增大,提高该特征路线的倾向。正则最优时矩差一般不是0。
-
环境只有一个动作,公平随机产生奖励0或2。为什么按exp奖励重权得到约0.880797的高奖励概率,不是一个可执行策略?
答案:没有其他动作可选,环境的高奖励概率固定为1/2。全局重权改变了不可控结果的分布,等于赋予决策者挑选随机结果的能力;因果控制必须保留原转移概率。
-
新地图路线01与11的特征分别为(3,1,2)、(2,0,2)。权重(0.69902,−0.75802,0)会选哪条,真实权重(0.7,−0.5,0)下损失多少?
答案:估计优势θ遮阴+θ拥挤=−0.059,所以选11。真实优势0.7−0.5=0.2,损失0.2;这是有限数据下对决策边界的误判,不是第三维常数歧义导致的。
沿着约束、概率与控制三条线读
Ng/Russell的有限MDP刻画适合看行为怎样约束奖励,以及为什么零奖励总是一个退化解。作者存档 最大熵模型适合看如何从特征约束得到路径概率、怎样计算分配函数,以及梯度为何是矩之差。作者更正版 该作品的作者页面标明AAAI2008与算法更正;PDF版权行2010不应被当作原会议年份或未经确认的更正日期。
比较实现时,再追踪因果熵的soft Bellman与访问频率,把终点、最后一次动作和折扣约定写清楚。固定开源实现 更复杂的方法可以改变特征、奖励参数化和拟合方式,但仍需回答:什么是可控的、什么能由数据识别、什么只由模型假设选定。
先判断,再看解释
所有候选路线长度相同,给每步奖励加相同常数,能从这些路线的选择频率识别该常数吗?
学习目标
- 说明行为如何约束而不唯一确定奖励,并推导有限路径最大熵目标、梯度及不可辨识方向。
- 验证枚举与反向规划一致,保留有限样本迁移失败,区分确定路径最大熵与随机动力学下的因果控制。
先修与延伸
查看知识关联图 →参考文献
- Algorithms for Inverse Reinforcement Learning — author archive, visual reading
Andrew Y. Ng; Stuart Russell · 2000 - Maximum Entropy Inverse Reinforcement Learning — author-corrected copy
Brian D. Ziebart; Andrew Maas; J. Andrew Bagnell; Anind K. Dey · 2008 - 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: ICML2000 author archive,8 pages. Text extraction is corrupted by font encoding; read rendered pages1–3. Known finite MDP, complete deterministic policy, state-only rewards, Equation4 for0<gamma<1 and zero/constant ambiguities. Remaining5 pages unread; no LP reproduction. Author landing page identifies AAAI2008 and an off-by-one correction; linked6-page copy has a2010 copyright line but no stated correction date. Read2–3 and viewed3. Finite deterministic paths, feature gradients and stochastic approximation; independently checked concave log-likelihood/convex NLL rather than copying page3 wording. No infinite-path convergence or later experimental audit. 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. 8 paired equations and four explained exercises. Known-policy constraints, finite deterministic MaxEnt gradients/covariance Hessian, fixed constant/temperature and terminal shaping conditions independently checked. Enumeration agrees with backward planning; stochastic reweighting does not invent control. All8seeds retain three changed-map failures. True reward is absent from fitting, and author-copy convexity wording is corrected by derivation.
- 已知策略约束、有限确定MaxEnt梯度/协方差Hessian、常数/温度及末端势条件独立核;枚举与反向规划一致,随机重权不赋予不存在的控制。八种子保留三迁移失败,真实奖励不入拟合,作者稿凸性措辞以独立推导校正。
- 每题四张计算SVG,9数值/几何与12个当前响应式组合通过;六张当前选定图均直接实看,初次数值色标越界已修正并保留失败资产,资产与稿件SHA绑定,完整页面验收另记。
核对的来源位置:
- Algorithms for Inverse Reinforcement Learning — author archive, visual reading · ICML2000 author archive,8 pages. Text extraction is corrupted by font encoding; read rendered pages1–3. Known finite MDP, complete deterministic policy, state-only rewards, Equation4 for0<gamma<1 and zero/constant ambiguities. Remaining5 pages unread; no LP reproduction.
- Maximum Entropy Inverse Reinforcement Learning — author-corrected copy · Author landing page identifies AAAI2008 and an off-by-one correction; linked6-page copy has a2010 copyright line but no stated correction date. Read2–3 and viewed3. Finite deterministic paths, feature gradients and stochastic approximation; independently checked concave log-likelihood/convex NLL rather than copying page3 wording. No infinite-path convergence or later experimental audit.
- 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.
相关主题