0
  • 聊天消息
  • 系统消息
  • 评论与回复
登录后你可以
  • 下载海量资料
  • 学习在线课程
  • 观看技术视频
  • 写文章/发帖/加入社区
创作中心

完善资料让更多小伙伴认识你,还能领取20积分哦,立即完善>

3天内不再提示

7个流行的强化学习算法及代码实现

颖脉Imgtec 2023-02-06 15:06 次阅读

作者:Siddhartha Pramanik来源:DeepHub IMBA


目前流行的强化学习算法包括 Q-learning、SARSA、DDPG、A2C、PPO、DQN 和 TRPO。这些算法已被用于在游戏、机器人和决策制定等各种应用中,并且这些流行的算法还在不断发展和改进,本文我们将对其做一个简单的介绍。

7653da42-a421-11ed-ad0d-dac502259ad0.png


1、Q-learningQ-learning:Q-learning 是一种无模型、非策略的强化学习算法。它使用 Bellman 方程估计最佳动作值函数,该方程迭代地更新给定状态动作对的估计值。Q-learning 以其简单性和处理大型连续状态空间的能力而闻名。下面是一个使用 Python 实现 Q-learning 的简单示例:

import numpy as np # Define the Q-table and the learning rate Q = np.zeros((state_space_size, action_space_size)) alpha = 0.1 # Define the exploration rate and discount factor epsilon = 0.1 gamma = 0.99 for episode in range(num_episodes): current_state = initial_state while not done: # Choose an action using an epsilon-greedy policy if np.random.uniform(0, 1) < epsilon: action = np.random.randint(0, action_space_size) else: action = np.argmax(Q[current_state]) # Take the action and observe the next state and reward next_state, reward, done = take_action(current_state, action) # Update the Q-table using the Bellman equation Q[current_state, action] = Q[current_state, action] + alpha * (reward + gamma * np.max(Q[next_state]) - Q[current_state, action]) current_state = next_state

上面的示例中,state_space_size 和 action_space_size 分别是环境中的状态数和动作数。num_episodes 是要为运行算法的轮次数。initial_state 是环境的起始状态。take_action(current_state, action) 是一个函数,它将当前状态和一个动作作为输入,并返回下一个状态、奖励和一个指示轮次是否完成的布尔值。

在 while 循环中,使用 epsilon-greedy 策略根据当前状态选择一个动作。使用概率 epsilon选择一个随机动作,使用概率 1-epsilon选择对当前状态具有最高 Q 值的动作。采取行动后,观察下一个状态和奖励,使用Bellman方程更新q。并将当前状态更新为下一个状态。这只是 Q-learning 的一个简单示例,并未考虑 Q-table 的初始化和要解决的问题的具体细节。


2、SARSASARSA:SARSA 是一种无模型、基于策略的强化学习算法。它也使用Bellman方程来估计动作价值函数,但它是基于下一个动作的期望值,而不是像 Q-learning 中的最优动作。SARSA 以其处理随机动力学问题的能力而闻名。

import numpy as np # Define the Q-table and the learning rate Q = np.zeros((state_space_size, action_space_size)) alpha = 0.1 # Define the exploration rate and discount factor epsilon = 0.1 gamma = 0.99 for episode in range(num_episodes): current_state = initial_state action = epsilon_greedy_policy(epsilon, Q, current_state) while not done: # Take the action and observe the next state and reward next_state, reward, done = take_action(current_state, action) # Choose next action using epsilon-greedy policy next_action = epsilon_greedy_policy(epsilon, Q, next_state) # Update the Q-table using the Bellman equation Q[current_state, action] = Q[current_state, action] + alpha * (reward + gamma * Q[next_state, next_action] - Q[current_state, action]) current_state = next_state action = next_action

state_space_size和action_space_size分别是环境中的状态和操作的数量。num_episodes是您想要运行SARSA算法的轮次数。Initial_state是环境的初始状态。take_action(current_state, action)是一个将当前状态和作为操作输入的函数,并返回下一个状态、奖励和一个指示情节是否完成的布尔值。

在while循环中,使用在单独的函数epsilon_greedy_policy(epsilon, Q, current_state)中定义的epsilon-greedy策略来根据当前状态选择操作。使用概率 epsilon选择一个随机动作,使用概率 1-epsilon对当前状态具有最高 Q 值的动作。上面与Q-learning相同,但是采取了一个行动后,在观察下一个状态和奖励时它然后使用贪心策略选择下一个行动。并使用Bellman方程更新q表。


