强化学习(DQN)

目录

  • 1、 DQN两大创新点
  • 2、流程图
  • 3、函数介绍
  • 4、代码实现
  • 5、报错纠正

1、 DQN两大创新点

① 经验回放:样本关联性:1.序列决策的样本关联2.样本利用率低

②固定Q目标:非平稳性:1.算法非平稳2.样本利用率低

2、流程图

强化学习(DQN)_第1张图片

3、函数介绍

①model:定义有神经网络部分的网络结构

②algorithm:定义具体算法来更新Q网络

  • predict():self_model来predict输出动作
  • learn():更新Q值
  • sync_target():实现model参数同步到target_model里面

③agent:与环境交互,在交互过程中,把生成的数据据提供给algorithm去更新网络model

  • sample():采样保证所有的动作能够被探索到
  • learn():根据从环境中拿到的数据去更新Q表格
  • build_program():构建静态图、计算图

4、代码实现

import parl
from parl import layers
import paddle.fluid as fluid
import copy
import numpy as np
import os
import gym
from parl.utils import logger
import paddle
paddle.enable_static()

LEARN_FREQ = 5 # 运行多少步以后学习一次
MEMORY_SIZE = 20000    # Memory 的大小
MEMORY_WARMUP_SIZE = 200  # Warmup 的大小
BATCH_SIZE = 32   # Batch 的大小
LEARNING_RATE = 0.001 # 学习率 alpha
GAMMA = 0.99 # reward 的 discount factor 衰减因子,一般取 0.9 到 0.999 不等

# Model 是一个神经网络模型,输入State输出对于所有 action 估计的Q Values(我们会使用2个神经网络模型,一个是 Current Q Network 一个是 Target Q Network)
# Algorithm 提供Loss Function和Optimization Algorithm,接收Agent的信息,用来优化神经网络
# Agent 直接跟环境来交互
class Model(parl.Model): # 这个 Model 是一个三层的 Multi-Layer Perceptron
    def __init__(self, act_dim): # 在 Model 初始化的时候 传进来 action 的数量,这决定了最后一个 FC 输出的维度
        hid1_size = 128
        hid2_size = 128
        self.fc1 = layers.fc(size=hid1_size, act='relu') # 第一个 FC,输出经过一个 ReLU
        self.fc2 = layers.fc(size=hid2_size, act='relu')
        self.fc3 = layers.fc(size=act_dim, act=None) # 最后一个 FC,输出不经过 Activation Function

    def value(self, obs):
        # 定义网络
        # 输入state,输出所有action对应的Q,[Q(s,a1), Q(s,a2), Q(s,a3)...]
        h1 = self.fc1(obs) # 这里把三层网络进行嵌套
        h2 = self.fc2(h1)
        Q = self.fc3(h2)
        return Q


# from parl.algorithms import DQN # 也可以直接从parl库中导入DQN算法

class DQN(parl.Algorithm):
    def __init__(self, model, act_dim=None, gamma=None, lr=None):
        """ DQN algorithm

        Args:
            model (parl.Model): 定义Q函数的前向网络结构
            act_dim (int): action空间的维度,即有几个action
            gamma (float): reward的衰减因子
            lr (float): learning rate 学习率.
        """
        self.model = model  # 我们用来获取 current Q 的模型
        self.target_model = copy.deepcopy(model)  # 创建一个target Q模型,创建的策略是直接从model复制给target

        assert isinstance(act_dim, int)
        assert isinstance(gamma, float)
        assert isinstance(lr, float)
        self.act_dim = act_dim  # 把这些参数变成class properties
        self.gamma = gamma
        self.lr = lr

    def predict(self, obs):  # 使用 current Q network 获取所有action的 Q values
        """ 使用self.model的value网络来获取 [Q(s,a1),Q(s,a2),...]
        """
        return self.model.value(obs)

    def learn(self, obs, action, reward, next_obs, terminal):
        """ 使用DQN算法更新self.model的value网络
        """
        # 从target_model中获取 max Q' 的值,用于计算target_Q
        next_pred_value = self.target_model.value(next_obs)  # 获取 target Q network 的所有action的 Q values
        best_v = layers.reduce_max(next_pred_value, dim=1)  # 获取最大的Q值
        best_v.stop_gradient = True  # 阻止梯度传递
        terminal = layers.cast(terminal, dtype='float32')  # 把terminal (是否终止)换为一个float32类型的数组,如果终止里面存储1,如果不终止里面存储0
        target = reward + (1.0 - terminal) * self.gamma * best_v  # 这里如果终止, 1-terminal 对应的元素为0,就不需要取best_v,不然还是要取best_v

        pred_value = self.model.value(obs)  # 获取Q预测 获取 current Q network 的所有action的 Q values

        # 接着我们需要获取action对应的Q,这里使用了一个one-hot encoding来做乘法运算,相当于选中了Q values中action对应的那个值

        # 将action转one-hot向量,比如:3 => [0,0,0,1,0]
        action_onehot = layers.one_hot(action, self.act_dim)
        action_onehot = layers.cast(action_onehot, dtype='float32')
        # 下面一行是逐元素相乘,拿到action对应的 Q(s,a)
        # 比如:pred_value = [[2.3, 5.7, 1.2, 3.9, 1.4]], action_onehot = [[0,0,0,1,0]]
        #  ==> pred_action_value = [[3.9]]
        pred_action_value = layers.reduce_sum(
            layers.elementwise_mul(action_onehot, pred_value), dim=1)

        # 计算 Q(s,a) 与 target_Q的MSE均方差,得到loss
        cost = layers.square_error_cost(pred_action_value, target)
        cost = layers.reduce_mean(cost)  # Loss 对于每一个样本都是一个数字,为了优化我们求平均数
        optimizer = fluid.optimizer.Adam(learning_rate=self.lr)  # 使用Adam优化器,Adam是一种优化算法
        optimizer.minimize(cost)
        return cost

    def sync_target(self):
        """ 把 self.model 的模型参数值同步到 self.target_model
        """
        self.model.sync_weights_to(
            self.target_model)  # 这个函数主要是为了更新 Target Q,因为每一段时间我们就需要使用 Current Q Network 更新一次Target Q Network

