PPO-强化学习算法


PPO受到与TRPO相同的问题的激励:我们如何才能使用当前拥有的数据在策略上采取最大可能的改进步骤,而又不会走得太远而导致意外导致性能下降? 在TRPO试图通过复杂的二阶方法解决此问题的地方,PPO是一阶方法的族,它使用其他一些技巧来使新策略接近于旧策略。 PPO方法实施起来非常简单,并且从经验上看,其性能至少与TRPO相同。

PPO有两种主要变体:PPO-penalty和PPO-clip。

  • PPO-Penalty 近似解决了像TRPO这样的受KL约束的更新,但是对目标函数中的KL偏离进行了惩罚,而不是使其成为硬约束,并且在训练过程中自动调整了惩罚系数,以便对其进行适当缩放。
  • PPO-Clip 在目标中没有KL散度项,也没有任何约束。 取而代之的是依靠对目标函数的专门裁剪来消除新政策消除旧政策的激励。

这里我们将聚焦PPO-clip(OpenAI)

Quick Facts

  • PPO是一个on-policy算法
  • PPO能用于离散或者连续的动作空间
  • Spinningup的PPO支持用MPI并行

Key Equations

PPO-clip更新策略通过: θ k + 1 = arg ⁡ max ⁡ θ E s , a ∼ π θ k [ L ( s , a , θ k , θ ) ] , \theta_{k+1} = \arg \max_{\theta} \underset{s,a \sim \pi_{\theta_k}}{{\mathrm E}}\left[ L(s,a,\theta_k, \theta)\right], θk+1=argθmaxs,aπθkE[L(s,a,θk,θ)],一般用多步(通常minibatch)SGD去最大化目标。这里的 L L L L ( s , a , θ k , θ ) = min ⁡ ( π θ ( a ∣ s ) π θ k ( a ∣ s ) A π θ k ( s , a ) ,      clip ( π θ ( a ∣ s ) π θ k ( a ∣ s ) , 1 − ϵ , 1 + ϵ ) A π θ k ( s , a ) ) , L(s,a,\theta_k,\theta) = \min\left( \frac{\pi_{\theta}(a|s)}{\pi_{\theta_k}(a|s)} A^{\pi_{\theta_k}}(s,a), \;\; \text{clip}\left(\frac{\pi_{\theta}(a|s)}{\pi_{\theta_k}(a|s)}, 1 - \epsilon, 1+\epsilon \right) A^{\pi_{\theta_k}}(s,a) \right), L(s,a,θk,θ)=min(πθk(as)πθ(as)Aπθk(s,a),clip(πθk(as)πθ(as),1ϵ,1+ϵ)Aπθk(s,a)),其中 ϵ \epsilon ϵ是一个较小的超参数,大概地描述新策略与旧策略相距多远。

