Advertisement
Guest User

Untitled

a guest
Jul 23rd, 2019
234
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.55 KB | None | 0 0
  1. class DQNAgent:
  2. def __init__(self, state_size, action_size):
  3. self.state_size = state_size
  4. self.action_size = action_size
  5. self.memory = deque(maxlen=300)
  6. self.gamma = 0.95 # discount rate
  7. self.epsilon = 1.0 # exploration rate
  8. self.epsilon_min = 0.01
  9. self.epsilon_decay = 1e-3
  10. self.learning_rate = 0.001
  11. self.model = self._build_model()
  12. self.target_model = self._build_model()
  13. self.update_target_model()
  14. self.start_reduce_epsilon = 200
  15.  
  16.  
  17. def _huber_loss(self, y_true, y_pred, clip_delta=1.0):
  18. error = y_true - y_pred
  19. cond = K.abs(error) <= clip_delta
  20.  
  21. squared_loss = 0.5 * K.square(error)
  22. quadratic_loss = 0.5 * K.square(clip_delta) + clip_delta * (K.abs(error) - clip_delta)
  23.  
  24. return K.mean(tf.where(cond, squared_loss, quadratic_loss))
  25.  
  26. def _build_model(self):
  27. # Neural Net for Deep-Q learning Model
  28. model = Sequential()
  29. model.add(Dense(24, input_dim=self.state_size, activation='relu'))
  30. model.add(Dense(24, activation='relu'))
  31. model.add(Dense(self.action_size, activation='linear'))
  32. model.compile(loss=self._huber_loss,
  33. optimizer=Adam(lr=self.learning_rate))
  34. return model
  35.  
  36. def update_target_model(self):
  37. # copy weights from model to target_model
  38. self.target_model.set_weights(self.model.get_weights())
  39.  
  40. def remember(self, state, action, reward, next_state, done):
  41. self.memory.append((state, action, reward, next_state, done))
  42.  
  43. def act(self, state):
  44. if np.random.rand() <= self.epsilon:
  45. return random.randrange(self.action_size)
  46. act_values = self.model.predict(state)
  47. return np.argmax(act_values[0]) # returns action
  48.  
  49. def replay(self, batch_size):
  50. minibatch = random.sample(self.memory, batch_size)
  51. for state, action, reward, next_state, done in minibatch:
  52. target = self.model.predict(state)
  53. if done:
  54. target[0][action] = reward
  55. else:
  56. t = self.target_model.predict(next_state)[0]
  57. target[0][action] = reward + self.gamma * np.amax(t)
  58. self.model.fit(state, target, epochs=1, verbose=0)
  59.  
  60. def update_epsilon(self, total_step):
  61. if self.epsilon > self.epsilon_min and total_step > self.start_reduce_epsilon:
  62. self.epsilon -= self.epsilon_decay
  63.  
  64. def load(self, name):
  65. self.model.load_weights(name)
  66.  
  67. def save(self, name):
  68. self.model.save_weights(name)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement