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

article/2025/4/27 11:30:32

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

1、Q-learning

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

下面是一个使用 Python 实现 Q-learning 的简单示例:

 importnumpyasnp# Define the Q-table and the learning rateQ=np.zeros((state_space_size, action_space_size))alpha=0.1# Define the exploration rate and discount factorepsilon=0.1gamma=0.99forepisodeinrange(num_episodes):current_state=initial_statewhilenotdone:# Choose an action using an epsilon-greedy policyifnp.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 rewardnext_state, reward, done=take_action(current_state, action)# Update the Q-table using the Bellman equationQ[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、SARSA

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

 importnumpyasnp# Define the Q-table and the learning rateQ=np.zeros((state_space_size, action_space_size))alpha=0.1# Define the exploration rate and discount factorepsilon=0.1gamma=0.99forepisodeinrange(num_episodes):current_state=initial_stateaction=epsilon_greedy_policy(epsilon, Q, current_state)whilenotdone:# Take the action and observe the next state and rewardnext_state, reward, done=take_action(current_state, action)# Choose next action using epsilon-greedy policynext_action=epsilon_greedy_policy(epsilon, Q, next_state)# Update the Q-table using the Bellman equationQ[current_state, action] =Q[current_state, action] +alpha* (reward+gamma*Q[next_state, next_action] -Q[current_state, action])current_state=next_stateaction=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、DDPG

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

 importnumpyasnpfromkeras.modelsimportModel, Sequentialfromkeras.layersimportDense, Inputfromkeras.optimizersimportAdam# Define the actor and critic modelsactor=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 bufferreplay_buffer= []# Define the exploration noiseexploration_noise=OrnsteinUhlenbeckProcess(size=action_space_size, theta=0.15, mu=0, sigma=0.2)forepisodeinrange(num_episodes):current_state=initial_statewhilenotdone:# Select an action using the actor model and add exploration noiseaction=actor.predict(current_state)[0] +exploration_noise.sample()action=np.clip(action, -1, 1)# Take the action and observe the next state and rewardnext_state, reward, done=take_action(current_state, action)# Add the experience to the replay bufferreplay_buffer.append((current_state, action, reward, next_state, done))# Sample a batch of experiences from the replay bufferbatch=sample(replay_buffer, batch_size)# Update the critic modelstates=np.array([x[0] forxinbatch])actions=np.array([x[1] forxinbatch])rewards=np.array([x[2] forxinbatch])next_states=np.array([x[3] forxinbatch])target_q_values=rewards+gamma*critic.predict(next_states)critic.train_on_batch(states, target_q_values)# Update the actor modelaction_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、A2C

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

 importnumpyasnpfromkeras.modelsimportModel, Sequentialfromkeras.layersimportDense, Inputfromkeras.optimizersimportAdamfromkeras.utilsimportto_categorical# Define the actor and critic modelsstate_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))forepisodeinrange(num_episodes):current_state=initial_statedone=Falsewhilenotdone:# Select an action using the actor model and add exploration noiseaction_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 rewardnext_state, reward, done=take_action(current_state, action)# Calculate the advantagetarget_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 modelaction_one_hot=to_categorical(action, action_space_size)actor_model.train_on_batch(np.array([current_state]), advantage*action_one_hot)# Update the critic modelcritic_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、PPO

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

 importnumpyasnpfromkeras.modelsimportModel, Sequentialfromkeras.layersimportDense, Inputfromkeras.optimizersimportAdam# Define the policy modelstate_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 modelvalue_model=Model(inputs=state_input, outputs=Dense(1, activation='linear')(policy))# Define the optimizeroptimizer=Adam(lr=0.001)forepisodeinrange(num_episodes):current_state=initial_statewhilenotdone:# Select an action using the policy modelaction_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 rewardnext_state, reward, done=take_action(current_state, action)# Calculate the advantagetarget_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 probabilitiesold_policy_prob=action_probs[action]new_policy_prob=policy_model.predict(np.array([next_state]))[0][action]# Calculate the ratio and the surrogate lossratio=new_policy_prob/old_policy_probsurrogate_loss=np.minimum(ratio*advantage, np.clip(ratio, 1-epsilon, 1+epsilon) *advantage)# Update the policy and value modelspolicy_model.trainable_weights=value_model.trainable_weightspolicy_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、DQN

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

 importnumpyasnpfromkeras.modelsimportSequentialfromkeras.layersimportDense, Inputfromkeras.optimizersimportAdamfromcollectionsimportdeque# Define the Q-network modelmodel=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 bufferreplay_buffer=deque(maxlen=replay_buffer_size)forepisodeinrange(num_episodes):current_state=initial_statewhilenotdone:# Select an action using an epsilon-greedy policyifnp.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 rewardnext_state, reward, done=take_action(current_state, action)# Add the experience to the replay bufferreplay_buffer.append((current_state, action, reward, next_state, done))# Sample a batch of experiences from the replay bufferbatch=random.sample(replay_buffer, batch_size)# Prepare the inputs and targets for the Q-networkinputs=np.array([x[0] forxinbatch])targets=model.predict(inputs)fori, (state, action, reward, next_state, done) inenumerate(batch):ifdone:targets[i, action] =rewardelse:targets[i, action] =reward+gamma*np.max(model.predict(np.array([next_state]))[0])# Update the Q-networkmodel.train_on_batch(inputs, targets)current_state=next_state

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

