import numpy as np
from keras.layers import Dense, Input
from keras.models import Model
import keras
from keras.optimizers import RMSprop ,adam
from keras import backend as K
np.random.seed(1)
class DQN:
# 初始值
def __init__(
self,
n_actions,
n_features,
learning_rate=0.01,
reward_decay=0.9,
e_greedy=0.9,
replace_target_iter=300,
memory_size=500,
batch_size=32,
e_greedy_increment=None,
output_graph=False,
):
self.n_actions = n_actions
self.n_features = n_features
self.lr = learning_rate
self.gamma = reward_decay
self.epsilon_max = e_greedy # epsilon 的最大值
self.replace_target_iter = replace_target_iter # 更换 target_net 的步数
self.memory_size = memory_size # 记忆上限
self.batch_size = batch_size # 每次更新时从 memory 里面取多少记忆出来
self.epsilon_increment = e_greedy_increment # epsilon 的增量
self.epsilon = 0 if e_greedy_increment is not None else self.epsilon_max # 是否开启探索模式, 并逐步减少探索次数
# 记录学习次数 (用于判断是否更换 target_net 参数)
self.learn_step_counter = 0
# 初始化全 0 记忆 [s, a, r, s_]
self.memory = np.zeros((self.memory_size, n_features * 2 + 2))
# 创建 [target_net, evaluate_net]
self._build_net()
self.cost_his = [] # 记录所有 cost 变化, 用于最后 plot 出来观看
def target_replace_op(self):
v1 = self.model2.get_weights()
self.model1.set_weights(v1)
print("params has changed")
def _build_net(self):
# 构建evaluation网络
eval_inputs = Input(shape=(self.n_features,))
x = Dense(64, activation='relu')(eval_inputs)
x = Dense(64, activation='relu')(x)
self.q_eval = Dense(self.n_actions)(x)
# 构建target网络,注意这个target层输出是q_next而不是,算法中的q_target
target_inputs = Input(shape=(self.n_features,))
x = Dense(64, activation='relu')(target_inputs)
x = Dense(64, activation='relu')(x)
self.q_next = Dense(self.n_actions)(x)
self.model1 = Model(target_inputs, self.q_next)
self.model2 = Model(eval_inputs, self.q_eval)
rmsprop = RMSprop(lr=self.lr)
self.model1.compile(loss='mean_squared_error', optimizer=rmsprop, metrics=['accuracy'])
self.model2.compile(loss='mean_squared_error', optimizer=rmsprop, metrics=['accuracy'])
def store_transition(self, s, a, r, s_):
if not hasattr(self, 'memory_counter'):
self.memory_counter = 0
# 记录一条 [s, a, r, s_] 记录
transition = np.hstack((s, [a, r], s_))
# 总 memory 大小是固定的, 如果超出总大小, 旧 memory 就被新 memory 替换
index = self.memory_counter % self.memory_size
self.memory[index, :] = transition # memory是一个二维列表
self.memory_counter += 1
def choose_action(self, observation):
# 统一 observation 的 shape (1, size_of_observation)
observation = np.array(observation)
observation = observation[np.newaxis, :]
if np.random.uniform() < self.epsilon:
# 让 eval_net 神经网络生成所有 action 的值, 并选择值最大的 action
actions_value = self.model1.predict(observation)
action = np.argmax(actions_value)
else:
action = np.random.randint(0, self.n_actions) # 随机选择
return action
def learn(self):
# 检查是否替换 target_net 参数
if self.learn_step_counter % self.replace_target_iter == 0:
self.target_replace_op()
print('\ntarget_params_replaced\n')
# 从 memory 中随机抽取 batch_size 这么多记忆
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, :]
# 获取 q_next (target_net 产生了 q) 和 q_eval(eval_net 产生的 q)
q_next, q_eval = self.model1.predict(batch_memory[:, -self.n_features:]), self.model2.predict(
batch_memory[:, :self.n_features])
# 下面这几步十分重要. q_next, q_eval 包含所有 action 的值,
# 而我们需要的只是已经选择好的 action 的值, 其他的并不需要.
# 所以我们将其他的 action 值全变成 0, 将用到的 action 误差值 反向传递回去, 作为更新凭据.
# 这是我们最终要达到的样子, 比如 q_target - q_eval = [1, 0, 0] - [-1, 0, 0] = [2, 0, 0]
# q_eval = [-1, 0, 0] 表示这一个记忆中有我选用过 action 0, 而 action 0 带来的 Q(s, a0) = -1, 所以其他的 Q(s, a1) = Q(s, a2) = 0.
# q_target = [1, 0, 0] 表示这个记忆中的 r+gamma*maxQ(s_) = 1, 而且不管在 s_ 上我们取了哪个 action,
# 我们都需要对应上 q_eval 中的 action 位置, 所以就将 1 放在了 action 0 的位置.
# 下面也是为了达到上面说的目的, 不过为了更方面让程序运算, 达到目的的过程有点不同.
# 是将 q_eval 全部赋值给 q_target, 这时 q_target-q_eval 全为 0,
# 不过 我们再根据 batch_memory 当中的 action 这个 column 来给 q_target 中的对应的 memory-action 位置来修改赋值.
# 使新的赋值为 reward + gamma * maxQ(s_), 这样 q_target-q_eval 就可以变成我们所需的样子.
# 具体在下面还有一个举例说明.
q_target = q_eval.copy()
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[batch_index, eval_act_index] = reward + self.gamma * np.max(q_next, axis=1)
"""
假如在这个 batch 中, 我们有2个提取的记忆, 根据每个记忆可以生产3个 action 的值:
q_eval =
[[1, 2, 3],
[4, 5, 6]]
q_target = q_eval =
[[1, 2, 3],
[4, 5, 6]]
然后根据 memory 当中的具体 action 位置来修改 q_target 对应 action 上的值:
比如在:
记忆 0 的 q_target 计算值是 -1, 而且我用了 action 0;
记忆 1 的 q_target 计算值是 -2, 而且我用了 action 2:
q_target =
[[-1, 2, 3],
[4, 5, -2]]
所以 (q_target - q_eval) 就变成了:
[[(-1)-(1), 0, 0],
[0, 0, (-2)-(6)]]
最后我们将这个 (q_target - q_eval) 当成误差, 反向传递会神经网络.
所有为 0 的 action 值是当时没有选择的 action, 之前有选择的 action 才有不为0的值.
我们只反向传递之前选择的 action 的值,
"""
# # 训练 eval_net
# _, self.cost = self.sess.run([self._train_op, self.loss],
# feed_dict={self.s: batch_memory[:, :self.n_features],
# self.q_target: q_target})
# self.cost_his.append(self.cost) # 记录 cost 误差
self.model2.fit(batch_memory[:, :self.n_features], q_target, epochs=10)
self.epsilon = self.epsilon + self.epsilon_increment if self.epsilon < self.epsilon_max else self.epsilon_max
self.learn_step_counter += 1
self.cost_his.append(eval_act_index) # 记录 cost 误差
def plot_cost(self):
import matplotlib.pyplot as plt
plt.plot(n