当前位置:   article > 正文

DQN算法&流程图&代码实现(Tensorflow2.x / Keras)_dqn算法流程图

dqn算法流程图

一、DQN详解

1) Qlearning --> DQN

  • 对于离散状态空间,若智能体所处的状态成千上万,用Qlearning表格法存储状态很不实际,对于连续状态空间同理。
  • 为了在连续状态空间下应用类似Qlearning的学习方式,需要对值函数进行逼近,故出现了DQN算法。

2) DQN实现流程

在里插入图片描述s : 当前状态
a : 当前s下,智能体根据策略(eval_model)给出决策a
r, s_ : 当前s下,做出行为a,环境给出奖励r,并跳转状态至s_

具体步骤
1)初始化状态s;
2)初始化eval_model 和 target_model,其中eval_model为决策网络,后续算法主动更新的是eval_model;target_model为目标网络,主要生成TD_error,作为更新算法中的一部分,eval_model和eval_model:结构相同、参数相同;
3)初始化记忆容器memory
4) s --> eval_model --> a ,遵循epsilon-greedy
5) 环境根据动作a反馈奖励r和下一个状态s_
6) 将(s,a,r,s_)存储在记忆容器memory中,新经历覆盖旧记忆
7)memory中经历足够多时进行算法更新,主动更新eval_model的参数:
每隔若干步就进行一次eval_model参数更新,从经历库中随机提取batch进行训练更新,更新依据梯度grad,其中:
grad = r + y * max q_target矩阵(batch* nums_action)- max q_eval(batch * nums_action)
⚠️矩阵相减的时候,需要保证q_target矩阵的最大值和q_eval矩阵的最大值在同一个位置。

8)每隔若干步,将eval_model的参数assign至 target_model

3) 实例(基于Tensorflow2.x / Keras):

基于Keras实现机器玩迷宫游戏。
其中网络建立部分:

from keras import layers, Model, Input
from keras.optimizers import RMSprop
import numpy as np
import matplotlib.pyplot as plt


class DQN:
    def __init__(self, n_features, n_actions):
        self.n_features = n_features
        self.n_actions = n_actions
        # 算法超参数设置
        self.lr = 0.01
        self.gamma = 0.9
        self.replace_target_iter = 300
        self.memory_size = 5000
        self.batch_size = 60
        self.epsilon_max = 0.99
        self.epsilon_increment = 0.05  # 不断减小随机选择的概率
        self.epsilon = 0 if self.epsilon_increment is not None else self.epsilon_max

        self.learn_step_counter = 0
        # 记忆[s,a,r,s_]:根据提议s长度为2,a长度为1,r长度为1,故总长度为2*2+1+1
        self.memory = np.zeros((self.memory_size, n_features*2+2))

        # 初始化两个网络模型
        self.model_eval = self.create_eval(n_actions, n_features)
        self.model_target = self.create_target(n_actions, n_features)
        self.model_eval.compile(optimizer=RMSprop(lr=self.lr), loss='mse')
        # 记录mse(TD_error)
        self.cost_his = []

    def create_eval(self, n_actions, n_features):
        input_tensor = Input(shape=(n_features,))
        x = layers.Dense(32, activation='relu')(input_tensor)
        x = layers.Dense(32, activation='relu')(x)
        output_tensor = layers.Dense(n_actions)(x)
        model = Model(input_tensor, output_tensor)
        model.summary()
        return model

    def create_target(self, n_actions, n_features):
        input_tensor = Input(shape=(n_features,))
        x = layers.Dense(32, activation='relu', trainable=False)(input_tensor)
        x = layers.Dense(32, activation='relu', trainable=False)(x)
        output_tensor = layers.Dense(n_actions)(x)
        model = Model(input_tensor, output_tensor)
        model.summary()
        return model

    def store_transition(self, s, a, r, s_):
        # 存储第一条初始化
        if not hasattr(self, 'memory_counter'):
            self.memory_counter = 0

        transition = np.hstack((s, [a, r], s_))  # 水平叠加,例如:np.hstack(([1,2],[3,4],[5,6])) => array(1 2 3 4 5 6)
        index = self.memory_counter % self.memory_size  # 后续经历覆盖老经历
        self.memory[index, :] = transition
        self.memory_counter += 1

    def choose_action(self, observation):
        observation = observation[np.newaxis, :]
        if np.random.uniform() < self.epsilon:
            action_value = self.model_eval.predict(observation)
            action = np.argmax(action_value)  # 0,1,2,3表示动作
        else:
            action = np.random.randint(0, self.n_actions)
        return action

    def _replace_target_params(self):
        for eval_layer, target_layer in zip(self.model_eval.layers, self.model_target.layers):
            target_layer.set_weights(eval_layer.get_weights())

    def learn(self):
        if self.memory_counter > self.memory_size:
            sample_index = np.random.choice(self.memory_size, size=self.batch_size)
        else:
            sample_index = np.random.choice(self.memory_counter, size=self.batch_size)

        batch_memory = self.memory[sample_index, :]  # shuffle
        q_next = self.model_target.predict(batch_memory[:, -self.n_features:])
        q_eval = self.model_eval.predict(batch_memory[:, :self.n_features])

        q_target = q_eval.copy()  # array不需要deepcopy

        batch_index = np.arange(self.batch_size, dtype=np.int32)
        eval_act_index = batch_memory[:, self.n_features].astype(int)
        reward = batch_memory[:, self.n_features + 1]
        # 为了方便矩阵相减,q_target - q_eval, 它们的最大q值要放在同一个矩阵位置
        q_target[batch_index, eval_act_index] = reward + self.gamma * np.max(q_next, axis=1)

        if self.learn_step_counter % self.replace_target_iter == 0:
            # 每隔若干步学习一次
            self._replace_target_params()

        cost = self.model_eval.train_on_batch(batch_memory[:, :self.n_features], q_target)
        self.cost_his.append(cost)

        self.epsilon = self.epsilon + self.epsilon_increment if self.epsilon < self.epsilon_max else self.epsilon_max
        self.learn_step_counter += 1

    def plot_cost(self):
        plt.plot(np.arange(len(self.cost_his)), self.cost_his)
        plt.ylabel('mse')
        plt.xlabel('training steps')
        plt.show()


  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66
  • 67
  • 68
  • 69
  • 70
  • 71
  • 72
  • 73
  • 74
  • 75
  • 76
  • 77
  • 78
  • 79
  • 80
  • 81
  • 82
  • 83
  • 84
  • 85
  • 86
  • 87
  • 88
  • 89
  • 90
  • 91
  • 92
  • 93
  • 94
  • 95
  • 96
  • 97
  • 98
  • 99
  • 100
  • 101
  • 102
  • 103
  • 104
  • 105
  • 106
  • 107

