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 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233
| class DeepQNetwork: def __init__( self, n_actions, n_features, learning_rate=0.1, reward_decay=0.001, e_greedy=0.99, replace_target_iter=200, memory_size=MEMORY_CAPACITY, batch_size=BATCH_SIZE, output_graph=False, ): ''' 初始化DQN网络
Parameters ---------- n_actions : TYPE 行为空间大小 n_features : TYPE 环境特征 learning_rate : TYPE, optional 学习率. The default is 0.1. reward_decay : TYPE, optional 奖励衰减因子. The default is 0.001. e_greedy : TYPE, optional e贪心因子. The default is 0.99. replace_target_iter : TYPE, optional 每多少次更新target参数. The default is 200. memory_size : TYPE, optional 记忆库大小. The default is MEMORY_CAPACITY. batch_size : TYPE, optional 批处理大小. The default is BATCH_SIZE. # e_greedy_increment : TYPE, optional e贪心因子增长幅度. The default is 8.684615e-05. output_graph : TYPE, optional 是否输出图表. The default is False.
Returns ------- None.
''' self.n_actions = n_actions self.n_features = n_features self.lr = learning_rate self.gamma = reward_decay self.epsilon_max = e_greedy self.replace_target_iter = replace_target_iter self.memory_size = memory_size self.batch_size = batch_size self.epsilon = 0.99
self.learn_step_counter = 0
self.memory = np.zeros((MEMORY_CAPACITY, s_dim * 2 + 2), dtype=np.float32)
self._build_net()
t_params = tf.get_collection(tf.GraphKeys.GLOBAL_VARIABLES, scope='target_net') e_params = tf.get_collection(tf.GraphKeys.GLOBAL_VARIABLES, scope='eval_net')
with tf.variable_scope('hard_replacement'): self.target_replace_op = [tf.assign(t, e) for t, e in zip(t_params, e_params)]
self.sess = tf.Session()
if output_graph: tf.summary.FileWriter("logs/", self.sess.graph) self.sess.run(tf.global_variables_initializer()) self.cost_his = []
def _build_net(self): ''' 构建所有的网络图
Returns ------- None.
''' self.s = tf.placeholder(tf.float32, [None, self.n_features], name='s') self.s_ = tf.placeholder(tf.float32, [None, self.n_features], name='s_') self.r = tf.placeholder(tf.float32, [None, ], name='r') self.a = tf.placeholder(tf.int32, [None, ], name='a') w_initializer, b_initializer = tf.random_normal_initializer(0., 0.3), tf.constant_initializer(0.1) with tf.variable_scope('eval_net'): e1 = tf.layers.dense(self.s, 100, tf.nn.relu6, kernel_initializer=w_initializer, bias_initializer=b_initializer, name='e1') e3 = tf.layers.dense(e1, 20, tf.nn.relu, kernel_initializer=w_initializer, bias_initializer=b_initializer, name='e3') self.q_eval = tf.layers.dense(e3, self.n_actions, tf.nn.softmax, kernel_initializer=w_initializer, bias_initializer=b_initializer, name='q')
with tf.variable_scope('target_net'): t1 = tf.layers.dense(self.s_, 100, tf.nn.relu6, kernel_initializer=w_initializer, bias_initializer=b_initializer, name='t1') t3 = tf.layers.dense(t1, 20, tf.nn.relu, kernel_initializer=w_initializer, bias_initializer=b_initializer, name='t3') self.q_next = tf.layers.dense(t3, self.n_actions, tf.nn.softmax, kernel_initializer=w_initializer, bias_initializer=b_initializer, name='t4')
with tf.variable_scope('q_target'): q_target = self.r + self.gamma * tf.reduce_max(self.q_next, axis=1, name='Qmax_s_') self.q_target = tf.stop_gradient(q_target) with tf.variable_scope('q_eval'): a_indices = tf.stack([tf.range(tf.shape(self.a)[0], dtype=tf.int32), self.a], axis=1) self.q_eval_wrt_a = tf.gather_nd(params=self.q_eval, indices=a_indices) with tf.variable_scope('loss'): self.loss = tf.reduce_mean(tf.squared_difference(self.q_target, self.q_eval_wrt_a, name='TD_error')) with tf.variable_scope('train'): self._train_op = tf.train.AdamOptimizer(self.lr).minimize(self.loss)
def store_transition(self, s, a, r, s_): ''' 存储记忆元组
Parameters ---------- s : 当前状态 a : 动作 r : 奖惩 s_ : 下一状态
Returns ------- None.
''' if not hasattr(self, 'memory_counter'): self.memory_counter = 0 transition = np.hstack((s, a, [r], s_)) index = self.memory_counter % self.memory_size self.memory[index, :] = transition self.memory_counter += 1
def choose_action(self, observation): ''' 根据当前状态选择动作
Parameters ---------- observation : 对环境的观测
Returns ------- action : 做出的动作
''' observation = observation[np.newaxis, :] if np.random.uniform() < self.epsilon: actions_value = self.sess.run(self.q_eval, feed_dict={self.s: observation}) action = np.argmax(actions_value) else: action = np.random.randint(0, self.n_actions) return action
def learn(self): ''' 神经网络训练
Returns ------- None.
''' if self.learn_step_counter % self.replace_target_iter == 0: self.sess.run(self.target_replace_op) print('\ntarget_params_replaced\n')
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, :]
_, cost = self.sess.run( [self._train_op, self.loss], feed_dict={ self.s: batch_memory[:, :self.n_features], self.a: batch_memory[:, self.n_features], self.r: batch_memory[:, self.n_features + 1], self.s_: batch_memory[:, -self.n_features:], })
self.cost_his.append(cost)
self.learn_step_counter += 1
|