-
Notifications
You must be signed in to change notification settings - Fork 0
/
PPO_agent.py
51 lines (40 loc) · 1.27 KB
/
PPO_agent.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
import argparse
import sys
import numpy as np
import gym
from gym import wrappers, logger
env = gym.make("CartPole-v0")
# code to create videos of the episodes
outdir = "./recordings"
env = wrappers.Monitor(env, directory=outdir, force=True, uid="", write_upon_reset=False)
def run_episode(params):
total_reward = 0
observation = env.reset()
while True:
# apply policy to the observation and return an action
# the @ symbol denotes matrix multiplication
if param @ observation < 0:
action = 0
else:
action = 1
# this collects all the information given in each step of the environment
observation, reward, done, info = env.step(action)
total_reward += reward
env.render()
if done:
break
return total_reward
episode_count = 126
reward = 0
done = False
max_reward = 0
for i in range(episode_count):
# generate a random policy
param = np.random.rand(4)
total_reward = run_episode(param)
# track the current max reward
max_reward = max(max_reward, total_reward)
# if the max reward is 200 (the highest it can be) the policy is the best policy
if max_reward >= 200:
print("Best Policy: ", param)
env.close()