-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy patha2c.py
More file actions
274 lines (215 loc) · 6.94 KB
/
a2c.py
File metadata and controls
274 lines (215 loc) · 6.94 KB
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
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
<<<<<<< HEAD
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
from torch.distributions import Categorical
import gym
import numpy as np
from itertools import count
from utils import plotProgress
#A3C without the asynchronous bit
env = gym.make('CartPole-v0')
#Hyper-parameters
lr = 1e-2
GAMMA = 0.99
BATCH_SIZE = 5
OBSERVATIONS_DIM = 4
ACTIONS_DIM = 2
#Used to reduce the learning rate as we progress through epochs
RUNNING_GAMMA = 1
#Policy
class A3CNet(nn.Module):
def __init__(self):
super(A3CNet, self).__init__()
self.model = nn.Sequential(
nn.Linear(OBSERVATIONS_DIM, 32),
nn.ReLU()
)
self.advantage = nn.Sequential(
nn.Linear(32, 32),
nn.ReLU(),
nn.Linear(32, ACTIONS_DIM),
)
self.value = nn.Sequential(
nn.Linear(32, 32),
nn.ReLU(),
nn.Linear(32, 1)
)
def forward(self, x):
out = self.model(x)
advantage = self.advantage(out)
value = self.value(out)
return F.softmax(advantage), F.sigmoid(value)
reward_progress = []
#Model instance
policy = A3CNet()
#RMS prop optimizer
optimizer = optim.RMSprop(policy.parameters(), lr=lr)
#We'll be collecting our experiences for the pcoh using these 3 arrays
state_pool = []
action_pool = []
reward_pool = []
for e in count():
state = env.reset()
for i in count(1):
#Calculate action from policy
state = torch.from_numpy(state).float()
logits, value = policy(state)
m = Categorical(logits)
action = m.sample().numpy()
#Feed our action to the environment
next_state, reward, done, _ = env.step(action)
#If done, its probably because we failed. In that case, nullify our reward
if done:
reward = 0
#Collect experiences
state_pool.append(state)
action_pool.append(float(action))
reward_pool.append(reward)
state = next_state
#Add to reward_pool and plot our progress
if done:
print("Reward: ", i)
reward_progress.append(i)
plotProgress(reward_progress)
break
#We'll be stepping every BATCH_SIZE epochs
if e > 0 and e % BATCH_SIZE == 0:
running_add = 0
for i in reversed(range(len(state_pool))):
if(reward_pool[i] == 0):
running_add = 0
else :
running_add = running_add*GAMMA + reward_pool[i]
reward_pool[i] = running_add
reward_pool = np.array(reward_pool)
reward_pool = (reward_pool - reward_pool.mean())/reward_pool.std()
optimizer.zero_grad()
loss = 0
for j in reversed(range(len(state_pool))):
state = state_pool[j]
action = torch.tensor(action_pool[j]).float()
reward = np.int(reward_pool[j])
logits, value = policy(state)
logits = logits
m = Categorical(logits)
inter = reward - value
value_loss = 0.5*inter.pow(2)
policy_loss = -inter.detach()*m.log_prob(action)*RUNNING_GAMMA
total_loss = value_loss + policy_loss
loss += total_loss
loss.backward()
optimizer.step()
RUNNING_GAMMA *= GAMMA
state_pool = []
action_pool = []
reward_pool = []
=======
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
from torch.distributions import Categorical
import gym
import numpy as np
from itertools import count
from utils import plotProgress
#create the environment
env = gym.make('CartPole-v0')
#Hyper-parameters
lr = 1e-2
GAMMA = 0.99
BATCH_SIZE = 5
OBSERVATIONS_DIM = 4
ACTIONS_DIM = 2
#Used to reduce the learning rate as we progress through epochs
RUNNING_GAMMA = 1
#Policy
class A3CNet(nn.Module):
def __init__(self):
super(A3CNet, self).__init__()
self.model = nn.Sequential(
nn.Linear(OBSERVATIONS_DIM, 32),
nn.ReLU()
)
self.advantage = nn.Sequential(
nn.Linear(32, 32),
nn.ReLU(),
nn.Linear(32, ACTIONS_DIM),
)
self.value = nn.Sequential(
nn.Linear(32, 32),
nn.ReLU(),
nn.Linear(32, 1)
)
def forward(self, x):
out = self.model(x)
advantage = self.advantage(out)
value = self.value(out)
return F.softmax(advantage), F.sigmoid(value)
reward_progress = []
#Model instance
policy = A3CNet()
#RMS prop optimizer
optimizer = optim.RMSprop(policy.parameters(), lr=lr)
#We'll be collecting our experiences for the pcoh using these 3 arrays
state_pool = []
action_pool = []
reward_pool = []
for e in count():
state = env.reset()
for i in count(1):
#Calculate action from policy
state = torch.from_numpy(state).float()
logits, value = policy(state)
m = Categorical(logits)
action = m.sample().numpy()
#Feed our action to the environment
next_state, reward, done, _ = env.step(action)
#If done, its probably because we failed. In that case, nullify our reward
if done:
reward = 0
#Collect experiences
state_pool.append(state)
action_pool.append(float(action))
reward_pool.append(reward)
state = next_state
#Add to reward_pool and plot our progress
if done:
print("Reward: ", i)
reward_progress.append(i)
plotProgress(reward_progress)
break
#We'll be stepping every BATCH_SIZE epochs
if e > 0 and e % BATCH_SIZE == 0:
running_add = 0
for i in reversed(range(len(state_pool))):
if(reward_pool[i] == 0):
running_add = 0
else :
running_add = running_add*GAMMA + reward_pool[i]
reward_pool[i] = running_add
reward_pool = np.array(reward_pool)
reward_pool = (reward_pool - reward_pool.mean())/reward_pool.std()
optimizer.zero_grad()
loss = 0
for j in reversed(range(len(state_pool))):
state = state_pool[j]
action = torch.tensor(action_pool[j]).float()
reward = np.int(reward_pool[j])
logits, value = policy(state)
logits = logits
m = Categorical(logits)
inter = reward - value
value_loss = 0.5*inter.pow(2)
policy_loss = -inter.detach()*m.log_prob(action)*RUNNING_GAMMA
total_loss = value_loss + policy_loss
loss += total_loss
loss.backward()
optimizer.step()
RUNNING_GAMMA *= GAMMA
state_pool = []
action_pool = []
reward_pool = []
>>>>>>> bd72a2cc82c6c93e9d5353b573d0a228de7164d4