|
| 1 | +import random |
| 2 | +import math |
| 3 | +from itertools import count |
| 4 | + |
| 5 | +import gym |
| 6 | +import torch |
| 7 | +import torch.optim as optim |
| 8 | +import torch.nn.functional as F |
| 9 | +import matplotlib.pyplot as plt |
| 10 | + |
| 11 | +from DQN import DQN |
| 12 | +from utils import get_screen |
| 13 | +from utils import plot_durations |
| 14 | +from memory import ReplayMemory |
| 15 | +from memory import Transition |
| 16 | + |
| 17 | +def select_action(state): |
| 18 | + global steps_done |
| 19 | + sample = random.random() |
| 20 | + eps_threshold = EPS_END + (EPS_START - EPS_END) * \ |
| 21 | + math.exp(-steps_done / float(EPS_DECAY)) |
| 22 | + steps_done += 1 |
| 23 | + |
| 24 | + # random strategy: at begining always take the random strategy |
| 25 | + if sample < eps_threshold: |
| 26 | + return torch.tensor([[random.randrange(2)]], device=device, dtype=torch.long) |
| 27 | + else: |
| 28 | + return policy_net(state).max(1)[1].view(1,1) |
| 29 | + |
| 30 | + |
| 31 | +def optimize_model(policy_net, optimizer): |
| 32 | + # first sample a batch |
| 33 | + if len(memory) < BATCH_SIZE: |
| 34 | + return |
| 35 | + transitions = memory.sample(BATCH_SIZE) |
| 36 | + batch = Transition(*zip(*transitions)) |
| 37 | + # non_final_mask is the mask to tag all the item whose next_state is not None as True |
| 38 | + non_final_mask = tuple(map(lambda s: s is not None, batch.next_state)) |
| 39 | + non_final_mask = torch.tensor(non_final_mask, device=device, dtype=torch.uint8) |
| 40 | + non_final_next_states = torch.cat([s for s in batch.next_state if s is not None]) |
| 41 | + |
| 42 | + state_batch = torch.cat(batch.state) |
| 43 | + action_batch = torch.cat(batch.action) |
| 44 | + reward_batch = torch.cat(batch.reward) |
| 45 | + |
| 46 | + # policy_net(state_batch) is used to get all value among all actions |
| 47 | + # gather method is used to get the value corresponding to certain action |
| 48 | + state_action_values = policy_net(state_batch).gather(1, action_batch) |
| 49 | + |
| 50 | + next_state_values = torch.zeros(BATCH_SIZE, device=device) |
| 51 | + |
| 52 | + # compute the V(s_{t+1}) for $s_{t+1}$ which is final state, we set V(s_{t+1}) = 0 |
| 53 | + next_state_values[non_final_mask] = target_net(non_final_next_states).max(1)[0].detach() |
| 54 | + expected_state_action_values = (next_state_values * GAMMA) + reward_batch |
| 55 | + |
| 56 | + # Huber loss |
| 57 | + loss = F.smooth_l1_loss(state_action_values, expected_state_action_values.unsqueeze(1)) |
| 58 | + |
| 59 | + optimizer.zero_grad() |
| 60 | + loss.backward() |
| 61 | + for param in policy_net.parameters(): |
| 62 | + param.grad.data.clamp_(-1, 1) |
| 63 | + optimizer.step() |
| 64 | + |
| 65 | +env = gym.make('CartPole-v0').unwrapped |
| 66 | +device = torch.device("cuda" if torch.cuda.is_available() else "cpu") |
| 67 | +env.reset() |
| 68 | + |
| 69 | +BATCH_SIZE = 128 |
| 70 | +# GAMMA is the discount factor |
| 71 | +GAMMA = 0.999 |
| 72 | +EPS_START = 0.9 |
| 73 | +EPS_END = 0.05 |
| 74 | +EPS_DECAY = 200 |
| 75 | + |
| 76 | +TARGET_UPDATE = 10 |
| 77 | + |
| 78 | +AVERAGE_SIZE = 10 |
| 79 | +episode_durations = [] |
| 80 | + |
| 81 | +init_screen = get_screen(env, device) |
| 82 | +_, _, screen_height, screen_width = init_screen.shape |
| 83 | + |
| 84 | +policy_net = DQN(screen_height, screen_width).to(device) |
| 85 | +target_net = DQN(screen_height, screen_width).to(device) |
| 86 | + |
| 87 | +target_net.load_state_dict(policy_net.state_dict()) |
| 88 | +target_net.eval() |
| 89 | + |
| 90 | +optimizer = optim.RMSprop(policy_net.parameters()) |
| 91 | +memory = ReplayMemory(10000) |
| 92 | + |
| 93 | +steps_done = 0 |
| 94 | +num_episodes = 300 |
| 95 | +for i_episode in range(num_episodes): |
| 96 | + env.reset() |
| 97 | + last_screen = get_screen(env, device) |
| 98 | + current_screen = get_screen(env, device) |
| 99 | + state = current_screen - last_screen |
| 100 | + #print state |
| 101 | + for t in count(): |
| 102 | + action = select_action(state) |
| 103 | + _, reward, done, _ = env.step(action.item()) |
| 104 | + reward = torch.tensor([reward], device=device) |
| 105 | + |
| 106 | + last_screen = current_screen |
| 107 | + current_screen = get_screen(env, device) |
| 108 | + |
| 109 | + if not done: |
| 110 | + next_state = current_screen - last_screen |
| 111 | + else: |
| 112 | + next_state = None |
| 113 | + |
| 114 | + memory.push(state, action, next_state, reward) |
| 115 | + |
| 116 | + state = next_state |
| 117 | + #if done: |
| 118 | + # print "Episode Done" |
| 119 | + #else: |
| 120 | + # print state.size() |
| 121 | + optimize_model(policy_net, optimizer) |
| 122 | + if done: |
| 123 | + episode_durations.append(t+1) |
| 124 | + plot_durations(episode_durations, AVERAGE_SIZE) |
| 125 | + break |
| 126 | + |
| 127 | + if i_episode % TARGET_UPDATE == 0: |
| 128 | + target_net.load_state_dict(policy_net.state_dict()) |
| 129 | + |
| 130 | +print("Complet") |
| 131 | +env.render() |
| 132 | +env.close() |
| 133 | +plt.ioff() |
| 134 | +plt.show() |
| 135 | + |
| 136 | + |
| 137 | + |
0 commit comments