7、TRPO

TRPO (Trust Region Policy Optimization)是一种无模型的策略算法,它使用信任域优化方法来更新策略。 它在具有高维观察和连续动作空间的环境中特别有用。

TRPO 是一个复杂的算法,需要多个步骤和组件来实现。TRPO不是用几行代码就能实现的简单算法。

所以我们这里使用实现了TRPO的现有库,例如OpenAI Baselines,它提供了包括TRPO在内的各种预先实现的强化学习算法,。

要在OpenAI Baselines中使用TRPO,我们需要安装:

 pip install baselines

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

 importgymfrombaselines.common.vec_env.dummy_vec_envimportDummyVecEnvfrombaselines.trpo_mpiimporttrpo_mpi#Initialize the environmentenv=gym.make("CartPole-v1")env=DummyVecEnv([lambda: env])# Define the policy networkpolicy_fn=mlp_policy#Train the TRPO modelmodel=trpo_mpi.learn(env, policy_fn, max_iters=1000)

我们使用Gym库初始化环境。然后定义策略网络,并调用TRPO模块中的learn()函数来训练模型。

还有许多其他库也提供了TRPO的实现,例如TensorFlow、PyTorch和RLLib。下面时一个使用TF 2.0实现的样例

 importtensorflowastfimportgym# Define the policy networkclassPolicyNetwork(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')defcall(self, inputs):x=self.dense1(inputs)x=self.dense2(x)x=self.dense3(x)returnx# Initialize the environmentenv=gym.make("CartPole-v1")# Initialize the policy networkpolicy_network=PolicyNetwork()# Define the optimizeroptimizer=tf.optimizers.Adam()# Define the loss functionloss_fn=tf.losses.BinaryCrossentropy()# Set the maximum number of iterationsmax_iters=1000# Start the training loopforiinrange(max_iters):# Sample an action from the policy networkaction=tf.squeeze(tf.random.categorical(policy_network(observation), 1))# Take a step in the environmentobservation, reward, done, _=env.step(action)withtf.GradientTape() astape:# Compute the lossloss=loss_fn(reward, policy_network(observation))# Compute the gradientsgrads=tape.gradient(loss, policy_network.trainable_variables)# Perform the update stepoptimizer.apply_gradients(zip(grads, policy_network.trainable_variables))ifdone:# Reset the environmentobservation=env.reset()

在这个例子中,我们首先使用TensorFlow的Keras API定义一个策略网络。然后使用Gym库和策略网络初始化环境。然后定义用于训练策略网络的优化器和损失函数。

