-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathcar.py
211 lines (161 loc) · 6.48 KB
/
car.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
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
import gym
import numpy as np
from maze import *
from matplotlib import pyplot as plt
from evaluationCar import *
from evaluationREINFORCE import *
env = gym.make("MountainCarContinuous-v0")
observation = env.reset()
env._max_episode_steps = 2000
discount = 0.9
# get the actionsSpace
# [position]
actionSpace = env.action_space
actionSpaceLowerBound = actionSpace.low
actionSpaceUpperBound = actionSpace.high
# descritize the action space
numBinsActions = 100
actionBins = np.linspace(actionSpaceLowerBound, actionSpaceUpperBound, numBinsActions)
# get the observations space
# [position, velocity]
observationSpace = env.observation_space
obsSpaceLowerbound = observationSpace.low
obsSpaceUpperbound = observationSpace.high
# descritize the observation space
numBinsObs = 100
obsBinsPos = np.linspace(obsSpaceLowerbound[0], obsSpaceUpperbound[0], numBinsObs)
obsBinsVel = np.linspace(obsSpaceLowerbound[1], obsSpaceUpperbound[1], numBinsObs)
#do the policy gradient
def REINFORCECar():
learningRate = .9
eval_steps, eval_reward = [], []
# for function approxomation
theta = np.random.random(size=(2,numBinsActions))
#baseline
b = np.sum(2,)
numIter = 1000
for i_episode in range(numIter):
#collect a set of trajectories by executing current policy
time = 2000
trajectories = np.zeros((3,time)) #(state,action,reward)
#collect a set the average of the observations
scores = np.zeros((2,time))
observation = env.reset()
for t in range(time-1):
# find the value of phi*theta
phiTheta = np.dot(observation, theta)
# take exponentials for softmax
phiThetaExp = np.exp(phiTheta)
# find the probailities of each column
probs = np.mean(phiThetaExp, axis=0) / np.mean(phiThetaExp)
# e-greedy probaility
e = 1.0 - t / (100)
# randomly pick action based on epsilon
if np.random.rand() < e:
action = random.uniform(actionSpaceLowerBound, actionSpaceUpperBound)
else:
# find the appropriate action
actionDes = int(np.argmax(probs))
action = np.array(actionBins[actionDes]).reshape((1,))
#take a step
observationPrime, reward, done, info = env.step(action)
#fill im trajectories
trajectories[1,t] = action
trajectories[2,t] = reward
#fill in the scores
scores[:,t] = (observation - observation/3).reshape(2,)
observation = observationPrime
env.render()
# evaluation
if (i_episode % 50 == 0):
avg_step, avg_reward = evaluationREINFORCE(env, action)
eval_steps.append(avg_step)
eval_reward.append(avg_reward)
#find gradient of J(theta)
for t in range(time):
#find Gt and update bt
Gt = 0
for tRest in range(t,time-1):
Gt = Gt + ((discount**tRest) * trajectories[2,tRest])
#get b
b = np.mean(trajectories[2,:])
#get the advantage
At = Gt - b
#correct action taken
action = int(trajectories[1,t])
#calculate g-hat, the gradient of logPi
gHat = scores[:,t]
#reconfigure thetas
theta[:,action] = theta[:,action] #+ learningRate * discount * At * gHat
f2, ax2 = plt.subplots()
# repeat for different algs
ax2.plot(range(0, numIter, 50), eval_steps)
f2.suptitle('Evaluation Steps')
f3, ax3 = plt.subplots()
# repeat for different algs
ax3.plot(range(0, numIter, 50), eval_reward)
f3.suptitle('Evaluation Reward')
plt.show()
def qLearningMountain():
learningRate = .2
eval_steps, eval_reward = [], []
qVals = np.random.choice(a = np.linspace(0,100,100), size=(numBinsObs,numBinsObs,numBinsActions))
numIter = 500
for i_episode in range(numIter):
observation = env.reset()
for t in range(2000):
env.render()
#get the descritized states
pos = observation[0]
vel = observation[1]
posDes = np.digitize(pos, obsBinsPos)
velDes = np.digitize(vel, obsBinsVel)
# e-greedy probaility
e = 1.0 - t / (100)
# randomly pick action based on epsilon
if np.random.rand() < e:
action = random.uniform(actionSpaceLowerBound, actionSpaceUpperBound)
#discretize the action
actionDes = np.digitize(action, actionBins)
else:
# get the action derived from q for current state
possibleActions = qVals[posDes,velDes, :]
actionDes = np.argmax(possibleActions)
action = np.array(actionBins[actionDes]).reshape((1,))
# take that action and step
observationPrime, reward, done, info = env.step(action)
# get the current q value
currQVal = qVals[posDes,velDes,actionDes]
#descretize the observation primes
posPrime = np.digitize(observationPrime[0], obsBinsPos)
velPrime = np.digitize(observationPrime[1], obsBinsVel)
# get the possible qvalues for s'
possibleNewStates = qVals[posPrime,velPrime, :]
# get the best action based on the next state s'
actionPrime = np.argmax(possibleNewStates)
# get the q value of that state
maxQSPrime = qVals[posPrime,velPrime, actionPrime]
# update the q value table
qVals[posDes,velDes,actionDes] = currQVal + learningRate * (reward + discount * maxQSPrime - currQVal)
# set the current state equal to the next state
observation = observationPrime
if done:
print("Episode finished after {} timesteps".format(t + 1))
break
#evaluation
if (i_episode % 50 == 0):
avg_step, avg_reward = evaluationCar(env, qVals,50,numIter)
eval_steps.append(avg_step)
eval_reward.append(avg_reward)
f2, ax2 = plt.subplots()
# repeat for different algs
ax2.plot(range(0, numIter, 50),eval_steps)
f2.suptitle('Evaluation Steps')
f3, ax3 = plt.subplots()
# repeat for different algs
ax3.plot(range(0,numIter,50),eval_reward)
f3.suptitle('Evaluation Reward')
plt.show()
if __name__ == "__main__":
REINFORCECar()
#qLearningMountain()