3、DDPGDDPG 是一种用于连续动作空间的无模型、非策略算法。它是一种actor-critic算法,其中actor网络用于选择动作,而critic网络用于评估动作。DDPG 对于机器人控制和其他连续控制任务特别有用。

import numpy as np from keras.models import Model, Sequential from keras.layers import Dense, Input from keras.optimizers import Adam # Define the actor and critic models actor = Sequential() actor.add(Dense(32, input_dim=state_space_size, activation='relu')) actor.add(Dense(32, activation='relu')) actor.add(Dense(action_space_size, activation='tanh')) actor.compile(loss='mse', optimizer=Adam(lr=0.001)) critic = Sequential() critic.add(Dense(32, input_dim=state_space_size, activation='relu')) critic.add(Dense(32, activation='relu')) critic.add(Dense(1, activation='linear')) critic.compile(loss='mse', optimizer=Adam(lr=0.001)) # Define the replay buffer replay_buffer = [] # Define the exploration noise exploration_noise = OrnsteinUhlenbeckProcess(size=action_space_size, theta=0.15, mu=0, sigma=0.2) for episode in range(num_episodes): current_state = initial_state while not done: # Select an action using the actor model and add exploration noise action = actor.predict(current_state)[0] + exploration_noise.sample() action = np.clip(action, -1, 1) # Take the action and observe the next state and reward next_state, reward, done = take_action(current_state, action) # Add the experience to the replay buffer replay_buffer.append((current_state, action, reward, next_state, done)) # Sample a batch of experiences from the replay buffer batch = sample(replay_buffer, batch_size) # Update the critic model states = np.array([x[0] for x in batch]) actions = np.array([x[1] for x in batch]) rewards = np.array([x[2] for x in batch]) next_states = np.array([x[3] for x in batch]) target_q_values = rewards + gamma * critic.predict(next_states) critic.train_on_batch(states, target_q_values) # Update the actor model action_gradients = np.array(critic.get_gradients(states, actions)) actor.train_on_batch(states, action_gradients) current_state = next_state

在本例中,state_space_size和action_space_size分别是环境中的状态和操作的数量。num_episodes是轮次数。Initial_state是环境的初始状态。Take_action (current_state, action)是一个函数,它接受当前状态和操作作为输入,并返回下一个操作。


4、A2CA2C(Advantage Actor-Critic)是一种有策略的actor-critic算法,它使用Advantage函数来更新策略。该算法实现简单,可以处理离散和连续的动作空间。

import numpy as np from keras.models import Model, Sequential from keras.layers import Dense, Input from keras.optimizers import Adam from keras.utils import to_categorical # Define the actor and critic models state_input = Input(shape=(state_space_size,)) actor = Dense(32, activation='relu')(state_input) actor = Dense(32, activation='relu')(actor) actor = Dense(action_space_size, activation='softmax')(actor) actor_model = Model(inputs=state_input, outputs=actor) actor_model.compile(loss='categorical_crossentropy', optimizer=Adam(lr=0.001)) state_input = Input(shape=(state_space_size,)) critic = Dense(32, activation='relu')(state_input) critic = Dense(32, activation='relu')(critic) critic = Dense(1, activation='linear')(critic) critic_model = Model(inputs=state_input, outputs=critic) critic_model.compile(loss='mse', optimizer=Adam(lr=0.001)) for episode in range(num_episodes): current_state = initial_state done = False while not done: # Select an action using the actor model and add exploration noise action_probs = actor_model.predict(np.array([current_state]))[0] action = np.random.choice(range(action_space_size), p=action_probs) # Take the action and observe the next state and reward next_state, reward, done = take_action(current_state, action) # Calculate the advantage target_value = critic_model.predict(np.array([next_state]))[0][0] advantage = reward + gamma * target_value - critic_model.predict(np.array([current_state]))[0][0] # Update the actor model action_one_hot = to_categorical(action, action_space_size) actor_model.train_on_batch(np.array([current_state]), advantage * action_one_hot) # Update the critic model critic_model.train_on_batch(np.array([current_state]), reward + gamma * target_value) current_state = next_state

在这个例子中,actor模型是一个神经网络,它有2个隐藏层,每个隐藏层有32个神经元,具有relu激活函数,输出层具有softmax激活函数。critic模型也是一个神经网络,它有2个隐含层,每层32个神经元,具有relu激活函数,输出层具有线性激活函数。使用分类交叉熵损失函数训练actor模型,使用均方误差损失函数训练critic模型。动作是根据actor模型预测选择的,并添加了用于探索的噪声。


