设计需求网站,没有办公地点怎么注册自己的公司,精品网站设计欣赏,整合营销传播的方法包括基于生成对抗网络的模仿学习#xff0c;假设存在一个专家智能体#xff0c;其策略可以看成最优策略#xff0c;我们就可以通过直接模仿这个专家在环境中交互的动作数据来训练一个策略#xff0c;并不需要用到环境提供的奖励信息。 生成对抗模仿学习GAIL实质上就是模仿了专家… 基于生成对抗网络的模仿学习假设存在一个专家智能体其策略可以看成最优策略我们就可以通过直接模仿这个专家在环境中交互的动作数据来训练一个策略并不需要用到环境提供的奖励信息。 生成对抗模仿学习GAIL实质上就是模仿了专家策略的占用度量即尽量使得策略在环境中的所有状态动作对(s,a) 的占用度量和专家策略的占用度量一致。 占用度量表示状态动作对(s,a) 被访问到的概率。 GAIL中有一个判别器和一个策略策略相当于生成对抗网络中的生成器给定一个状态策略会输出这个状态下一个采取的动作而判别器将状态动作对(s,a) 作为输入输出一个0到1的实数表示判别器认为该状态动作对(s,a) 是来自智能体策略而非专家的概率。判别器的目标是尽可能将专家数据的输出靠近0将模仿者策略的输出靠近1这样就可以将两组数据分辨开来。 有了判别器之后模仿者策略的目标就是其交互产生的轨迹能被判别器误认为专家轨迹。于是我们就可以用判别器的输出作为奖励函数来训练模仿者策略。具体来说若模仿者策略在环境中采样得到状态S ,并且采取动作a ,此时该动作对s,a会输入到判别器D中输出D(s,a)的值然后将奖励设置为r(s,a) -logD(s,a)。于是我们可以用任意强化学习算法使用这些数据继续训练模仿者策略。最后在对抗过程不断进行后模仿者策略生成的数据分布将接近真实的专家数据分布达到模仿学习的目标。
代码实践
生成专家数据
首先我们需要一定量的专家数据为此预先通过PPO算法训练出一个表现良好的专家模型再利用专家模型生成专家数据。
import gym
import torch
import torch.nn.functional as F
import torch.nn.as nn
import numpy as np
import matplotlib.pyplot as plt
from tqdm import tqdm
import random
import rl_utils
class PolicyNet(torch.nn.Module):def __init__(self,state_dim,hidden_dim,action_dim):super(PolicyNet,self).__init__()self.fc1 torch.nn.Linear(state_dim,hidden_dim)self.fc2 toech.nn.Linear(hidden_dim,action_dim)def forward(self,x):x F.relu(self.fc1(x))return F.softmax(self.fc2(x),dim1)class ValueNet(torch.nn.Module):def __init__(self,state_dim,hidden_dim):super(ValueNet,self).__init__()self.fc1 torch.nn.Linear(state_dim,hidden_dim)self.fc2 torch.nn.Linear(hidden_dim,1)def forward(self,x):x F.relu(self.fc1(x))return self.fc2(x)
class PPO:def__init__(self,state_dim,action_dim,actor_lr,critic_lr,lmbda,epochs,
eps,gamma,device):self.actor PolicyNet(state_dim,hidden_dim,action_dim).to(device)self.critic ValueNet(state_dim,hidden_dim).to(device)self.actor_optimizer torch,optim.Adam(self.actor.parameters(),lr actor_lr)self.critic_optimizer torch.optim.Adam(self.critic.parameters(),lr critic_lr)self.gamma gammaself.lmbda lmbdaself.epochs epochs#一条序列的数据用于训练数据self.eps eps #PPO中截断范围的参数self.device devicedef take_action(self,state):state torch.tensor([state],dtypetorch.float).to(self.device)probs self.actor(state)action_dist torch.distributions.Categorical(probs) #离散概率发布action action_dist.sample()return action.item()def update(self,transition_dict):state torch.tensor(transition_dict[states],dtypetorch.float).to(self.device)actions torch.tensor(transition_dict[actions]).view(-1,1).to(self.device)rewards torch.tensor(transition_dict[rewards]).view(-1,1).to(self.device)next_states torch.tensor(transition_dict[next_states]).view(-1,1)
.to(self.device)dones torch.tensor(transition_dict[dones]).view(-1,1)
.to(self.device)td_target rewards self.gamma * self.critic(next_states) * (1-dones)td_delta td_target - self.critic(states)advantage rl_utils.compute_advantage(self.gamma,self.lmbda,td_delta.cpu()).to(self.device)old_log_probs torch.log(self.actor(states).gather(1,actions)).detach()for _ in range(self.epochs):log_probs torch.log(self.actor(states).gather(1,actions))ratio torch.exp(log_probs - old_log_probs)surr1 ratio * adaventagesurr2 torch.clamp(ratio1-self.eps,1eps) * advantage #截断 #限制范围actor_loss torch.mean(-torch.min(surr1,surr2)) #PPO损失函数critic_loss torch.mean(F.mse_loss(self.critic(states),td_target,detach())) #评论家的损失self.actor_optimizer.zero_grad()self.critic_optimizer.zero_grad()actor_loss.backward()critic_loss.backward()self.actor_optimizer.step()self.critic_optimizer.step()
接下来开始生成专家数据我们只生成一条轨迹并从中采样30个状态动作样本(s,a)。我们只用者30个专家数据样本来训练模仿策略。
def sample_-expert_data(n_episode):states []actions []for episode in range(n_episode):state env.reset()done Falsewhile not done:action ppo_agent.take_action(state)states.append(state)actions.append(action)next_state,reward,done,_ env.step(action)state next_statereturn np.array(states),np.array(actions)行为克隆的代码
在BC中我们将专家数据中(st,at)的at视为标签行为克隆算法BC则转化为监督学习中经典的分类问题采用最大似然估计的训练方法可得到分类结果。
class BehaviorClone:def __init__(self,state_dim,hidden_dim,action_dim,lr):self.policy policyNet(state_dim,hidden_dim,action_dim).to(device)self.optimizer torch.optim.Adam(self.policy.parameters(),lrlr)def learn(self,states,actions):states torch.tensor(states,dtypetorch.float).to(device)actions torch.tensor(actions).view(-1,1).to(device)log_probs torch.log(self.policy(states).gather(1,actions))bc_loss torch.mean(-log_probs) #最大似然估计self.optimizer.zero_grad()bc_loss.backward() #关键用最大似然估计来更新网络使其更接近专家系统self.optimizer.step()def take_action(self,state):state torch.tensor([state],dtypetorch.float).to(device)probs self.policy(state)action_dist torch.distributions.Categorical(probs)action action_dist.sample()return action.item()def test_agent(agent,env,n_episode):return_list []for episode in range(n_episode):episode_return 0state env.reset()done Falsewhile not done:action agent.take_action(state)next_state,reward,done,_ env.step(action)state next_stateepisode_return rewardreturn_list.append(episode_return)return np.mean(return_list)我们发现BC无法学习到最优策略这主要是因为在数据量比较少的情况下容易发生过拟合
生成对抗模仿学习的代码
接下来我们实现GAIL的代码
首先实现判别器模型其模型架构为一个两层的全连接网络模型输入一个状态动作对输出一个概率标量。
class Discriminator(nn.Module):def __init__(self,state_dim,hidden_dim,action_dim):super(Discriminator,self).__init__()self.fc1 torch.nn.Linear(state_dimaction_dim,hidden_dim)self.fc2 torch.nn.Linear(hidden_dim,1)def forward(self,x,a):cat torch.cat([x,a],dim1)x F.relu(self.fc1(cat))return torch.sigmoid(self.fc2(x))接下来正式实现GAIL的代码在每一轮迭代中GAIL中的策略和环境进行交互采样新的状态动作对。基于专家数据和策略新采样的数据首先训练判别器然后将判别器的输出转换为策略的奖励信号指导策略用PPO算法做训练。
class GAIL:def __init__(self,agent,state_dim,action_dim,hidden_dim,lr_d):self.discriminator Discriminator(state_dim,hidden_dim,action_dim).to(device)self.discriminator_optimizer torch.optim.Adam(self.discriminator,parameters(),
lr lr_d)self.agent agentdef learn(self,expert_s,expert_a,agent_s,agent_a,next_s,done):expert_states torch.tensor(expert_s,dtypetorch.float).to(device)expert_actions torch.tensor(expert_a).to(device)agent_states torch.tensor(agent_s,dtype torch.float).to(device)agent_actions torch.tensor(agent_a).to(device)expert_actions F.one_hot(expert_actions,num_classes 2).float()agent_actions F.one_hot(agent_actions,num_classes2).float()expert_prob self.discriminator(expert_states,expert_actions)agent_prob self.discriminator(agent_states,agent_actions)discriminator_loss nn.BCELoss()(agent_prob,torch.ones_like(agent_prob))nn.BCELoss()(expert_prob,torch.zeros_like(expert_probs))self.discriminator_optimizer.zero_grad()discriminator_loss .backward()self.discriminator_optimizer.step()reward -torch.log(agent_prob).detach().cpu().numpy() #使用鉴别器输出的概率计算代理的奖励奖励为负对数概率。这种奖励机制鼓励代理生成的数据更接近真实数据。transition_dict {states:agent_s,actions:agent_a,rewards:rewards,next_states:next_s,dones:dones}self.agent.update(transition_dict)几个关键点
鉴别器的作用鉴别器用于区分专家数据和代理生成的数据其输出的概率用于计算代理的奖励。奖励计算通过负对数概率计算奖励使得代理在生成数据时更倾向于生成与专家数据相似的样本。
代理更新使用计算得到的奖励和其他数据来更新代理的策略使其更好地模仿专家的行为。 通过上面的实验对比我们可以直观地感受到在数据样本有限的情况下BC不能学习到最优策略但是GAIL在相同的专家数据下可以取得非常好的结果这一方面归因于GAIL的训练目标拉近策略和专家的占用度十分贴合模仿学习任务的目标避免了BC中的复合误差问题另一方面得益于在GAIL的训练中策略可以和环境交互出更多的数据以此训练判别器进而生成对基于策略“量身定做”的指导奖励信号。