class Agent(parl.Agent):
    def __init__(self,
                 algorithm,
                 obs_dim,
                 act_dim,
                 e_greed=0.1,
                 e_greed_decrement=0):
        assert isinstance(obs_dim, int)
        assert isinstance(act_dim, int)
        self.obs_dim = obs_dim
        self.act_dim = act_dim
        super(Agent, self).__init__(algorithm)

        self.global_step = 0
        self.update_target_steps = 200  # 每隔200个training steps再把model的参数复制到target_model中

        self.e_greed = e_greed  # 有一定概率随机选取动作,探索
        self.e_greed_decrement = e_greed_decrement  # 随着训练逐步收敛,探索的程度慢慢降低

    def build_program(self):
        self.pred_program = fluid.Program()
        self.learn_program = fluid.Program()

        with fluid.program_guard(self.pred_program):  # 搭建计算图用于 预测动作,定义输入输出变量
            obs = layers.data(
                name='obs', shape=[self.obs_dim], dtype='float32')
            self.value = self.alg.predict(obs)

        with fluid.program_guard(self.learn_program):  # 搭建计算图用于 更新Q网络,定义输入输出变量
            obs = layers.data(
                name='obs', shape=[self.obs_dim], dtype='float32')
            action = layers.data(name='act', shape=[1], dtype='int32')
            reward = layers.data(name='reward', shape=[], dtype='float32')
            next_obs = layers.data(
                name='next_obs', shape=[self.obs_dim], dtype='float32')
            terminal = layers.data(name='terminal', shape=[], dtype='bool')
            self.cost = self.alg.learn(obs, action, reward, next_obs, terminal)


    def sample(self, obs): # epsilon-greedy exploration
        sample = np.random.rand()  # 产生0~1之间的小数
        if sample < self.e_greed:
            act = np.random.randint(self.act_dim)  # 探索:每个动作都有概率被选择
        else:
            act = self.predict(obs)  # 选择最优动作
        self.e_greed = max(
            0.01, self.e_greed - self.e_greed_decrement)  # 随着训练逐步收敛,探索的程度慢慢降低,这里最低还是要保持0.01的epsilon来探索
        return act

    def predict(self, obs):  # 选择最优动作
        obs = np.expand_dims(obs, axis=0)
        pred_Q = self.fluid_executor.run(
            self.pred_program,
            feed={'obs': obs.astype('float32')},
            fetch_list=[self.value])[0]
        pred_Q = np.squeeze(pred_Q, axis=0)
        act = np.argmax(pred_Q)  # 选择Q最大的下标,即对应的动作
        return act

    def learn(self, obs, act, reward, next_obs, terminal):
        # 每隔200个training steps同步一次model和target_model的参数
        if self.global_step % self.update_target_steps == 0:
            self.alg.sync_target()
        self.global_step += 1

        act = np.expand_dims(act, -1)
        feed = {
            'obs': obs.astype('float32'),
            'act': act.astype('int32'),
            'reward': reward,
            'next_obs': next_obs.astype('float32'),
            'terminal': terminal
        }
        cost = self.fluid_executor.run(
            self.learn_program, feed=feed, fetch_list=[self.cost])[0]  #feed传入数据,输出self.cost在build_program里 训练一次网络
        return cost

#下面是Experience Replay使用的Memory,这也是一个class。
import random
import collections
import numpy as np


class ReplayMemory(object):
    def __init__(self, max_size):
        self.buffer = collections.deque(maxlen=max_size) # deque 是两头可进入取出的 queue, maxlen 指的是memory最大有多大

    # 增加一条经验到经验池中
    def append(self, exp):
        self.buffer.append(exp) # 增加一个 experience, experience的结构是 (obs, action, reward, next_obs, done)

    # 从经验池中选取N条经验出来
    def sample(self, batch_size):
        mini_batch = random.sample(self.buffer, batch_size) # 从buffer里面选取mini-batch
        obs_batch, action_batch, reward_batch, next_obs_batch, done_batch = [], [], [], [], []

        for experience in mini_batch: # 把每一个Experience里的每一个部分变成一个list,下面会转成numpy数组
            s, a, r, s_p, done = experience
            obs_batch.append(s)
            action_batch.append(a)
            reward_batch.append(r)
            next_obs_batch.append(s_p)
            done_batch.append(done)

        return np.array(obs_batch).astype('float32'), \
            np.array(action_batch).astype('float32'), np.array(reward_batch).astype('float32'),\
            np.array(next_obs_batch).astype('float32'), np.array(done_batch).astype('float32')

    def __len__(self):
        return len(self.buffer) # 返回经验数量