5、PPOPPO(Proximal Policy Optimization)是一种策略算法,它使用信任域优化的方法来更新策略。它在具有高维观察和连续动作空间的环境中特别有用。PPO 以其稳定性和高样品效率而著称。

import numpy as np from keras.models import Model, Sequential from keras.layers import Dense, Input from keras.optimizers import Adam # Define the policy model state_input = Input(shape=(state_space_size,)) policy = Dense(32, activation='relu')(state_input) policy = Dense(32, activation='relu')(policy) policy = Dense(action_space_size, activation='softmax')(policy) policy_model = Model(inputs=state_input, outputs=policy) # Define the value model value_model = Model(inputs=state_input, outputs=Dense(1, activation='linear')(policy)) # Define the optimizer optimizer = Adam(lr=0.001) for episode in range(num_episodes): current_state = initial_state while not done: # Select an action using the policy model action_probs = policy_model.predict(np.array([current_state]))[0] action = np.random.choice(range(action_space_size), p=action_probs) # Take the action and observe the next state and reward next_state, reward, done = take_action(current_state, action) # Calculate the advantage target_value = value_model.predict(np.array([next_state]))[0][0] advantage = reward + gamma * target_value - value_model.predict(np.array([current_state]))[0][0] # Calculate the old and new policy probabilities old_policy_prob = action_probs[action] new_policy_prob = policy_model.predict(np.array([next_state]))[0][action] # Calculate the ratio and the surrogate loss ratio = new_policy_prob / old_policy_prob surrogate_loss = np.minimum(ratio * advantage, np.clip(ratio, 1 - epsilon, 1 + epsilon) * advantage) # Update the policy and value models policy_model.trainable_weights = value_model.trainable_weights policy_model.compile(optimizer=optimizer, loss=-surrogate_loss) policy_model.train_on_batch(np.array([current_state]), np.array([action_one_hot])) value_model.train_on_batch(np.array([current_state]), reward + gamma * target_value) current_state = next_state


6、DQNDQN(深度 Q 网络)是一种无模型、非策略算法,它使用神经网络来逼近 Q 函数。DQN 特别适用于 Atari 游戏和其他类似问题,其中状态空间是高维的,并使用神经网络近似 Q 函数。

import numpy as np from keras.models import Sequential from keras.layers import Dense, Input from keras.optimizers import Adam from collections import deque # Define the Q-network model model = Sequential() model.add(Dense(32, input_dim=state_space_size, activation='relu')) model.add(Dense(32, activation='relu')) model.add(Dense(action_space_size, activation='linear')) model.compile(loss='mse', optimizer=Adam(lr=0.001)) # Define the replay buffer replay_buffer = deque(maxlen=replay_buffer_size) for episode in range(num_episodes): current_state = initial_state while not done: # Select an action using an epsilon-greedy policy if np.random.rand() < epsilon: action = np.random.randint(0, action_space_size) else: action = np.argmax(model.predict(np.array([current_state]))[0]) # Take the action and observe the next state and reward next_state, reward, done = take_action(current_state, action) # Add the experience to the replay buffer replay_buffer.append((current_state, action, reward, next_state, done)) # Sample a batch of experiences from the replay buffer batch = random.sample(replay_buffer, batch_size) # Prepare the inputs and targets for the Q-network inputs = np.array([x[0] for x in batch]) targets = model.predict(inputs) for i, (state, action, reward, next_state, done) in enumerate(batch): if done: targets[i, action] = reward else: targets[i, action] = reward + gamma * np.max(model.predict(np.array([next_state]))[0]) # Update the Q-network model.train_on_batch(inputs, targets) current_state = next_state

上面的代码,Q-network有2个隐藏层,每个隐藏层有32个神经元,使用relu激活函数。该网络使用均方误差损失函数和Adam优化器进行训练。


7、TRPOTRPO (Trust Region Policy Optimization)是一种无模型的策略算法,它使用信任域优化方法来更新策略。它在具有高维观察和连续动作空间的环境中特别有用。TRPO 是一个复杂的算法,需要多个步骤和组件来实现。TRPO不是用几行代码就能实现的简单算法。所以我们这里使用实现了TRPO的现有库,例如OpenAI Baselines,它提供了包括TRPO在内的各种预先实现的强化学习算法,。要在OpenAI Baselines中使用TRPO,我们需要安装:

pip install baselines

然后可以使用baselines库中的trpo_mpi模块在你的环境中训练TRPO代理,这里有一个简单的例子:

