SARSA:用真正要执行的下一动作学习
SARSA
将已采样的下一动作带到下一步,区分探索策略价值与贪心目标。
sarsa下一步的哪个动作进入目标?
假设下一状态的两个动作估计为4和1,一次探索选择了第二个动作。奖励0、折扣0.9,学习目标该是3.6还是0.9?
SARSA使用0.9,即已采样下一动作的估计。随后把这个动作带入下一次交互,而不是再采样一次、可能执行另一个动作。若把采样值换成最大值4,就变成了Q-learning目标。只看一次更新,就能辨认区别,不必等很长的学习曲线。
Sutton与Barto第6.4节用一次转移中的状态、动作、奖励、下一状态和下一动作命名该方法。Silver控制讲义将它归为同策略控制:学习也计入行为策略的探索动作。
预测与改进共用行为策略
Q_t(s,a)估计在状态s先选动作a,随后继续执行正在学习的策略时的回报。看到下一奖励与状态后,从该策略采样A_(t+1),再更新:
目标的各项都使用旧表,只改被访问的状态动作对。若后继真正终止,继续价值为零,不需要再选动作,但最终奖励仍进入目标。在正常持续交互中,已经采样的下一动作会真正执行,即使更新期间价值表发生改变也沿用它。
把探索概率写清楚
程序采用epsilon-greedy行为,epsilon∈[0,1]。设可用动作数为m,B_t(s)为当前价值最大的全部并列动作。探索概率均匀分给所有动作,其余概率均匀分给并列者:
这个同分约定避免在初始全零表中总选最小动作ID。两动作、epsilon0.2、唯一最佳动作时,概率为0.9和0.1;最佳动作也分到一部分探索概率。Silver的epsilon-greedy讲解说明覆盖的动机;在全部并列最大者之间均分,是本实现明确采用的约定。
固定价值表与行为策略时,采样目标的期望为:
一次SARSA更新采样了内部的动作平均。Expected SARSA在可计算时显式求这个动作平均;Q-learning则换成最大值。对同一张表:
平均值不超过其中最大项,所以不等式成立。但它不能排列两算法最终表现的优劣:它们的表、数据和行为可能分别演化。epsilon为零时,贪心采样目标等于最大值,包括并列最大动作;探索率为正时,采样到低估计动作就可能改变目标。
探索改变正在遵循的策略价值
采用原创街机:入口0、房间1、终止2。在入口离开得2分,前进得0分并进入房间;房间离开得4分,转盘得1.6分,再以0.4、0.4、0.2概率进入入口、房间或终止。假设贪心选择已经稳定为前进/转盘,而epsilon保持0.2,每个状态仍有0.1概率选择离开。折扣0.9时,这条固定行为策略的值为:
常数项平均即时奖励,系数则相乘行为概率、转移概率与折扣。解得约v0=3.930748、v1=4.605861。这是探索策略的状态价值,不是动作价值表里最大的那一项。无探索的最优值约4.556962和5.063291。保留探索是被评估行为的一部分,不一定意味着学习出了问题。
固定epsilon不等于GLIE
收敛到最优动作价值,需要比“跑了很多回合”更强的条件。在标准有限表格环境、奖励有界且0≤gamma<1时,通常还需无限状态动作访问、极限贪心及适当逐对步长:
前两个要求描述GLIE:无限探索,同时在极限中变贪心。Silver的收敛幻灯片也列出步长条件。单独让epsilon递减,不能证明任意MDP里所有状态动作对都会被访问。本演示保持固定epsilon,不宣称满足GLIE或证明收敛到q*。
采样一次,更新,再沿用动作
将独立标准库程序保存为sarsa.py,用Python 3.12运行。更新函数不修改输入;环境与动作选择使用两个独立种子的随机流。
"""Original sarsa teaching example; synthetic episodes, not benchmark reproduction."""
import json
import math
import random
def unit(x, name):
if isinstance(x, bool) or not isinstance(x, (int, float)) or not math.isfinite(x) or not 0 <= x <= 1:
raise ValueError(name+' must be finite in [0,1]')
def sequence(states, rewards, values, terminated):
if type(terminated) is not bool or len(values)<2 or any(not math.isfinite(x) for x in values) or values[-1]!=0:
raise ValueError('finite values with a zero terminal component required')
if not rewards or len(states)!=len(rewards)+1 or any(not math.isfinite(r) for r in rewards):
raise ValueError('nonempty finite rewards and one extra state required')
terminal=len(values)-1
if any(type(s) is not int or not 0<=s<=terminal for s in states):
raise ValueError('state index outside table')
if terminal in states[:-1] or (states[-1]==terminal)!=terminated:
raise ValueError('termination flag must match the final state only')
class Arcade:
def __init__(self, seed):
self.rng = random.Random(seed)
self.state = 2
def reset(self):
self.state = 0
return self.state
def step(self, action):
if type(action) is not int or action not in (0, 1) or self.state == 2:
raise ValueError('valid action and a nonterminal state required')
if self.state == 0:
self.state, reward = (2, 2.0) if action == 0 else (1, 0.0)
elif action == 0:
self.state, reward = 2, 4.0
else:
u = self.rng.random()
self.state = 0 if u < .4 else 1 if u < .8 else 2
reward = 1.6
return self.state, reward, self.state == 2
def table(q):
if len(q)!=3 or any(len(row)!=2 or any(not math.isfinite(x) for x in row) for row in q) or q[2]!=[0,0]:
raise ValueError('finite 3 by 2 table with zero terminal row required')
def choose(q,state,epsilon,rng):
table(q);unit(epsilon,'epsilon')
if type(state) is not int or state not in (0,1):raise ValueError('nonterminal state required')
if rng.random()<epsilon:return rng.randrange(2)
best=max(q[state]);ties=[a for a in range(2) if q[state][a]==best]
return rng.choice(ties)
def step(q,state,action,reward,next_state,next_action,terminated,alpha=.5,gamma=.9):
table(q);unit(alpha,'alpha');unit(gamma,'gamma')
sequence([state,next_state],[reward],[0,0,0],terminated)
if type(action) is not int or action not in (0,1):raise ValueError('valid action required')
if (terminated and next_action is not None) or (not terminated and (type(next_action) is not int or next_action not in (0,1))):
raise ValueError('sampled next action required exactly when nonterminal')
target=reward+(0 if terminated else gamma*q[next_state][next_action]);delta=target-q[state][action]
out=[row.copy() for row in q];out[state][action]+=alpha*delta
return out,dict(target=target,delta=delta)
def train(episodes=20000,epsilon=.2,seed=41,max_steps=1000):
unit(epsilon,'epsilon')
if type(episodes) is not int or episodes<1 or type(max_steps) is not int or max_steps<1:raise ValueError('positive budgets required')
env=Arcade(seed);rng=random.Random(seed+1);q=[[0.0,0.0] for _ in range(3)];counts=[[0,0] for _ in range(3)];cutoffs=0
for _ in range(episodes):
s=env.reset();a=choose(q,s,epsilon,rng)
for k in range(max_steps):
nxt,r,done=env.step(a);nxt_a=None if done else choose(q,nxt,epsilon,rng)
counts[s][a]+=1;alpha=.8/counts[s][a]**.6
q,_=step(q,s,a,r,nxt,nxt_a,done,alpha)
if done:break
s,a=nxt,nxt_a
if not done:cutoffs+=1
return dict(q=q,counts=counts,greedy=[max(range(2),key=lambda a:q[s][a]) for s in (0,1)],cutoffs=cutoffs)
def demo():
q=[[2.,5.],[4.,1.],[0.,0.]];updated,row=step(q,0,1,0,1,1,False)
# A fixed epsilon policy around [advance,spin], not an input to training.
p=.2/2;g=.9;v1=(4*p+1.6*(1-p)+g*.4*(1-p)*2*p)/(1-g*.4*(1-p)-g*g*.4*(1-p)**2)
return dict(sampled_update=dict(**row,q=updated),max_action_target=.9*4,trained=train(),
epsilon=.2,fixed_behavior_reference=[2*p+g*(1-p)*v1,v1,0],optimal_reference=[360/79,400/79,0])
if __name__=='__main__':
print(json.dumps(demo(),indent=2,allow_nan=False))
单次更新例中,当前状态动作值为5,采样后继动作值为1;目标0.9、误差−4.1,alpha0.5得到2.95。若采用后继最大值,目标则是3.6。
训练20,000回合,环境种子41、动作种子42、epsilon0.2,步长0.8/N(s,a)^0.6。最终非终止行约为[[2,4.178836],[4,4.745020]],访问计数为[[4050,35869],[5996,49611]],贪心动作[1,1]。这次运行没有回合达到1,000步采集上限。这些采样动作价值不是精确策略值,也不是基准成绩。
若达到采集上限,程序仍用最后非终止状态及采样继续动作自举,记录一次截断,再重置采集。虽然采集边界阻止该动作在这段轨迹中执行,它仍表示持续任务的目标继续动作。真正终止则要求next_action=None,继续价值为零。两种情形都不能把新重置状态当作旧回合的后继。
一般表格更新的算术只改一对,但这个小实现还检查并复制全表、扫描动作以做选择。若推广为同样写法的S × A表,每转移成本为O(SA),内存O(SA);这是便于检查的教学实现,不是优化后的稀疏求解器。这里S=3、A=2。校验确保终止行保持零,并且恰好在需要时提供下一动作。
同策略不等于没有探索
探索动作可能拉低目标;若未来确实继续这样行动,这正是合适的计算。单独进行贪心评估是在问另一问题。报告评估回报时,应说明执行了哪条策略、是否保留探索。
训练策略随价值表变化,有限运行结果不等于某条永久固定策略的精确解。函数逼近、异策略回放、部分观测和奖励变化,都增加了小例之外的假设。Q-learning采用另一种目标;资格迹则把信用扩展到更早访问,但也需要自己的更新约定。
别丢掉转移中的第五项
-
为什么先采样下一动作,再更新,并沿用该动作?
答案:这让目标里采样的继续动作,与实际轨迹的下一动作一致。更新表后重新采样,可能产生不同于刚才目标所用的继续动作。
-
当前值5、奖励0、采样下一动作值1、gamma0.9、alpha0.5,计算更新。
答案:目标0.9,误差
0.9−5=−4.1,新值5+0.5×(−4.1)=2.95。另一个动作的最大值4不进入这次SARSA样本。 -
两动作、epsilon0.2、唯一最佳动作时,概率各是多少?两动作并列呢?
答案:唯一最佳得到
0.2/2+0.8=0.9,另一动作0.1。按所述均匀同分规则,两者并列时各为0.1+0.8/2=0.5。 -
每回合降低epsilon,并观察到一条不错的贪心策略,是否已经建立最优收敛结论?
答案:没有。还要核访问、逐状态动作步长及有限马尔可夫环境假设。有限运行不能证明无限探索;epsilon递减本身也不让难以到达的状态动作对获得充分样本。
算法与收敛条件分别读
工作稿SARSA节给出五元更新与终止约定;其中历史收敛说明归于私人通信。Silver控制讲义明确列出GLIE和步长条件。这里把它们作为明示假设,没有冒充新核验了一份完整定理证明。程序为原创,没有复现讲义的有风网格实验。
先判断,再看解释
采样的下一动作Q=1,另一个动作Q=4;奖励0、gamma0.9,SARSA目标是多少?
学习目标
- 实现SARSA五元转移,沿用下一动作而不重新采样。
- 区分固定探索率与GLIE,说明访问和步长条件。
先修与延伸
查看知识关联图 →参考文献
- Reinforcement Learning: An Introduction — second-edition working draft (2014–2015)
Richard S. Sutton; Andrew G. Barto · 2015 - Lecture 5: Model-Free Control
David Silver · 2015
版本1 · 编写状态: 已完成记录中的技术复核
查看技术检查记录(AI)
Codex · 2026-09-23 · Single AI author. Scoped reading: PDF168–169 §6.4/Fig6.9: state-action transitions, carried action, terminal row zero; old draft personal-communication convergence remark is not a new published proof. Read2026-09-23. Read PDF5,11,15,20,23 and visually inspected the image-only algorithm on PDF22. On/off-policy distinction, epsilon exploration, carried next action, GLIE and step-size conditions. Infinite state-action visitation is a separate assumption; a decaying epsilon schedule alone is not proved sufficient for arbitrary MDPs. Course year from author teaching page; no benchmark replication. 6 paired equations and four explained exercises. Checked sampled-action targets, pre-update action reuse, greedy tie sampling, epsilon endpoints, terminal and cutoff actions, seeded control and a separate fixed-epsilon policy oracle. Fixed epsilon is not GLIE; action values are not state values.
- 核采样动作目标、更新前动作复用、贪心同分采样、epsilon端点、终止/截断动作、固定种子控制与独立固定epsilon策略参照;固定epsilon不是GLIE,动作价值不是状态价值。
- 每题四张计算SVG,12数值/几何与36响应式组合通过;12张当前选定图均直接实看,浏览器输入由插图前SHA绑定,完整页面验收另记。
核对的来源位置:
- Reinforcement Learning: An Introduction — second-edition working draft (2014–2015) · PDF168–169 §6.4/Fig6.9: state-action transitions, carried action, terminal row zero; old draft personal-communication convergence remark is not a new published proof. Read2026-09-23.
- Lecture 5: Model-Free Control · Read PDF5,11,15,20,23 and visually inspected the image-only algorithm on PDF22. On/off-policy distinction, epsilon exploration, carried next action, GLIE and step-size conditions. Infinite state-action visitation is a separate assumption; a decaying epsilon schedule alone is not proved sufficient for arbitrary MDPs. Course year from author teaching page; no benchmark replication.
相关主题