MCPcopy Create free account
hub / github.com/lazyprogrammer/machine_learning_examples / play_one_mc

Function play_one_mc

rl2/cartpole/pg_tf.py:193–243  ·  view source on GitHub ↗
(env, pmodel, vmodel, gamma)

Source from the content-addressed store, hash-verified

191
192
193def play_one_mc(env, pmodel, vmodel, gamma):
194 observation = env.reset()
195 done = False
196 totalreward = 0
197 iters = 0
198
199 states = []
200 actions = []
201 rewards = []
202
203 reward = 0
204 while not done and iters < 2000:
205 # if we reach 2000, just quit, don't want this going forever
206 # the 200 limit seems a bit early
207 action = pmodel.sample_action(observation)
208
209 states.append(observation)
210 actions.append(action)
211 rewards.append(reward)
212
213 prev_observation = observation
214 observation, reward, done, info = env.step(action)
215
216 if done:
217 reward = -200
218
219 if reward == 1: # if we changed the reward to -200
220 totalreward += reward
221 iters += 1
222
223 # save the final (s,a,r) tuple
224 action = pmodel.sample_action(observation)
225 states.append(observation)
226 actions.append(action)
227 rewards.append(reward)
228
229 returns = []
230 advantages = []
231 G = 0
232 for s, r in zip(reversed(states), reversed(rewards)):
233 returns.append(G)
234 advantages.append(G - vmodel.predict(s)[0])
235 G = r + gamma*G
236 returns.reverse()
237 advantages.reverse()
238
239 # update the models
240 pmodel.partial_fit(states, actions, advantages)
241 vmodel.partial_fit(states, returns)
242
243 return totalreward
244
245
246def main():

Callers 1

mainFunction · 0.70

Calls 5

resetMethod · 0.45
sample_actionMethod · 0.45
stepMethod · 0.45
predictMethod · 0.45
partial_fitMethod · 0.45

Tested by

no test coverage detected