import gym from baselines.common.vec_env.dummy_vec_env import DummyVecEnv from baselines.trpo_mpi import trpo_mpi #Initialize the environment env = gym.make("CartPole-v1") env = DummyVecEnv([lambda: env]) # Define the policy network policy_fn = mlp_policy #Train the TRPO model model = trpo_mpi.learn(env, policy_fn, max_iters=1000)

我们使用Gym库初始化环境。然后定义策略网络,并调用TRPO模块中的learn()函数来训练模型。还有许多其他库也提供了TRPO的实现,例如TensorFlow、PyTorch和RLLib。下面时一个使用TF 2.0实现的样例:

import tensorflow as tf import gym # Define the policy network class PolicyNetwork(tf.keras.Model): def __init__(self): super(PolicyNetwork, self).__init__() self.dense1 = tf.keras.layers.Dense(16, activation='relu') self.dense2 = tf.keras.layers.Dense(16, activation='relu') self.dense3 = tf.keras.layers.Dense(1, activation='sigmoid') def call(self, inputs): x = self.dense1(inputs) x = self.dense2(x) x = self.dense3(x) return x # Initialize the environment env = gym.make("CartPole-v1") # Initialize the policy network policy_network = PolicyNetwork() # Define the optimizer optimizer = tf.optimizers.Adam() # Define the loss function loss_fn = tf.losses.BinaryCrossentropy() # Set the maximum number of iterations max_iters = 1000 # Start the training loop for i in range(max_iters): # Sample an action from the policy network action = tf.squeeze(tf.random.categorical(policy_network(observation), 1)) # Take a step in the environment observation, reward, done, _ = env.step(action) with tf.GradientTape() as tape: # Compute the loss loss = loss_fn(reward, policy_network(observation)) # Compute the gradients grads = tape.gradient(loss, policy_network.trainable_variables) # Perform the update step optimizer.apply_gradients(zip(grads, policy_network.trainable_variables)) if done: # Reset the environment observation = env.reset()

在这个例子中,我们首先使用TensorFlow的Keras API定义一个策略网络。然后使用Gym库和策略网络初始化环境。然后定义用于训练策略网络的优化器和损失函数。在训练循环中,从策略网络中采样一个动作,在环境中前进一步,然后使用TensorFlow的GradientTape计算损失和梯度。然后我们使用优化器执行更新步骤。这是一个简单的例子,只展示了如何在TensorFlow 2.0中实现TRPO。TRPO是一个非常复杂的算法,这个例子没有涵盖所有的细节,但它是试验TRPO的一个很好的起点。


总结

以上就是我们总结的7个常用的强化学习算法,这些算法并不相互排斥,通常与其他技术(如值函数逼近、基于模型的方法和集成方法)结合使用,可以获得更好的结果。

声明:本文内容及配图由入驻作者撰写或者入驻合作网站授权转载。文章观点仅代表作者本人,不代表电子发烧友网立场。文章及其配图仅供工程师学习之用,如有内容侵权或者其他违规问题,请联系本站处理。 举报投诉
  • 人工智能
    +关注

    关注

    1776

    文章

    43845

    浏览量

    230602
  • 强化学习
    +关注

    关注

    4

    文章

    259

    浏览量

    11114
