-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsoft_double_dqn.py
192 lines (146 loc) · 6.28 KB
/
soft_double_dqn.py
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
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
import math
import random
import gym
import numpy as np
import torch
import torch.nn as nn
import torch.optim as optim
import torch.nn.functional as F
class ReplayBuffer:
def __init__(self, size, state_shape):
self.size = size
self.count = 0
self.state_memory = np.zeros((self.size, *state_shape), dtype=np.float32)
self.action_memory = np.zeros( self.size, dtype=np.int64 )
self.reward_memory = np.zeros( self.size, dtype=np.float32)
self.next_state_memory = np.zeros((self.size, *state_shape), dtype=np.float32)
self.done_memory = np.zeros( self.size, dtype=np.bool )
def store_memory(self, state, action, reward, next_state, done):
index = self.count % self.size
self.state_memory[index] = state
self.action_memory[index] = action
self.reward_memory[index] = reward
self.next_state_memory[index] = next_state
self.done_memory[index] = done
self.count += 1
def sample(self, sample_size):
highest_index = min(self.count, self.size)
indices = np.random.choice(highest_index, sample_size, replace=False)
states = self.state_memory[indices]
actions = self.action_memory[indices]
rewards = self.reward_memory[indices]
next_states = self.next_state_memory[indices]
dones = self.done_memory[indices]
return states, actions, rewards, next_states, dones
class Network(torch.nn.Module):
def __init__(self, learn_rate, input_shape, num_actions):
super().__init__()
self.fc1Dims = 1024
self.fc2Dims = 512
self.fc1 = nn.Linear(*input_shape, self.fc1Dims)
self.fc2 = nn.Linear( self.fc1Dims, self.fc2Dims)
self.fc3 = nn.Linear( self.fc2Dims, num_actions )
self.optimizer = optim.Adam(self.parameters(), lr=learn_rate)
self.loss = nn.MSELoss()
# self.device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
self.device = torch.device("cpu")
self.to(self.device)
def forward(self, x):
x = F.relu(self.fc1(x))
x = F.relu(self.fc2(x))
x = self.fc3(x)
return x
class LinearSchedule:
def __init__(self, start, end, num_steps):
self.delta = (end - start) / float(num_steps)
self.num = start - self.delta
self.count = 0
self.num_steps = num_steps
def value(self):
return self.num
def step(self):
if self.count <= self.num_steps:
self.num += self.delta
self.count += 1
return self.num
class Agent():
def __init__(self, learn_rate, input_shape, num_actions, batch_size):
self.net = Network(learn_rate, input_shape, num_actions)
self.target_net = Network(learn_rate, input_shape, num_actions)
self.memory = ReplayBuffer(size=100000, state_shape=input_shape)
self.epsilon = LinearSchedule(start=1.0, end=0.01, num_steps=2000)
self.batch_size = batch_size
self.num_actions = num_actions
self.gamma = 0.99
self.tau = 0.1
def choose_action(self, observation):
if random.random() > self.epsilon.value():
state = torch.tensor(observation).float().detach()
state = state.to(self.net.device)
state = state.unsqueeze(0)
q_values = self.net(state)
action = torch.argmax(q_values).item()
return action
else:
action = random.randint(0, self.num_actions - 1)
return action
def store_memory(self, state, action, reward, state_, done):
self.memory.store_memory(state, action, reward, state_, done)
def update_params(self):
net_params = self.net.named_parameters()
target_net_params = self.target_net.named_parameters()
target_net = dict(net_params)
net_ = dict(target_net_params)
for name in target_net:
target_net[name] = (
self.tau * target_net[name].clone()
+ (1 - self.tau) * net_[name].clone())
self.target_net.load_state_dict(target_net)
def learn(self):
if self.memory.count < self.batch_size:
return
self.net.optimizer.zero_grad()
states, actions, rewards, states_, dones = \
self.memory.sample(self.batch_size)
states = torch.tensor( states ).to(self.net.device)
actions = torch.tensor( actions ).to(self.net.device)
rewards = torch.tensor( rewards ).to(self.net.device)
states_ = torch.tensor( states_ ).to(self.net.device)
dones = torch.tensor( dones ).to(self.net.device)
batch_indices = np.arange(self.batch_size, dtype=np.int64)
action_qs = self.net(states)[batch_indices, actions] # (batch_size, 1)
qs_ = self.target_net(states_) # (batch_size, num_actions)
policy_qs = self.net(states_) # (batch_size, num_actions)
actions_ = torch.max(policy_qs, dim=1)[1] # (batch_size, 1)
action_qs_ = qs_[batch_indices, actions_]
action_qs_[dones] = 0.0
q_targets = rewards + self.gamma * action_qs_
loss = self.net.loss(q_targets, action_qs).to(self.net.device)
loss.backward()
self.net.optimizer.step()
self.epsilon.step()
self.update_params()
if __name__ == '__main__':
env = gym.make('CartPole-v1').unwrapped
agent = Agent(learn_rate=0.001, input_shape=(4,), num_actions=2, batch_size=64)
high_score = -math.inf
episode = 0
num_samples = 0
while True:
done = False
state = env.reset()
score, frame = 0, 1
while not done:
env.render()
action = agent.choose_action(state)
state_, reward, done, info = env.step(action)
agent.store_memory(state, action, reward, state_, done)
agent.learn()
state = state_
num_samples += 1
score += reward
frame += 1
high_score = max(high_score, score)
print(("total samples: {}, ep {}: high-score {:12.3f}, score {:12.3f}").format(
num_samples, episode, high_score, score, frame))
episode += 1