|
| 1 | +import numpy as np |
| 2 | +import pandas as pd |
| 3 | +import tensorflow.compat.v1 as tf |
| 4 | +tf.disable_v2_behavior() |
| 5 | + |
| 6 | +np.random.seed(1) |
| 7 | +tf.set_random_seed(1) |
| 8 | + |
| 9 | + |
| 10 | +# Deep Q Network off-policy |
| 11 | +class DeepQNetwork: |
| 12 | + def __init__( |
| 13 | + self, |
| 14 | + n_actions, |
| 15 | + n_features, |
| 16 | + learning_rate=0.01, |
| 17 | + reward_decay=0.9, |
| 18 | + e_greedy=0.9, |
| 19 | + replace_target_iter=300, |
| 20 | + memory_size=500, |
| 21 | + batch_size=32, |
| 22 | + e_greedy_increment=None, |
| 23 | + output_graph=True, |
| 24 | + ): |
| 25 | + self.n_actions = n_actions |
| 26 | + self.n_features = n_features |
| 27 | + self.lr = learning_rate |
| 28 | + self.gamma = reward_decay |
| 29 | + self.epsilon_max = e_greedy |
| 30 | + self.replace_target_iter = replace_target_iter |
| 31 | + self.memory_size = memory_size |
| 32 | + self.batch_size = batch_size |
| 33 | + self.epsilon_increment = e_greedy_increment |
| 34 | + self.epsilon = 0 if e_greedy_increment is not None else self.epsilon_max |
| 35 | + |
| 36 | + # total learning step |
| 37 | + self.learn_step_counter = 0 |
| 38 | + |
| 39 | + # initialize zero memory [s, a, r, s_] |
| 40 | + self.memory = np.zeros((self.memory_size, n_features * 2 + 2)) |
| 41 | + |
| 42 | + # consist of [target_net, evaluate_net] |
| 43 | + self._build_net() |
| 44 | + t_params = tf.get_collection('target_net_params') |
| 45 | + e_params = tf.get_collection('eval_net_params') |
| 46 | + self.replace_target_op = [tf.assign(t, e) for t, e in zip(t_params, e_params)] |
| 47 | + |
| 48 | + self.sess = tf.Session() |
| 49 | + |
| 50 | + if output_graph: |
| 51 | + # $ tensorboard --logdir=logs |
| 52 | + # tf.train.SummaryWriter soon be deprecated, use following |
| 53 | + tf.summary.FileWriter("logs/", self.sess.graph) |
| 54 | + |
| 55 | + self.sess.run(tf.global_variables_initializer()) |
| 56 | + self.cost_his = [] |
| 57 | + |
| 58 | + def _build_net(self): |
| 59 | + # ------------------ build evaluate_net ------------------ |
| 60 | + self.s = tf.placeholder(tf.float32, [None, self.n_features], name='s') # input |
| 61 | + self.q_target = tf.placeholder(tf.float32, [None, self.n_actions], name='Q_target') # for calculating loss |
| 62 | + with tf.variable_scope('eval_net'): |
| 63 | + # c_names(collections_names) are the collections to store variables |
| 64 | + c_names, n_l1, w_initializer, b_initializer = \ |
| 65 | + ['eval_net_params', tf.GraphKeys.GLOBAL_VARIABLES], 10, \ |
| 66 | + tf.random_normal_initializer(0., 0.3), tf.constant_initializer(0.1) # config of layers |
| 67 | + |
| 68 | + # first layer. collections is used later when assign to target net |
| 69 | + with tf.variable_scope('l1'): |
| 70 | + w1 = tf.get_variable('w1', [self.n_features, n_l1], initializer=w_initializer, collections=c_names) |
| 71 | + b1 = tf.get_variable('b1', [1, n_l1], initializer=b_initializer, collections=c_names) |
| 72 | + l1 = tf.nn.relu(tf.matmul(self.s, w1) + b1) |
| 73 | + |
| 74 | + # second layer. collections is used later when assign to target net |
| 75 | + with tf.variable_scope('l2'): |
| 76 | + w2 = tf.get_variable('w2', [n_l1, self.n_actions], initializer=w_initializer, collections=c_names) |
| 77 | + b2 = tf.get_variable('b2', [1, self.n_actions], initializer=b_initializer, collections=c_names) |
| 78 | + self.q_eval = tf.matmul(l1, w2) + b2 |
| 79 | + |
| 80 | + with tf.variable_scope('loss'): |
| 81 | + self.loss = tf.reduce_mean(tf.squared_difference(self.q_target, self.q_eval)) |
| 82 | + with tf.variable_scope('train'): |
| 83 | + self._train_op = tf.train.RMSPropOptimizer(self.lr).minimize(self.loss) |
| 84 | + |
| 85 | + # ------------------ build target_net ------------------ |
| 86 | + self.s_ = tf.placeholder(tf.float32, [None, self.n_features], name='s_') # input |
| 87 | + with tf.variable_scope('target_net'): |
| 88 | + # c_names(collections_names) are the collections to store variables |
| 89 | + c_names = ['target_net_params', tf.GraphKeys.GLOBAL_VARIABLES] |
| 90 | + |
| 91 | + # first layer. collections is used later when assign to target net |
| 92 | + with tf.variable_scope('l1'): |
| 93 | + w1 = tf.get_variable('w1', [self.n_features, n_l1], initializer=w_initializer, collections=c_names) |
| 94 | + b1 = tf.get_variable('b1', [1, n_l1], initializer=b_initializer, collections=c_names) |
| 95 | + l1 = tf.nn.relu(tf.matmul(self.s_, w1) + b1) |
| 96 | + |
| 97 | + # second layer. collections is used later when assign to target net |
| 98 | + with tf.variable_scope('l2'): |
| 99 | + w2 = tf.get_variable('w2', [n_l1, self.n_actions], initializer=w_initializer, collections=c_names) |
| 100 | + b2 = tf.get_variable('b2', [1, self.n_actions], initializer=b_initializer, collections=c_names) |
| 101 | + self.q_next = tf.matmul(l1, w2) + b2 |
| 102 | + |
| 103 | + def store_transition(self, s, a, r, s_): |
| 104 | + if not hasattr(self, 'memory_counter'): |
| 105 | + self.memory_counter = 0 |
| 106 | + |
| 107 | + transition = np.hstack((s, [a, r], s_)) |
| 108 | + |
| 109 | + # replace the old memory with new memory |
| 110 | + index = self.memory_counter % self.memory_size |
| 111 | + self.memory[index, :] = transition |
| 112 | + |
| 113 | + self.memory_counter += 1 |
| 114 | + |
| 115 | + def choose_action(self, observation): |
| 116 | + # to have batch dimension when feed into tf placeholder |
| 117 | + observation = observation[np.newaxis, :] |
| 118 | + |
| 119 | + if np.random.uniform() < self.epsilon: |
| 120 | + # forward feed the observation and get q value for every actions |
| 121 | + actions_value = self.sess.run(self.q_eval, feed_dict={self.s: observation}) |
| 122 | + action = np.argmax(actions_value) |
| 123 | + else: |
| 124 | + action = np.random.randint(0, self.n_actions) |
| 125 | + return action |
| 126 | + |
| 127 | + def learn(self): |
| 128 | + # check to replace target parameters |
| 129 | + if self.learn_step_counter % self.replace_target_iter == 0: |
| 130 | + self.sess.run(self.replace_target_op) |
| 131 | + print('\ntarget_params_replaced\n') |
| 132 | + |
| 133 | + # sample batch memory from all memory |
| 134 | + if self.memory_counter > self.memory_size: |
| 135 | + sample_index = np.random.choice(self.memory_size, size=self.batch_size) |
| 136 | + else: |
| 137 | + sample_index = np.random.choice(self.memory_counter, size=self.batch_size) |
| 138 | + batch_memory = self.memory[sample_index, :] |
| 139 | + |
| 140 | + q_next, q_eval = self.sess.run( |
| 141 | + [self.q_next, self.q_eval], |
| 142 | + feed_dict={ |
| 143 | + self.s_: batch_memory[:, -self.n_features:], # fixed params |
| 144 | + self.s: batch_memory[:, :self.n_features], # newest params |
| 145 | + }) |
| 146 | + |
| 147 | + # change q_target w.r.t q_eval's action |
| 148 | + q_target = q_eval.copy() |
| 149 | + |
| 150 | + batch_index = np.arange(self.batch_size, dtype=np.int32) |
| 151 | + eval_act_index = batch_memory[:, self.n_features].astype(int) |
| 152 | + reward = batch_memory[:, self.n_features + 1] |
| 153 | + |
| 154 | + q_target[batch_index, eval_act_index] = reward + self.gamma * np.max(q_next, axis=1) |
| 155 | + |
| 156 | + """ |
| 157 | + For example in this batch I have 2 samples and 3 actions: |
| 158 | + q_eval = |
| 159 | + [[1, 2, 3], |
| 160 | + [4, 5, 6]] |
| 161 | + q_target = q_eval = |
| 162 | + [[1, 2, 3], |
| 163 | + [4, 5, 6]] |
| 164 | + Then change q_target with the real q_target value w.r.t the q_eval's action. |
| 165 | + For example in: |
| 166 | + sample 0, I took action 0, and the max q_target value is -1; |
| 167 | + sample 1, I took action 2, and the max q_target value is -2: |
| 168 | + q_target = |
| 169 | + [[-1, 2, 3], |
| 170 | + [4, 5, -2]] |
| 171 | + So the (q_target - q_eval) becomes: |
| 172 | + [[(-1)-(1), 0, 0], |
| 173 | + [0, 0, (-2)-(6)]] |
| 174 | + We then backpropagate this error w.r.t the corresponding action to network, |
| 175 | + leave other action as error=0 cause we didn't choose it. |
| 176 | + """ |
| 177 | + |
| 178 | + # train eval network |
| 179 | + _, self.cost = self.sess.run([self._train_op, self.loss], |
| 180 | + feed_dict={self.s: batch_memory[:, :self.n_features], |
| 181 | + self.q_target: q_target}) |
| 182 | + self.cost_his.append(self.cost) |
| 183 | + |
| 184 | + # increasing epsilon |
| 185 | + self.epsilon = self.epsilon + self.epsilon_increment if self.epsilon < self.epsilon_max else self.epsilon_max |
| 186 | + self.learn_step_counter += 1 |
| 187 | + |
| 188 | + def plot_cost(self): |
| 189 | + import matplotlib.pyplot as plt |
| 190 | + plt.plot(np.arange(len(self.cost_his)), self.cost_his) |
| 191 | + plt.ylabel('Cost') |
| 192 | + plt.xlabel('training steps') |
| 193 | + plt.show() |
0 commit comments