收藏 人收藏

    评论

    相关推荐

    什么是强化学习

    强化学习是机器学习的方式之一,它与监督学习、无监督学习并列,是三种机器学习训练方法之一。 在围棋上击败世界第一李世石的 AlphaGo、在《
    的头像 发表于 10-30 11:36 1643次阅读
    什么是<b class='flag-5'>强化学习</b>

    NeurIPS 2023 | 扩散模型解决多任务强化学习问题

    扩散模型(diffusion model)在 CV 领域甚至 NLP 领域都已经有了令人印象深刻的表现。最近的一些工作开始将 diffusion model 用于强化学习(RL)中来解决序列决策问题
    的头像 发表于 10-02 10:45 447次阅读
    NeurIPS 2023 | 扩散模型解决多任务<b class='flag-5'>强化学习</b>问题

    模拟矩阵在深度强化学习智能控制系统中的应用

    讯维模拟矩阵在深度强化学习智能控制系统中的应用主要是通过构建一个包含多种环境信息和动作空间的模拟矩阵,来模拟和预测深度强化学习智能控制系统在不同环境下的表现和效果,从而优化控制策略和提高系统的性能
    的头像 发表于 09-04 14:26 327次阅读
    模拟矩阵在深度<b class='flag-5'>强化学习</b>智能控制系统中的应用

    机器学习有哪些算法?机器学习分类算法有哪些?机器学习预判有哪些算法

    机器学习有哪些算法?机器学习分类算法有哪些?机器学习预判有哪些算法? 机器
    的头像 发表于 08-17 16:30 1398次阅读

    语言模型做先验,统一强化学习智能体,DeepMind选择走这条通用AI之路

    在智能体的开发中,强化学习与大语言模型、视觉语言模型等基础模型的进一步融合究竟能擦出怎样的火花?谷歌 DeepMind 给了我们新的答案。 一直以来,DeepMind 引领了强化学习(RL)智能
    的头像 发表于 07-24 16:55 332次阅读
    语言模型做先验,统一<b class='flag-5'>强化学习</b>智能体,DeepMind选择走这条通用AI之路

    基于强化学习的目标检测算法案例

    摘要:基于强化学习的目标检测算法在检测过程中通常采用预定义搜索行为,其产生的候选区域形状和尺寸变化单一,导致目标检测精确度较低。为此,在基于深度强化学习的视觉目标检测算法基础上,提出联
    发表于 07-19 14:35 0次下载

    45. 5 2 强化学习(深度强化学习) #硬声创作季

    机器学习
    充八万
    发布于 :2023年07月07日 01:56:26

    什么是深度强化学习?深度强化学习算法应用分析

    什么是深度强化学习? 众所周知,人类擅长解决各种挑战性的问题,从低级的运动控制(如:步行、跑步、打网球)到高级的认知任务。
    发表于 07-01 10:29 1186次阅读
    什么是深度<b class='flag-5'>强化学习</b>?深度<b class='flag-5'>强化学习</b><b class='flag-5'>算法</b>应用分析

    人工智能强化学习开源分享

    电子发烧友网站提供《人工智能强化学习开源分享.zip》资料免费下载
    发表于 06-20 09:27 1次下载
    人工智能<b class='flag-5'>强化学习</b>开源分享

    利用强化学习来探索更优排序算法的AI系统

    前言 DeepMind 最近在 Nature 发表了一篇论文 AlphaDev[2, 3],一个利用强化学习来探索更优排序算法的AI系统。 AlphaDev 系统直接从 CPU 汇编指令的层面入手
    的头像 发表于 06-19 10:49 393次阅读
    利用<b class='flag-5'>强化学习</b>来探索更优排序<b class='flag-5'>算法</b>的AI系统

    基于深度强化学习的视觉反馈机械臂抓取系统

    机械臂抓取摆放及堆叠物体是智能工厂流水线上常见的工序,可以有效的提升生产效率,本文针对机械臂的抓取摆放、抓取堆叠等常见任务,结合深度强化学习及视觉反馈,采用AprilTag视觉标签、后视经验回放机制
    的头像 发表于 06-12 11:25 1399次阅读
    基于深度<b class='flag-5'>强化学习</b>的视觉反馈机械臂抓取系统

    ICLR 2023 Spotlight|节省95%训练开销,清华黄隆波团队提出强化学习专用稀疏训练框架RLx2

    大模型时代,模型压缩和加速显得尤为重要。传统监督学习可通过稀疏神经网络实现模型压缩和加速,那么同样需要大量计算开销的强化学习任务可以基于稀疏网络进行训练吗?本文提出了一种强化学习专用稀
    的头像 发表于 06-11 21:40 402次阅读
    ICLR 2023 Spotlight|节省95%训练开销,清华黄隆波团队提出<b class='flag-5'>强化学习</b>专用稀疏训练框架RLx2

    彻底改变算法交易:强化学习的力量

    强化学习(RL)是人工智能的一个子领域,专注于决策过程。与其他形式的机器学习相比,强化学习模型通过与环境交互并以奖励或惩罚的形式接收反馈来学习
    发表于 06-09 09:23 370次阅读

    机器学习笔记之优化-拉格朗日乘子法和对偶分解

    优化是机器学习中的关键步骤。在这个机器学习系列中,我们将简要介绍优化问题,然后探讨两种特定的优化方法,即拉格朗日乘子和对偶分解。这两种方法在机器学习强化学习和图模型中非常
    的头像 发表于 05-30 16:47 1428次阅读
    机器<b class='flag-5'>学习</b>笔记之优化-拉格朗日乘子法和对偶分解

    基于多智能体深度强化学习的体系任务分配方法

    为了应对在未来复杂的战场环境下,由于通信受限等原因导致的集中式决策模式难以实施的情况,提出了一个基于多智能体深度强化学习方法的分布式作战体系任务分配算法,该算法为各作战单元均设计一个独立的策略网络
    的头像 发表于 05-18 16:46 2678次阅读
    基于多智能体深度<b class='flag-5'>强化学习</b>的体系任务分配方法