在训练循环中,从策略网络中采样一个动作,在环境中前进一步,然后使用TensorFlow的GradientTape计算损失和梯度。然后我们使用优化器执行更新步骤。

这是一个简单的例子,只展示了如何在TensorFlow 2.0中实现TRPO。TRPO是一个非常复杂的算法,这个例子没有涵盖所有的细节,但它是试验TRPO的一个很好的起点。

总结

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

https://avoid.overfit.cn/post/82000e3c65a14403b5e4defae28b703b

作者:Siddhartha Pramanik


http://chatgpt.dhexx.cn/article/2kGxlKWZ.shtml

相关文章

流行学习,比较好的一篇博客

转载自&#xff1a;https://blog.csdn.net/sinat_32043495/article/details/78997758 嵌入在高维空间的低维流形 流形&#xff1a;局部具有欧几里得空间性质的空间 1.较好的描述转载 作者&#xff1a;暮暮迷了路 链接&#xff1a;https://www.zhihu.com/question/2401548…

深度学习—近年来流行的卷积神经网络(一)

近年来流行的卷积神经网络 1. 回顾与目标2. 近年来流行的卷积神经网络2.1 VGGNet2.1.1 感受野的概念2.1.2 感受野的计算 2.2 GooleNet2.3 ResNet 3. 结尾参考资料 1. 回顾与目标 前面几讲&#xff0c;我们以LeNet和AlexNet为例&#xff0c;详细讲解了卷积神经网络的结构。从20…

流行学习常用算法

Isomap&#xff1a;等距映射。前提假设为低维空间中的欧式距离等于高维空间中的侧地线距离&#xff0c;当然该算法具体实施时是高维空间中较近点之间的测地线距离用欧式距离代替&#xff0c;较远点距离用测地线距离用最短路径逼近。 LLE:局部线性嵌入。前提假设是数据所在的低维…

流行学习与拉普拉斯变换的推导

参考&#xff1a;拉普拉斯矩阵 参考&#xff1a;流行学习

流行学习初步理解

一. 流形学习的英文名为manifold learning。其主要思想是把一个高维的数据非线性映射到低维&#xff0c;该低维数据能够反映高维数据的本质&#xff0c;当然有一个前提假设就是高维观察数据存在流形结构&#xff0c;其优点是非参数&#xff0c;非线性&#xff0c;求解过程简单。…

流行学习简单入门与理解

最近博主再看西瓜书第十三章半监督学习&#xff0c;文章中作者提到需要少量查询的主动学习、K-means簇的聚类&#xff0c;以及流行学习。对于流行学习&#xff0c;博主也是第一次接触&#xff0c;下面我们来简单学习和理解一下流行学习。 1. 半监督学习 SSL的成立依赖于模型假…

机器学习----流行学习(manifold learning)的通俗理解

流形学习&#xff08;manifold learning&#xff09;是一类借鉴了拓扑流行概念的降维方法&#xff0c;在降维时&#xff0c;若低维流行嵌入到高维空间中&#xff0c;则数据样本在高维空间的分布虽然看上去十分复杂&#xff0c;但在局部上仍具有欧式空间&#xff08;对现实空间的…

流行学习Manifold Learning

文章目录 1、流行学习前言&#xff1a;2、流形学习的概念流形的概念&#xff1a;流行学习的概念&#xff1a; 3、流形学习的分类4、高维数据降维与可视化5、基本问题和个人观点6、参考文献 1、流行学习前言&#xff1a; 流形学习是个很广泛的概念。这里我主要谈的是自从2000年…

关于nn.embedding的理解

import torch.nn as nn nn.Embedding(num_embeddings, embedding_dim, padding_idxNone, max_normNone, norm_type2, scale_grad_by_freqFalse, sparseFalse)参数解释 num_embeddings (python:int) – 词典的大小尺寸&#xff0c;比如总共出现5000个词&#xff0c;那就输入500…

深究embedding层

