@MikeShi42/

CartPole

Python

Policy Search to solve OpenAI Gym's Cart Pole Problem

fork
loading
Files
  • main.py
  • _.py
  • index.html
  • requirements.txt
main.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
# Click Run Above to Start Training the Model
# After training, the best policy will automatically replay on the
# browser on the right.

import gym
import numpy as np

env = gym.make('CartPole-v1')

def play(env, policy):
  observation = env.reset()
  
  done = False
  score = 0
  observations = []
  
  for _ in range(5000):
    observations += [observation.tolist()] # Record the observations for normalization and replay
    
    if done: # If the simulation was over last iteration, exit loop
      break
        
    # Pick an action according to the policy matrix
    outcome = np.dot(policy, observation)
    action = 1 if outcome > 0 else 0
    
    # Make the action, record reward
    observation, reward, done, info = env.step(action)
    score += reward

  return score, observations

print('💪💪💪 Training Policy... \n')

max = (0, [], [])

for _ in range(100):
  policy = np.random.rand(1,4) - 0.5
  score, observations = play(env, policy)
  
  if score > max[0]:
    max = (score, observations, policy)

print('Max Score', max[0], 'out of 500 \n')

scores = []
for _ in range(100):
  score, _  = play(env, max[2])
  scores += [score]
  
print('Average Score (100 trials)', np.mean(scores))

print('Starting Replay Server...')

from flask import Flask
import json

app = Flask(__name__, static_folder='.')

@app.route("/data")
def data():
    return json.dumps(max[1])

@app.route('/')
def root():
    return app.send_static_file('./index.html')
    
app.run(host='0.0.0.0', port='3000')