-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathARS_Final.py
More file actions
178 lines (123 loc) · 4.89 KB
/
ARS_Final.py
File metadata and controls
178 lines (123 loc) · 4.89 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
import os
import numpy as np
import gym
from gym import wrappers
import pybullet_envs
import matplotlib.pyplot as plt
#The HyperParameters Required
total_steps = 1000
episode_length = 1000
learning_rate = 0.02
total_directions = 16
good_directions = 16
noise = 0.03
env_name = 'HalfCheetahBulletEnv-v0'
class Normalizer():
def __init__(self, input_space):
self.n = np.ones(input_space)
self.mean = np.ones(input_space)
self.mean_diff = np.ones(input_space)
self.var = np.ones(input_space)
def observe(self, x):
self.n = self.n + 1.
last_mean = self.mean.copy()
self.mean += (x - self.mean) / self.n
self.mean_diff += (x - last_mean) * (x - self.mean)
self.var = (self.mean_diff / self.n).clip(min = 1e-2)
def normalize(self, inputs):
obs_mean = self.mean
obs_std = np.sqrt(self.var)
res = (inputs - obs_mean)
return (res/ obs_std)
# Building the AI
class Policy():
def __init__(self, input_size, output_size):
self.theta = np.ones((output_size, input_size))
def evaluate(self, input, delta = None, direction = None):
if direction is None:
return self.theta.dot(input)
val=noise*delta
if direction == "positive":
return (self.theta + val).dot(input)
else:
return (self.theta - val).dot(input)
def sample_deltas(self):
sample=[]
for i in range(total_directions):
sample.append(np.random.randn(*self.theta.shape))
return sample
def update(self, r_pos, r_neg, d, sigma_r):
step = np.ones(self.theta.shape)
for i in range(total_directions):
s = (r_pos[i] - r_neg[i])*d[i]
step = step + s
val = learning_rate / (good_directions * sigma_r) * step
self.theta = self.theta + val
def explore(env, normalizer, policy, direction = None, delta = None):
state = env.reset()
done = False
numTrials = 0.
total_rewards = 0
while not done and numTrials < episode_length:
normalizer.observe(state)
state = normalizer.normalize(state)
action = policy.evaluate(state, delta, direction)
state, reward, done, _ = env.step(action)
total_rewards += reward
numTrials += 1
return total_rewards
def train(env, policy, normalizer):
totalR=[]
for step in range(total_steps):
# initialize the random noise deltas and the positive/negative rewards
deltas = policy.sample_deltas()
positive_rewards = negative_rewards = [i for i in range(total_directions)]
# play an episode each with positive deltas and negative deltas, collect rewards
for k in range(total_directions):
positive_rewards[k] = explore(env, normalizer, policy, direction = "positive", delta = deltas[k])
negative_rewards[k] = explore(env, normalizer, policy, direction = "negative", delta = deltas[k])
# Compute the standard deviation of all rewards
total_rewards = positive_rewards + negative_rewards
all_rewards = np.array(total_rewards)
sigma_r = np.std(all_rewards)
# Sort the rollouts by the max(r_pos, r_neg) and select the deltas with best rewards
scores ={}
for s in range(total_directions):
maxVal= max(positive_rewards[s],negative_rewards[s])
scores.update({s:maxVal})
order = sorted(scores.keys(), key = lambda x:scores[x], reverse = True)[:good_directions]
pos_rew = []
neg_rew = []
delts = []
for k in order:
pos_rew.append(positive_rewards[k])
neg_rew.append(negative_rewards[k])
delts.append(deltas[k])
# Update the policy
policy.update(pos_rew, neg_rew,delts,sigma_r)
reward_evaluation = explore(env, normalizer, policy)
totalR.append(reward_evaluation)
print('Step:', step, 'Reward:', reward_evaluation)
plotResults(totalR)
def saveVideo(base, name):
path = os.path.join(base, name)
if not os.path.exists(path):
os.makedirs(path)
return path
def plotResults(totalR):
fig = plt.figure()
plt.plot(np.arange(1, len(totalR)+1), totalR)
plt.ylabel('Score')
plt.xlabel('Episodes')
plt.show()
def runEnv(env):
inputs_space = env.observation_space.shape[0]
outputs_space = env.action_space.shape[0]
policy = Policy(inputs_space, outputs_space)
normalizer = Normalizer(inputs_space)
train(env, policy, normalizer)
env = gym.make(env_name)
#env = wrappers.Monitor(env, monitor_dir, force = True)
#work_dir = mkdir('exp', 'brs')
#monitor_dir = mkdir(work_dir, 'monitor')
runEnv(env)