这是一个较复杂的表述,很难一眼看出它是怎么做的或是如何有助于保持新策略接近旧策略。事实证明,此目标有一个相当简化的版本[1],较容易解决(也是我们在代码中实现的版本): L ( s , a , θ k , θ ) = min ⁡ ( π θ ( a ∣ s ) π θ k ( a ∣ s ) A π θ k ( s , a ) ,      g ( ϵ , A π θ k ( s , a ) ) ) , L(s,a,\theta_k,\theta) = \min\left( \frac{\pi_{\theta}(a|s)}{\pi_{\theta_k}(a|s)} A^{\pi_{\theta_k}}(s,a), \;\; g(\epsilon, A^{\pi_{\theta_k}}(s,a)) \right), L(s,a,θk,θ)=min(πθk(as)πθ(as)Aπθk(s,a),g(ϵ,Aπθk(s,a))),其中 g ( ϵ , A ) = { ( 1 + ϵ ) A A ≥ 0 ( 1 − ϵ ) A A < 0. g(\epsilon, A) = \left\{ \begin{array}{ll} (1 + \epsilon) A & A \geq 0 \\ (1 - \epsilon) A & A < 0. \end{array} \right. g(ϵ,A)={(1+ϵ)A(1ϵ)AA0A<0.为了弄清楚从中得到的直觉,让我们看一下单个状态-动作对 ( s , a ) (s,a) (s,a),并考虑多个案例。

  • Advantage is positive 假设该 状态-动作对 的优势为正,在这种情况下,其对目标的贡献减少为 L ( s , a , θ k , θ ) = min ⁡ ( π θ ( a ∣ s ) π θ k ( a ∣ s ) , ( 1 + ϵ ) ) A π θ k ( s , a ) . L(s,a,\theta_k,\theta) = \min\left( \frac{\pi_{\theta}(a|s)}{\pi_{\theta_k}(a|s)}, (1 + \epsilon) \right) A^{\pi_{\theta_k}}(s,a). L(s,a,θk,θ)=min(πθk(as)πθ(as),(1+ϵ))Aπθk(s,a).因为优势是正的,所以如果采取行动的可能性更大,即 π θ ( a ∣ s ) \pi_\theta(a|s) πθ(as)增加,则目标也会增加。但是此术语中的最小值限制了目标可以增加多少。当 π θ ( a ∣ s ) > ( 1 + ϵ ) π θ k ( a ∣ s ) \pi_\theta(a|s)>(1+\epsilon)\pi_{\theta_k}(a|s) πθ(as)>(1+ϵ)πθk(as),这个式子达到 ( 1 + ϵ ) A π θ k ( s , a ) (1+\epsilon)A^{\pi_{\theta_k}}(s,a) (1+ϵ)Aπθk(s,a)的上限.因此新政策不会因远离旧政策而受益。
  • Advantage is negative: 假设该状态对对的优势为负,在这种情况下,其对目标的贡献减少为 L ( s , a , θ k , θ ) = max ⁡ ( π θ ( a ∣ s ) π θ k ( a ∣ s ) , ( 1 − ϵ ) ) A π θ k ( s , a ) . L(s,a,\theta_k,\theta) = \max\left( \frac{\pi_{\theta}(a|s)}{\pi_{\theta_k}(a|s)}, (1 - \epsilon) \right) A^{\pi_{\theta_k}}(s,a). L(s,a,θk,θ)=max(πθk(as)πθ(as),(1ϵ))Aπθk(s,a).因为优势是负面的,所以如果行动的可能性降低,即 π θ ( a ∣ s ) \pi_\theta(a|s) πθ(as)减小,则目标将增加。但是这个式子的最大值限制了目标增加的多少。当 π θ ( a ∣ s ) < ( 1 − ϵ ) π θ k ( a ∣ s ) \pi_\theta(a|s)<(1-\epsilon)\pi_{\theta_k}(a|s) πθ(as)<(1ϵ)πθk(as), 式子达到最大值 ( 1 − ϵ ) A π θ k ( s , a ) (1-\epsilon)A^{\pi_{\theta_k}}(s,a) (1ϵ)Aπθk(s,a).因此,再次:新政策不会因远离旧政策而受益。

到目前为止,我们看到的是clipping作为一种调节器消除策略急剧变化的激励,而超参数ε则对应于新政策与旧政策的距离有多远,同时仍然有利于实现目标。

[1]https://drive.google.com/file/d/1PDzn9RPvaXjJFZkGeapMHbHGiWWW20Ey/view?usp=sharing

尽管这种clipping对确保合理的策略更新大有帮助,但仍然有可能最终产生与旧策略相距太远的新策略,并且不同的PPO实现使用了很多技巧来避免这种情况 关。 在此处的实现中,我们使用一种特别简单的方法:提前停止。 如果新政策与旧政策的平均KL差距超出阈值,我们将停止采取梯度步骤。
如果您对基本的数学知识和实施细节感到满意,则有必要查看其他实施以了解它们如何处理此问题!

Exploration vs. Exploitation

PPO以一种基于策略的方式训练随机策略。 这意味着它将根据最新版本的随机策略通过采样操作来进行探索。 动作选择的随机性取决于初始条件和训练程序。 在培训过程中,由于更新规则鼓励该策略利用已发现的奖励,因此该策略通常变得越来越少随机性。 这可能会导致策略陷入局部最优状态。

Pseudocode

在这里插入图片描述

Documentaton

spinup.ppo(env_fn, actor_critic=, ac_kwargs={}, seed=0, steps_per_epoch=4000, epochs=50, gamma=0.99, clip_ratio=0.2, pi_lr=0.0003, vf_lr=0.001, train_pi_iters=80, train_v_iters=80, lam=0.97, max_ep_len=1000, target_kl=0.01, logger_kwargs={}, save_freq=10)
Parameters:

  • env_fn – A function which creates a copy of the environment. The environment must satisfy the OpenAI Gym API.
  • actor_critic – A function which takes in placeholder symbols for state, x_ph, and action, a_ph, and returns the main outputs from the agent’s Tensorflow computation graph:在这里插入图片描述
  • ac_kwargs (dict) – Any kwargs appropriate for the actor_critic function you provided to PPO.
  • seed (int) – Seed for random number generators.
  • steps_per_epoch (int) – Number of steps of interaction (state-action pairs) for the agent and the environment in each epoch.
  • epochs (int) – Number of epochs of interaction (equivalent to number of policy updates) to perform.
  • gamma (float) – Discount factor. (Always between 0 and 1.)
  • clip_ratio (float) – Hyperparameter for clipping in the policy objective. Roughly: how far can the new policy go from the old policy while still profiting (improving the objective function)? The new policy can still go farther than the clip_ratio says, but it doesn’t help on the objective anymore. (Usually small, 0.1 to 0.3.)
  • pi_lr (float) – Learning rate for policy optimizer.
  • vf_lr (float) – Learning rate for value function optimizer.
  • train_pi_iters (int) – Maximum number of gradient descent steps to take on policy loss per epoch. (Early stopping may cause optimizer to take fewer than this.)
  • train_v_iters (int) – Number of gradient descent steps to take on value function per epoch.
  • lam (float) – Lambda for GAE-Lambda. (Always between 0 and 1, close to 1.)
  • max_ep_len (int) – Maximum length of trajectory / episode / rollout.
  • target_kl (float) – Roughly what KL divergence we think is appropriate between new and old policies after an update. This will get used for early stopping. (Usually small, 0.01 or 0.05.)
  • logger_kwargs (dict) – Keyword args for EpochLogger.
  • save_freq (int) – How often (in terms of gap between epochs) to save the current policy and value function.
PPO-PID控制算法并不是一个标准术语,通常它可能指的是将**比例-积分-微分(PID)控制**与**近端策略优化(PPO,Proximal Policy Optimization)**结合的一种混合控制方法。以下是相关介绍: ### 1. PID控制基础 PID控制是一种经典的控制算法,广泛应用于工业控制系统中。它通过计算误差的比例(P)、积分(I)和微分(D)来调节控制量,公式如下: \[ u(t) = K_p e(t) + K_i \int_0^t e(\tau) d\tau + K_d \frac{de(t)}{dt} \] 其中: - \( e(t) \) 是设定值与实际值的误差; - \( K_p, K_i, K_d \) 分别是比例、积分和微分系数。 ### 2. PPO算法基础 PPO是一种强化学习算法,属于策略梯度方法的一种。它通过优化策略函数来最大化累积奖励,同时避免策略更新过大导致性能下降。PPO的核心思想是限制策略更新的幅度,通常通过裁剪目标函数来实现。 ### 3. PPO-PID结合的思路 将PPO与PID结合的目的是利用强化学习PPO)的自主学习能力来优化PID控制器的参数(\( K_p, K_i, K_d \)),从而适应复杂或动态变化的环境。具体步骤如下: 1. **初始化PID参数**:随机或基于经验初始化 \( K_p, K_i, K_d \)。 2. **定义状态和动作**: - 状态:可以是系统的当前状态(如误差、误差变化率等)。 - 动作:调整PID参数(如 \( \Delta K_p, \Delta K_i, \Delta K_d \))。 3. **定义奖励函数**:根据控制性能(如超调量、稳定时间、稳态误差等)设计奖励函数。 4. **训练PPO模型**:通过与环境交互(即应用PID控制器并观察系统响应),PPO学习如何调整PID参数以最大化累积奖励。 5. **部署优化后的PID控制器**:训练完成后,使用优化后的PID参数进行实际控制。 ### 示例代码(简化版) 以下是一个简化的PPO-PID结合的伪代码示例: ```python import numpy as np import torch import torch.optim as optim from torch.distributions import Normal class PPO_PID: def __init__(self, state_dim, action_dim): self.actor = torch.nn.Linear(state_dim, action_dim) # 策略网络,输出PID参数调整量 self.critic = torch.nn.Linear(state_dim, 1) # 价值网络 self.optimizer = optim.Adam(self.parameters(), lr=1e-3) def select_action(self, state): # 根据状态选择动作(调整PID参数) action_mean = self.actor(state) action_std = torch.ones_like(action_mean) * 0.1 dist = Normal(action_mean, action_std) action = dist.sample() return action def update(self, states, actions, rewards, next_states, dones): # PPO更新逻辑(简化版) # 计算优势函数和价值函数损失 # 裁剪目标函数并更新网络 pass # 初始化 state_dim = 2 # 例如:误差和误差变化率 action_dim = 3 # 调整 K_p, K_i, K_d ppo_pid = PPO_PID(state_dim, action_dim) # 训练循环 for episode in range(1000): states, actions, rewards, next_states, dones = [], [], [], [], [] state = get_initial_state() # 获取初始状态 for t in range(100): action = ppo_pid.select_action(torch.FloatTensor(state)) next_state, reward, done = apply_pid_and_step(state, action) # 应用PID并获取系统响应 states.append(state) actions.append(action) rewards.append(reward) next_states.append(next_state) dones.append(done) state = next_state if done: break ppo_pid.update(states, actions, rewards, next_states, dones) ``` ### 4. 应用场景 PPO-PID结合的方法适用于以下场景: - 系统动态特性复杂或未知; - 环境变化频繁,传统PID参数难以适应; - 需要自适应调整PID参数以提高控制性能。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值