DQN.py 7.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169
  1. import numpy as np
  2. import pandas as pd
  3. import tensorflow as tf
  4. np.random.seed(1)
  5. tf.set_random_seed(1)
  6. class DQN():
  7. def __init__(self,
  8. n_actions,
  9. n_features,
  10. learning_rate=0.001,
  11. reward_decay=0.9,
  12. e_greedy=0.9,
  13. replace_target_iter=300,
  14. memory_size=800,
  15. batch_size=64,
  16. e_greedy_increment=None,
  17. output_graph=False
  18. ):
  19. self.n_actions = n_actions
  20. self.n_features = n_features
  21. self.lr = learning_rate
  22. self.gamma = reward_decay
  23. self.epsilon_max = e_greedy
  24. self.replace_target_iter = replace_target_iter
  25. self.memory_size = memory_size
  26. self.batch_size = batch_size
  27. self.epsilon_increment = e_greedy_increment
  28. self.epsilon = 0 if e_greedy_increment is not None else self.epsilon_max
  29. # total learning step
  30. self.learn_step_counter = 0
  31. # initialize zero memory [s, a, r, s_]
  32. self.memory = np.zeros((self.memory_size, n_features * 2 + 2))
  33. # consist of [target_net, evaluate_net]
  34. self._build_net()
  35. t_params = tf.get_collection('target_net_params')
  36. e_params = tf.get_collection('eval_net_params')
  37. self.replace_target_op = [tf.assign(t, e) for t, e in zip(t_params, e_params)]
  38. self.sess = tf.Session()
  39. if output_graph:
  40. # $ tensorboard --logdir=logs
  41. # tf.train.SummaryWriter soon be deprecated, use following
  42. tf.summary.FileWriter("logs/", self.sess.graph)
  43. self.sess.run(tf.global_variables_initializer())
  44. self.cost_his = []
  45. def _build_net(self):
  46. # ------------------ build evaluate_net ------------------
  47. self.s = tf.placeholder(tf.float32, [None, self.n_features], name='s') # input
  48. self.q_target = tf.placeholder(tf.float32, [None, self.n_actions], name='Q_target') # for calculating loss
  49. # print(self.s)
  50. with tf.variable_scope('eval_net'):
  51. # c_names(collections_names) are the collections to store variables
  52. c_names, n_l1, w_initializer, b_initializer = \
  53. ['eval_net_params', tf.GraphKeys.GLOBAL_VARIABLES], 10, \
  54. tf.random_normal_initializer(0., 0.3), tf.constant_initializer(0.1) # config of layers
  55. # first layer. collections is used later when assign to target net
  56. with tf.variable_scope('l1'):
  57. w1 = tf.get_variable('w1', [self.n_features, n_l1], initializer=w_initializer, collections=c_names)
  58. b1 = tf.get_variable('b1', [1, n_l1], initializer=b_initializer, collections=c_names)
  59. l1 = tf.nn.relu(tf.matmul(self.s, w1) + b1)
  60. # second layer. collections is used later when assign to target net
  61. with tf.variable_scope('l2'):
  62. w2 = tf.get_variable('w2', [n_l1, self.n_actions], initializer=w_initializer, collections=c_names)
  63. b2 = tf.get_variable('b2', [1, self.n_actions], initializer=b_initializer, collections=c_names)
  64. self.q_eval = tf.matmul(l1, w2) + b2
  65. with tf.variable_scope('loss'):
  66. self.loss = tf.reduce_mean(tf.squared_difference(self.q_target, self.q_eval))
  67. with tf.variable_scope('train'):
  68. self._train_op = tf.train.RMSPropOptimizer(self.lr).minimize(self.loss)
  69. # ------------------ build target_net ------------------
  70. self.s_ = tf.placeholder(tf.float32, [None, self.n_features], name='s_') # input
  71. with tf.variable_scope('target_net'):
  72. # c_names(collections_names) are the collections to store variables
  73. c_names = ['target_net_params', tf.GraphKeys.GLOBAL_VARIABLES]
  74. # first layer. collections is used later when assign to target net
  75. with tf.variable_scope('l1'):
  76. w1 = tf.get_variable('w1', [self.n_features, n_l1], initializer=w_initializer, collections=c_names)
  77. b1 = tf.get_variable('b1', [1, n_l1], initializer=b_initializer, collections=c_names)
  78. l1 = tf.nn.relu(tf.matmul(self.s_, w1) + b1)
  79. # second layer. collections is used later when assign to target net
  80. with tf.variable_scope('l2'):
  81. w2 = tf.get_variable('w2', [n_l1, self.n_actions], initializer=w_initializer, collections=c_names)
  82. b2 = tf.get_variable('b2', [1, self.n_actions], initializer=b_initializer, collections=c_names)
  83. self.q_next = tf.matmul(l1, w2) + b2
  84. def store_transition(self, s, a, r, s_):
  85. if not hasattr(self, 'memory_counter'):
  86. self.memory_counter = 0
  87. transition = np.hstack((s, [a, r], s_))
  88. # replace the old memory with new memory
  89. index = self.memory_counter % self.memory_size
  90. self.memory[index, :] = transition
  91. self.memory_counter += 1
  92. def choose_action(self, observation):
  93. # to have batch dimension when feed into tf placeholder
  94. observation = observation[np.newaxis, :]
  95. if np.random.uniform() < self.epsilon:
  96. # forward feed the observation and get q value for every actions
  97. actions_value = self.sess.run(self.q_eval, feed_dict={self.s: observation})
  98. action = np.argmax(actions_value)
  99. else:
  100. action = np.random.randint(0, self.n_actions)
  101. return action
  102. def learn(self):
  103. # check to replace target parameters
  104. if self.learn_step_counter % self.replace_target_iter == 0:
  105. self.sess.run(self.replace_target_op)
  106. print('target_params_replaced\n')
  107. # sample batch memory from all memory
  108. if self.memory_counter > self.memory_size:
  109. sample_index = np.random.choice(self.memory_size, size=self.batch_size)
  110. else:
  111. sample_index = np.random.choice(self.memory_counter, size=self.batch_size)
  112. batch_memory = self.memory[sample_index, :]
  113. q_next, q_eval = self.sess.run(
  114. [self.q_next, self.q_eval],
  115. feed_dict={
  116. self.s_: batch_memory[:, -self.n_features:], # fixed params
  117. self.s: batch_memory[:, :self.n_features], # newest params
  118. })
  119. # change q_target w.r.t q_eval's action
  120. q_target = q_eval.copy()
  121. batch_index = np.arange(self.batch_size, dtype=np.int32)
  122. eval_act_index = batch_memory[:, self.n_features].astype(int)
  123. reward = batch_memory[:, self.n_features + 1]
  124. q_target[batch_index, eval_act_index] = reward + self.gamma * np.max(q_next, axis=1)
  125. # train eval network
  126. _, self.cost,a = self.sess.run([self._train_op, self.loss,self.s],
  127. feed_dict={self.s: batch_memory[:, :self.n_features],
  128. self.q_target: q_target})
  129. self.cost_his.append(self.cost)
  130. # increasing epsilon
  131. self.epsilon = self.epsilon + self.epsilon_increment if self.epsilon < self.epsilon_max else self.epsilon_max
  132. self.learn_step_counter += 1
  133. def plot_cost(self):
  134. import matplotlib.pyplot as plt
  135. plt.plot(np.arange(len(self.cost_his)), self.cost_his)
  136. plt.ylabel('Cost')
  137. plt.xlabel('training steps')
  138. plt.show()