RL_brain.py 8.3 KB

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