#Training 和 Testing 函数
# 训练一个episode
def run_episode(env, agent, rpm):
    total_reward = 0
    obs = env.reset()
    step = 0
    while True:
        step += 1
        action = agent.sample(obs)  # 采样动作,因为使用了epsilon-greedy exploration, 所有动作都有概率被尝试到
        next_obs, reward, done, _ = env.step(action)
        rpm.append((obs, action, reward, next_obs, done))

        # train model
        if (len(rpm) > MEMORY_WARMUP_SIZE) and (step % LEARN_FREQ == 0):
            # 这里确定memory中有MEMORY_WARMUP_SIZE个Experience,如果没有就持续累积,有了才开始训练,这样让训练比较稳定。
            # 这里还确保了不是每次得到Experience都训练,有LEARN_FREQ的间隔。
            (batch_obs, batch_action, batch_reward, batch_next_obs,
             batch_done) = rpm.sample(BATCH_SIZE) # 从replay memory中sample出BATCH_SIZE个Experience,并且分类放在每一个变量中
            train_loss = agent.learn(batch_obs, batch_action, batch_reward,
                                     batch_next_obs,
                                     batch_done)  # s,a,r,s',done

        total_reward += reward
        obs = next_obs
        if done:
            break
    return total_reward


# 评估 agent, 跑 5 个episode,总reward求平均,因为环境有随机性,这样可以比较稳定
def evaluate(env, agent, render=False):
    eval_reward = []
    for i in range(5):
        obs = env.reset()
        episode_reward = 0
        while True:
            action = agent.predict(obs)  # 预测动作,只选最优动作,这里没有随机性了
            obs, reward, done, _ = env.step(action)
            episode_reward += reward
            if render:
                env.render()
            if done:
                break
        eval_reward.append(episode_reward)
    return np.mean(eval_reward)

#运行代码
env = gym.make('CartPole-v0')  # CartPole-v0: 预期最后一次评估总分 > 180(最大值是200)
action_dim = env.action_space.n  # CartPole-v0: 2
obs_shape = env.observation_space.shape  # CartPole-v0: (4,)

rpm = ReplayMemory(MEMORY_SIZE)  # DQN的经验回放池

# 根据parl框架构建agent
model = Model(act_dim=action_dim)
algorithm = DQN(model, act_dim=action_dim, gamma=GAMMA, lr=LEARNING_RATE)
agent = Agent(
    algorithm,
    obs_dim=obs_shape[0],
    act_dim=action_dim,
    e_greed=0.1,  # 有一定概率随机选取动作,探索
    e_greed_decrement=1e-6)  # 随着训练逐步收敛,探索的程度慢慢降低

# 加载模型
# save_path = './dqn_model.ckpt'
# agent.restore(save_path)

# 先往经验池里存一些数据,避免最开始训练的时候样本丰富度不够
while len(rpm) < MEMORY_WARMUP_SIZE:
    run_episode(env, agent, rpm)

max_episode = 2000

# 开始训练
episode = 0
while episode < max_episode:  # 训练max_episode个回合,test部分不计算入episode数量
    # train part
    for i in range(0, 50):
        total_reward = run_episode(env, agent, rpm)
        episode += 1

    # test part
    eval_reward = evaluate(env, agent, render=False)  # render=True 查看显示效果
    logger.info('episode:{}    e_greed:{}   test_reward:{}'.format(
        episode, agent.e_greed, eval_reward))

# 训练结束,保存模型
save_path = './dqn_model.ckpt'
agent.save(save_path)

5、报错纠正

TypeError: Descriptors cannot not be created directly. If this call came from a _pb2.py file, your generated code is out of date and must be regenerated with protoc >= 3.19.0.
If you cannot immediately regenerate your protos, some other possible workarounds are:
 1. Downgrade the protobuf package to 3.20.x or lower.
 2. Set PROTOCOL_BUFFERS_PYTHON_IMPLEMENTATION=python (but this will use pure-Python parsing and will be much slower).

按照提示重装protobuf,例如:

pip install protobuf==3.20.1

也可以用镜像加快下载速度

pip install -i https://pypi.tuna.tsinghua.edu.cn/simple protobuf==3.20.0

AssertionError: In PaddlePaddle 2.x, we turn on dynamic graph mode by default, and 'data()' is only supported in static graph mode. So if you want to use this api, please call 'paddle.enable_static()' before this api to enter static graph mode.

解决办法:

import paddle
paddle.enable_static()

你可能感兴趣的:(强化学习,深度学习,机器学习,python)