代码风格主要参考莫凡,完整代码详见github

https://github.com/huafeng97/DQN.git

二、 DQN变种:Double_DQN和Duel_DQN

DDQN:我们知道,DQN在基于target_model进行状态评估的过程中,首先要基于eval_model先选择最大Q(s_)对应的action,然后把这个action对应的最大Q(s_)值赋给eval_model要优化的action位置上,显然前后涉及的两个Q(s_)是相等的。这使得传统DQN在值函数估计上与真实值偏差较大。

DDQN稍作改变,将状态评估过程中,先根据ANN1选择最大Q(s_)对应的action,然后再根据选定的action的位置索引到target_model的Q(s_,a)对上,从而选出Q值(实际这个Q值在target_model这边可能并不是最大值)。这种操作,可以获得更准确地估计Q值。

Duel_DQN:将值函数分解成价值和优势,值函数在不同状况下对价值和优势的敏感程度不同,例如自动驾驶,在无其他汽车的路面上,价值对值函数的影响较大;若汽车靠近其他车辆,则优势对值函数的影响较大。它不像DoubleDQN改变的是算法,它改变的是网络结构,将原来的单Q输出,变成了双输出(价值和优势)

三、 为什么不打破数据相关性,DQN神经网络的训练效果就不好

智能体对值函数很敏感,直接影响智能体的决策,而一个连续相关的数据集会使得智能体一直朝着该数据集建议的方向(R值较大)进行探索,若此时另一个数据集出现,智能体又不得不向着另一个方向探索。于是,数据间前后的相互依赖性会对智能体学习、更新策略造成严重的波动,最后很难学到真正的最优策略,也就是难以收敛。还有一个问题就是连续数据段变化带来的可能的值函数突变,将导致神经网络反向传播时梯度爆炸,导致神经网络无法收敛,所以才要用经历回放并随机采样,从一开始反向传播的过程中,就解决梯度瞬间增大的问题。

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/盐析白兔/article/detail/295865
推荐阅读
相关标签
  

闽ICP备14008679号