策略梯度方法介绍——蒙特卡洛策略梯度方法(REINFORCE)

目录

上一节介绍了 ∇ J ( θ ) \nabla \mathcal J(\theta) J(θ)的求解过程的推导,本节将基于上述推导进行补充,构建更加泛化的表达式,从而引出REINFORCE算法的更新方程。

回顾: ∇ J ( θ ) \nabla \mathcal J(\theta) J(θ)梯度求解结果

上一节介绍关于 ∇ J ( θ ) \nabla \mathcal J(\theta) J(θ)梯度方向的求解结果如下:
∇ J ( θ ) = ∇ V π ( s 0 ) ∝ ∑ s ∈ S μ ( s ) ∑ a ∈ A ( s ) ∇ π ( a ∣ s ) q π ( s , a ) \begin{aligned} \nabla \mathcal J(\theta) & = \nabla V_\pi(s_0) \\ & \propto \sum_{s \in \mathcal S} \mu(s) \sum_{a \in \mathcal A(s)} \nabla \pi(a \mid s)q_\pi(s,a) \end{aligned} J(θ)=Vπ(s0)sSμ(s)aA(s)π(as)qπ(s,a)
其中 s 0 s_0 s0表示情节的初始状态 μ ( s ) \mu(s) μ(s)表示某状态 s s s在情节中出现的概率
μ ( s ) = η ( s ) ∑ s ′ η ( s ′ ) \mu(s) = \frac{\eta(s)}{\sum_{s'}\eta(s')} μ(s)=sη(s)η(s)
η ( s ) \eta(s) η(s)表示某状态 s s s在情节中出现的平均次数

策略梯度定理的延伸

观察 ∇ J ( θ ) \nabla \mathcal J(\theta) J(θ)梯度方向的求解结果:
∇ J ( θ ) ∝ ∑ s ∈ S μ ( s ) ∑ a ∈ A ( s ) ∇ π ( a ∣ s ) q π ( s , a ) \nabla \mathcal J(\theta) \propto \sum_{s \in \mathcal S} \mu(s) \sum_{a \in \mathcal A(s)} \nabla \pi(a \mid s)q_\pi(s,a) J(θ)sSμ(s)aA(s)π(as)qπ(s,a)
发现 μ ( s ) \mu(s) μ(s)本身是状态 s s s出现概率 → \to 可以将 ∑ s ∈ S μ ( s ) \sum_{s \in \mathcal S} \mu(s) sSμ(s)表示为表示为期望形式
∑ s ∈ S μ ( s ) ∑ a ∈ A ( s ) ∇ π ( a ∣ s ) q π ( s , a ) = E ? [ ∑ a ∈ A ( s ) ∇ π ( a ∣ s ) q π ( s , a ) ] \sum_{s \in \mathcal S} \mu(s) \sum_{a \in \mathcal A(s)} \nabla \pi(a \mid s)q_\pi(s,a) = \mathbb E_{?}\left[\sum_{a \in \mathcal A(s)} \nabla \pi(a \mid s)q_\pi(s,a)\right] sSμ(s)aA(s)π(as)qπ(s,a)=E? aA(s)π(as)qπ(s,a)
问题:期望符号中的概率分布 是谁(上式中“?”部分);
既然是关于状态的概率分布,我们定义这样一个分布符号: ρ π θ \rho^{\pi_{\theta}} ρπθ,使得状态 s s s出现概率服从该分布。
需要注意的点:该分布不仅和策略函数 π ( a ∣ s ; θ ) \pi(a \mid s;\theta) π(as;θ)相关,因为‘状态转移过程’是系统内部的变化,因此这个出现概率的分布还与‘环境’相关。
∀ s ∈ S → s ∼ ρ π θ ( s ) = lim ⁡ t → ∞ P ( S t = s ∣ A 0 : t ∼ π ) \forall s \in \mathcal S \to s \sim \rho^{\pi_{\theta}}(s) = \mathop{\lim}\limits_{t \to \infty}P(S_t = s \mid A_{0:t} \sim \pi) sSsρπθ(s)=tlimP(St=sA0:tπ)
上述式子整理如下:
E s ∼ ρ π θ [ ∑ a ∈ A ( s ) ∇ π ( a ∣ s ) q π ( s , a ) ] \mathbb E_{s \sim \rho^{\pi_{\theta}}}\left[\sum_{a \in \mathcal A(s)} \nabla \pi(a \mid s)q_\pi(s,a)\right] Esρπθ

