-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathppo.py
More file actions
136 lines (106 loc) · 3.38 KB
/
ppo.py
File metadata and controls
136 lines (106 loc) · 3.38 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
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 = []