|
| 1 | +import math |
| 2 | +import random |
| 3 | +import matplotlib |
| 4 | +import matplotlib.pyplot as plt |
| 5 | +from collections import namedtuple, deque |
| 6 | +from itertools import count |
| 7 | + |
| 8 | +import numpy as np |
| 9 | +import torch |
| 10 | +import torch.nn as nn |
| 11 | +import torch.optim as optim |
| 12 | +import torch.nn.functional as F |
| 13 | + |
| 14 | +from scripts.Chris.DQN.Environment import Maze_Environment |
| 15 | + |
| 16 | +Transition = namedtuple('Transition', |
| 17 | + ('state', 'action', 'next_state', 'reward')) |
| 18 | + |
| 19 | +class ReplayMemory(object): |
| 20 | + def __init__(self, capacity): |
| 21 | + self.memory = deque([], maxlen=capacity) |
| 22 | + |
| 23 | + def push(self, *args): |
| 24 | + """Save a transition""" |
| 25 | + self.memory.append(Transition(*args)) |
| 26 | + |
| 27 | + def sample(self, batch_size): |
| 28 | + return random.sample(self.memory, batch_size) |
| 29 | + |
| 30 | + def __len__(self): |
| 31 | + return len(self.memory) |
| 32 | + |
| 33 | +class DQN(nn.Module): |
| 34 | + |
| 35 | + def __init__(self, n_observations, n_actions): |
| 36 | + super(DQN, self).__init__() |
| 37 | + self.layer1 = nn.Linear(n_observations, 128) |
| 38 | + self.layer2 = nn.Linear(128, 128) |
| 39 | + self.layer3 = nn.Linear(128, n_actions) |
| 40 | + |
| 41 | + # Called with either one element to determine next action, or a batch |
| 42 | + # during optimization. Returns tensor([[left0exp,right0exp]...]). |
| 43 | + def forward(self, x): |
| 44 | + x = F.relu(self.layer1(x)) |
| 45 | + x = F.relu(self.layer2(x)) |
| 46 | + return self.layer3(x) |
| 47 | + |
| 48 | + |
| 49 | +# Select action using epsilon-greedy policy |
| 50 | +def select_action(state, step, eps, policy_net, env): |
| 51 | + # eps_threshold = EPS_END + (EPS_START - EPS_END) * \ |
| 52 | + # math.exp(-1. * step / EPS_DECAY) |
| 53 | + |
| 54 | + # Select action from policy net |
| 55 | + if random.random() > eps: |
| 56 | + with torch.no_grad(): |
| 57 | + # t.max(1) will return the largest column value of each row. |
| 58 | + # second column on max result is index of where max element was |
| 59 | + # found, so we pick action with the larger expected reward. |
| 60 | + return policy_net(state).max(1).indices.view(1, 1) |
| 61 | + |
| 62 | + # Select random action (exploration) |
| 63 | + else: |
| 64 | + return torch.tensor(np.random.choice(env.num_actions)).view(1, 1) |
| 65 | + |
| 66 | + |
| 67 | +# Optimize DQN |
| 68 | +def optimize_model(memory, batch_size, policy_net, target_net, optimizer, gamma, device): |
| 69 | + if len(memory) < batch_size: |
| 70 | + return |
| 71 | + transitions = memory.sample(batch_size) |
| 72 | + # Transpose the batch (see https://stackoverflow.com/a/19343/3343043 for |
| 73 | + # detailed explanation). This converts batch-array of Transitions |
| 74 | + # to Transition of batch-arrays. |
| 75 | + batch = Transition(*zip(*transitions)) |
| 76 | + |
| 77 | + # Compute a mask of non-final states and concatenate the batch elements |
| 78 | + # (a final state would've been the one after which simulation ended) |
| 79 | + non_final_mask = torch.tensor(tuple(map(lambda s: s is not None, |
| 80 | + batch.next_state)), device=device, dtype=torch.bool) |
| 81 | + non_final_next_states = torch.cat([s for s in batch.next_state |
| 82 | + if s is not None]) |
| 83 | + state_batch = torch.cat(batch.state) |
| 84 | + action_batch = torch.cat(batch.action) |
| 85 | + reward_batch = torch.cat(batch.reward) |
| 86 | + |
| 87 | + # Compute Q(s_t, a) - the model computes Q(s_t), then we select the |
| 88 | + # columns of actions taken. These are the actions which would've been taken |
| 89 | + # for each batch state according to policy_net |
| 90 | + state_action_values = policy_net(state_batch).gather(1, action_batch) |
| 91 | + |
| 92 | + # Compute V(s_{t+1}) for all next states. |
| 93 | + # Expected values of actions for non_final_next_states are computed based |
| 94 | + # on the "older" target_net; selecting their best reward with max(1).values |
| 95 | + # This is merged based on the mask, such that we'll have either the expected |
| 96 | + # state value or 0 in case the state was final. |
| 97 | + next_state_values = torch.zeros(batch_size, device=device) |
| 98 | + with torch.no_grad(): |
| 99 | + next_state_values[non_final_mask] = target_net(non_final_next_states).max(1).values |
| 100 | + # Compute the expected Q values |
| 101 | + expected_state_action_values = (next_state_values * gamma) + reward_batch |
| 102 | + |
| 103 | + # Compute Huber loss |
| 104 | + criterion = nn.SmoothL1Loss() |
| 105 | + loss = criterion(state_action_values, expected_state_action_values.unsqueeze(1)) |
| 106 | + |
| 107 | + # Optimize the model |
| 108 | + optimizer.zero_grad() |
| 109 | + loss.backward() |
| 110 | + # In-place gradient clipping |
| 111 | + torch.nn.utils.clip_grad_value_(policy_net.parameters(), 100) |
| 112 | + optimizer.step() |
| 113 | + |
| 114 | + |
| 115 | +if __name__ == '__main__': |
| 116 | + device = 'cpu' |
| 117 | + n_actions = 4 |
| 118 | + n_observations = 2 |
| 119 | + LR = 0.01 |
| 120 | + EPS_START = 0.9 |
| 121 | + EPS_END = 0.05 |
| 122 | + EPS_DECAY = 1000 |
| 123 | + TAU = 0.005 |
| 124 | + GAMMA = 0.99 |
| 125 | + MAX_STEPS_PER_EP = 1000 |
| 126 | + TOTAL_STEPS = 10000 |
| 127 | + MAX_EPS = 300 |
| 128 | + BATCH_SIZE = 128 |
| 129 | + |
| 130 | + policy_net_ = DQN(n_observations, n_actions).to(device) |
| 131 | + target_net_ = DQN(n_observations, n_actions).to(device) |
| 132 | + target_net_.load_state_dict(policy_net_.state_dict()) |
| 133 | + optimizer_ = optim.AdamW(policy_net_.parameters(), lr=LR, amsgrad=True) |
| 134 | + memory_ = ReplayMemory(10000) |
| 135 | + env_ = Maze_Environment(width=5, height=5) |
| 136 | + |
| 137 | + episode_durations = [] |
| 138 | + episodes = 0 |
| 139 | + total_steps = 0 |
| 140 | + print(env_.maze) |
| 141 | + while total_steps < TOTAL_STEPS and episodes < MAX_EPS: |
| 142 | + # Initialize the environment and get its state |
| 143 | + state, info = env_.reset() |
| 144 | + state = torch.tensor(state.coordinates, dtype=torch.float32, device=device).unsqueeze(0) |
| 145 | + # print(f"Episode {i_episode}") |
| 146 | + for t in count(): |
| 147 | + eps = EPS_END + (EPS_START - EPS_END) * math.exp(-1. * total_steps / EPS_DECAY) |
| 148 | + action = select_action(state, t, eps, policy_net_, env_) |
| 149 | + observation, reward, terminated, _ = env_.step(action.item()) |
| 150 | + reward = torch.tensor([reward], device=device) |
| 151 | + |
| 152 | + if terminated: |
| 153 | + next_state = None |
| 154 | + else: |
| 155 | + next_state = torch.tensor(observation.coordinates, dtype=torch.float32, device=device).unsqueeze(0) |
| 156 | + |
| 157 | + # Store the transition in memory |
| 158 | + memory_.push(state, action, next_state, reward) |
| 159 | + |
| 160 | + # Move to the next state |
| 161 | + state = next_state |
| 162 | + |
| 163 | + # Perform one step of the optimization (on the policy network) |
| 164 | + optimize_model(memory_, BATCH_SIZE, policy_net_, target_net_, optimizer_, gamma=GAMMA, device=device) |
| 165 | + |
| 166 | + # Soft update of the target network's weights |
| 167 | + # θ′ ← τ θ + (1 −τ )θ′ |
| 168 | + target_net_state_dict = target_net_.state_dict() |
| 169 | + policy_net_state_dict = policy_net_.state_dict() |
| 170 | + for key in policy_net_state_dict: |
| 171 | + target_net_state_dict[key] = policy_net_state_dict[key] * TAU + target_net_state_dict[key] * (1 - TAU) |
| 172 | + target_net_.load_state_dict(target_net_state_dict) |
| 173 | + |
| 174 | + total_steps += 1 |
| 175 | + if terminated or t > MAX_STEPS_PER_EP: |
| 176 | + episode_durations.append(t + 1) |
| 177 | + break |
| 178 | + print(f"Episode {episodes} lasted {t+1} steps, eps = {round(eps, 2)} total steps = {total_steps}") |
| 179 | + episodes += 1 |
| 180 | + |
| 181 | + plt.plot(episode_durations) |
| 182 | + plt.show() |
0 commit comments