### 策略梯度方法在强化学习中的应用和实现 #### 一、策略梯度简介 策略梯度是一种直接参数化并优化策略方法,在不同的状态下,该方法能够学习到动作的概率分布,以此来优化长期获得的奖励总和。这种方法不依赖于环境模型,可以直接应用于高维连续空间的问题中[^1]。 #### 二、算法详解 为了更好地理解策略梯度的工作原理,可以考虑一个简单的例子——“FrozenLake”游戏环境下的求解方案。在这个环境中,智能体的目标是从起点到达终点而不掉入陷阱。通过不断尝试新的路径,并根据所得到的结果调整自己的行动模式,最终达到最优解的目的。 具体来说,对于每一个时间步t, 给定当前的状态st以及由神经网络定义的一系列可能的行为at及其对应的概率π(at|st;θ),其中θ代表可调参量,则期望回报J(θ)=E[Gt]=∑γ^kR(t+k+1)可以通过随机采样轨迹的方式近似计算出来;而我们的目标就是找到使得这个预期收益最大化的参数向量θ*: \[ J(\theta )=\mathbb {E} _{a_{0},\ldots ,a_{T}\sim \pi }\left[\sum _{t=0}^{T}\gamma ^{t}r(s_{t},a_{t})\right]\] 这里\( r(s_t,a_t)\) 表示即时奖励函数, γ 是折扣因子 (discount factor), T 则指代终止时刻之前的时间长度。 当采用蒙特卡洛估计时,上述表达式的导数形式如下: \[ ∇_\theta J (\theta )≈{\frac {1}{N}}\sum _{{n=1}}^{N}[G({s_{{tn}},a_{{tn}})}∇_\theta log π(a_{{tn}}| s_{{tn}};\theta)]\] 此处 N 为样本数量, G(sn,an) 记作从第 n 条序列中抽取的一个完整的回合产生的累计折现奖赏值。 ```python import gymnasium as gym import numpy as np from tensorflow.keras.models import Sequential from tensorflow.keras.layers import Dense from tensorflow.keras.optimizers import Adam def create_model(input_dim, output_dim): model = Sequential() model.add(Dense(units=16, activation='relu', input_shape=(input_dim,))) model.add(Dense(units=output_dim, activation='softmax')) model.compile(optimizer=Adam(), loss='categorical_crossentropy') return model env = gym.make('FrozenLake-v1', desc=None,map_name="4x4", is_slippery=True) state_space_samples = [] for i in range(env.observation_space.n): state_space_samples.append(i) obs_high = max(state_space_samples) obs_low = min(state_space_samples) num_states = env.observation_space.n num_actions = env.action_space.n model = create_model(num_states, num_actions) episodes = 1000 max_steps_per_episode = 100 learning_rate = 0.01 discount_rate = 0.99 exploration_rate = 1.0 max_exploration_rate = 1.0 min_exploration_rate = 0.01 exploration_decay_rate = 0.001 rewards_all_episodes = [] # Q-learning algorithm with policy gradient updates. for episode in range(episodes): state = env.reset()[0] done = False rewards_current_episode = 0 for step in range(max_steps_per_episode): exploration_threshold = np.random.uniform(0, 1) if exploration_threshold > exploration_rate: action_probabilities = model.predict(np.array([state])) action = np.argmax(action_probabilities) else: action = env.action_space.sample() new_state, reward, terminated,truncated,_ = env.step(action) done = truncated or terminated target = reward + discount_rate * \ np.max(model.predict(np.array([new_state]))) target_vec = model.predict(np.array([state]))[0] target_vec[action] = target mask = np.zeros((num_states,num_actions)) mask[state][action] = 1 model.fit(x=np.array([state]), y=np.reshape(target_vec,(1,-1)), epochs=1, verbose=0) state = new_state rewards_current_episode += reward if done == True: break exploration_rate = min_exploration_rate + \ (max_exploration_rate - min_exploration_rate) * np.exp(-exploration_decay_rate*episode) rewards_all_episodes.append(rewards_current_episode) reward_per_thousand_episodes = np.split(np.array(rewards_all_episodes), episodes/1000.0) count = 1000 print("********Average reward per thousand episodes********\n") for r in reward_per_thousand_episodes: print(count, ": ", str(sum(r/1000))) count += 1000 ``` 此代码片段实现了基于策略梯度的学习过程,用于解决 Frozen Lake 游戏问题。注意这里的实现方式实际上更接近于 actor-critic 方法的一部分特性,因为它不仅更新了策略(actor),还使用了一个类似于 critic 的机制来进行价值预测以便指导策略改进的方向[^3]。 然而值得注意的是,尽管策略梯度提供了强大的理论框架和支持复杂决策的能力,但在实际操作过程中也会遇到诸如样本效率低下等问题,这可能导致训练速度较慢且难以收敛至全局最优点附近[^4]。
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

静静的喝酒

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值