forked from hunkim/ReinforcementZeroToAll
-
Notifications
You must be signed in to change notification settings - Fork 0
/
09_2_cross_entropy.py
189 lines (139 loc) · 3.83 KB
/
09_2_cross_entropy.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
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
"""
Cross Entropy Method
Cross Entropy Method is a simple and efficient method
for solving a variety of estimation and optimization problems.
Psuedocode
initialize mu, sd
while not done:
collect N samples of theta ~ N(mu, diag(sd))
perform one episode with each theta
select top performing samples, called elite set
obtain a new mu and sd
end
"""
import numpy as np
import gym
env = gym.make("CartPole-v0")
INPUT_SIZE = env.observation_space.shape[0]
OUTPUT_SIZE = env.action_space.n
def get_W_b(theta):
"""Get W and b
Parameters
----------
theta : 1-d array
Flatten theta
Returns
----------
W : 2-d array
b : 1-d array
Examples
----------
>>> theta = np.random.randn(5)
>>> W, b = get_W_b(theta)
"""
idx = INPUT_SIZE * OUTPUT_SIZE
W = theta[:idx].reshape(INPUT_SIZE, OUTPUT_SIZE)
b = theta[idx:].reshape(OUTPUT_SIZE)
return W, b
def choose_action(s, W, b):
"""Return an action (argmax)
Parameters
----------
s : ndarray
Observation (input_dim, )
W : ndarray, (input_dim, number_of_actions)
b : ndarray, (number_of_actions)
Returns
----------
action: int
action index
Examples
----------
>>> s = env.reset()
>>> W, b = get_W_b(theta)
>>> action = choose_action(s, W, b)
"""
action = np.dot(s, W) + b
return np.argmax(action)
def run_episode(env, theta, render=False):
""" Run a single episode with theta
Parameters
----------
env : gym environment
theta : 1-d array
render : bool, optional
Returns
----------
reward : float
Episode reward
Examples
----------
>>> env = gym.make('CartPole-v0')
>>> reward = run_episode(env, theta)
"""
W, b = get_W_b(theta)
s = env.reset()
done = False
reward = 0
while not done:
if render:
env.render()
a = choose_action(s, W, b)
s2, r, done, info = env.step(a)
reward += r
s = s2
return reward
def make_theta(theta_mean, theta_sd):
""" Make a theta parameters with mean and sd
Parameters
----------
theta_mean : ndarray
A n-d array of means
theta_sd : nd array
A n-d array of standard deviations
Returns
----------
theta : n-d array
Shape (n, )
Examples
----------
>>> DIM = INPUT_SIZE * OUTPUT_SIZE + OUTPUT_SIZE
>>> mu = np.zeros(DIM)
>>> sd = np.ones(SD)
>>> theta = make_theta(mu, sd)
"""
return np.random.multivariate_normal(mean=theta_mean, cov=np.diag(theta_sd),)
def main():
""" Every magic happens here """
global env, INPUT_SIZE, OUTPUT_SIZE
# Number of samples
N = 32
# Size of theta
DIM = INPUT_SIZE * OUTPUT_SIZE + OUTPUT_SIZE
# Initialize parameters
theta_mean = np.zeros(DIM)
theta_sd = np.ones(DIM)
# Loop until clear the game
# make population with mean & sd
# choose elite groups
# obtain new mean & sd
for _ in range(100):
population = [make_theta(theta_mean, theta_sd) for _ in range(N)]
reward = [run_episode(env, p) for p in population]
sorted_idx = np.argsort(reward)[-int(N * 0.20):]
elite_population = [population[idx] for idx in sorted_idx]
elite_reward = [reward[idx] for idx in sorted_idx]
theta_mean = np.mean(elite_population, axis=0)
theta_sd = np.std(elite_population, axis=0)
avg_reward = np.mean(elite_reward)
print("Reward: {}".format(avg_reward))
if avg_reward == 200:
print("Game Cleared")
break
env = gym.wrappers.Monitor(env, "gym-results/", force=True)
best_parm = elite_population[-1]
for i in range(100):
reward = run_episode(env, best_parm)
print(reward)
if __name__ == '__main__':
main()