1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168
| import torch import torch.nn as nn import torch.optim as optim import torch.nn.functional as F
class SDQN(nn.Module): def __init__(self, input_size, output_size): super(SDQN, self).__init__() self.input_size = input_size self.output_size = output_size
self.fc1 = nn.Linear(input_size, 128) self.fc2 = nn.Linear(128, 128) self.fc3 = nn.Linear(128, output_size)
def forward(self, x): x = x.view(-1, self.input_size) x = F.relu(self.fc1(x)) x = F.relu(self.fc2(x)) return self.fc3(x)
def save(self, path): torch.save(self.state_dict(), path)
def load(self, path): self.load_state_dict(torch.load(path))
class ReplayMemory(object): def __init__(self, capacity): self.capacity = capacity self.memory = [] self.position = 0
def push(self, state, action, reward, next_state, done): if len(self.memory) < self.capacity: self.memory.append(None)
self.memory[self.position] = (state, action, reward, next_state, done) self.position = (self.position + 1) % self.capacity
def sample(self, batch_size): return random.sample(self.memory, batch_size)
def __len__(self): return len(self.memory)
class Agent(object): def __init__(self, input_size, output_size, memory_size, batch_size, gamma, lr): self.input_size = input_size self.output_size = output_size self.memory = ReplayMemory(memory_size) self.batch_size = batch_size self.gamma = gamma self.lr = lr
self.model = SDQN(input_size, output_size) self.optimizer = optim.Adam(self.model.parameters(), lr=lr) def select_action(self, state): state = torch.from_numpy(state).float().unsqueeze(0) q_values = self.model(state) action = q_values.max(1)[1].item() return action def optimize(self): if len(self.memory) < self.batch_size: return transitions = self.memory.sample(self.batch_size) batch = Transition(*zip(*transitions))
state_batch = torch.cat(batch.state) action_batch = torch.cat(batch.action) reward_batch = torch.cat(batch.reward) next_state_batch = torch.cat(batch.next_state)
state_action_values = self.model(state_batch).gather(1, action_batch) next_state_values = self.model(next_state_batch).max(1)[0].detach() expected_state_action_values = (next_state_values * self.gamma) + reward_batch
loss = F.smooth_l1_loss(state_action_values, expected_state_action_values.unsqueeze(1))
self.optimizer.zero_grad() loss.backward() self.optimizer.step() def save(self, path): self.model.save(path) def load(self, path): self.model.load(path) pass def push(self, state, action, reward, next_state, done): self.memory.push(state, action, reward, next_state, done) def __len__(self): return len(self.memory) def __repr__(self): return self.model.__repr__()
import gym import random from collections import namedtuple
Transition = namedtuple("Transition", ("state", "action", "reward", "next_state", "done"))
def train(env, agent, num_episodes, max_steps): for episode in range(num_episodes): state = env.reset() for step in range(max_steps): action = agent.select_action(state) next_state, reward, done, _ = env.step(action) agent.push(state, action, reward, next_state, done) agent.optimize() state = next_state if done: break print("Episode: {}, Step: {}".format(episode, step)) env.close()
def test(env, agent, num_episodes, max_steps): for episode in range(num_episodes): state = env.reset() for step in range(max_steps): action = agent.select_action(state) next_state, reward, done, _ = env.step(action) state = next_state if done: break print("Episode: {}, Step: {}".format(episode, step)) env.close() if __name__ == "__main__": env_name = "CartPole-v0" num_episodes = 1000 max_steps = 1000 memory_size = 10000 batch_size = 128 gamma = 0.99 lr = 1e-3 save_path = "model.pt" env = gym.make(env_name) input_size = env.observation_space.shape[0] output_size = env.action_space.n agent = Agent(input_size, output_size, memory_size, batch_size, gamma, lr) train(env, agent, num_episodes, max_steps) agent.save(save_path) agent.load(save_path) test(env, agent, num_episodes, max_steps)
|