关于embedding层&#xff0c;贴出一些很好的链接&#xff0c;以供备忘与分享。 http://blog.sina.com.cn/s/blog_1450ac3c60102x79x.html https://blog.csdn.net/sjyttkl/article/details/80324656 https://blog.csdn.net/jiangpeng59/article/details/77533309 https://juejin…

一文搞懂 Embedding !

这篇文章把embedding单独提出来,梳理一下embedding在推荐系统中的应用。以下内容主要从深度学习方法和传统的协同过滤方法两个方面加深和理解在推荐系统领域对embedding的认识,详细解读下“embedding”这一重要思想。 什么是Embedding? Embedding(嵌入)是拓扑学里面的词…

5、Embedding

本文作为个人笔记引用于&#xff1a; https://blog.csdn.net/weixin_42078618/article/details/82999906 https://blog.csdn.net/weixin_42078618/article/details/84553940 https://www.jianshu.com/p/63e7acc5e890 简介 假设&#xff0c;我们中文&#xff0c;一共只有10个字…

embedding

what is emdding embedding就是把字词用向量表示出来&#xff0c;相当于是对字词做encoding motivation 比如 猫&#xff0c;狗&#xff0c;我们当然可以直接把他们表示为一些独立的离散符号&#xff0c;但是这样的表示毫无意义&#xff0c;而且会产生大量稀疏数据。使我们在…

Embeding编码方式

Embeding编码方式概述 独热码&#xff1a;数量大而且过于稀疏&#xff0c;映射之间是独立的&#xff0c;没有表现出关联性。 Embedding&#xff1a;是一种单词编码方法&#xff0c;用低维向量实现了编码&#xff0c;这种编码通过神经网络训练优化&#xff0c;能表达出单词间的…

机器学习中的Embedding

来自知乎的一个解释&#xff1a;&#xff08;版权归原作者所有&#xff0c;仅供学习&#xff0c;禁止商用&#xff09; https://zhuanlan.zhihu.com/p/46016518 解释还是有点感觉迷糊&#xff0c;数学解释&#xff1a; Embedding在数学上表示一个maping, f: X -> Y&#x…

Embedding 编码方法

一、作用 Embedding 是一种单词编码&#xff0c;用低维向量实现了编码&#xff0c;这种编码通过神经网络训练优化&#xff0c;能表达单词之间的相关性。 在是用独热码one_hot编码时&#xff0c;我们会发现单词的编码十分稀疏&#xff0c;以至于训练的效率不是很高。采用embeddi…

nn.Embedding使用

nn.Embedding是一种词嵌入的方式&#xff0c;跟one-hot相似但又不同&#xff0c;会生成低维稠密向量&#xff0c;但是初始是随机化的&#xff0c;需要根据模型训练时进行调节&#xff0c;若使用预训练词向量模型会比较好。 1. one-hot one-hot是给定每个单词一个索引&#xf…

深度学习中Embedding的解释

转载于https://zhuanlan.zhihu.com/p/164502624 什么是Embedding&#xff1f; 近年来&#xff0c;NLP自然语言处理、推荐系统&#xff0c;以及计算机视觉已成为目前工业界算法岗的主流方向&#xff0c;无论在哪个领域&#xff0c;对“Embedding”这个词概念的理解都是每个庞大知…

Embedding理解+代码

目录 Embedding主要思想 Word2vec主要思想两种模型&#xff1a;目的&#xff1a; 算法一、定义超参数二、将语料库转换one-hot编码表示三、模型训练 代码手动实现 skip-gram模型一、数据准备二、定义超参数三、定义word2vec模型数据清洗及生成词汇表训练模型 四、 获取词向量和…

Embedding 基础

一、什么是Embedding 简单来说&#xff0c;Embedding 就是用一个数值向量“表示”一个对象&#xff08;Object&#xff09;的方法&#xff0c;这里说的对象可以是一个词、一个物品&#xff0c;也可以是一部电影等等。一个物品能被向量表示&#xff0c;是因为这个向量跟其他物品…