-
Notifications
You must be signed in to change notification settings - Fork 0
/
qlearning.py
277 lines (242 loc) · 8.36 KB
/
qlearning.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
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
from numpy import *
class QLearning:
def __init__(self, nStates, nActions):
self.network = QLearningNeuralNetwork(nStates + nActions, 20)
self.nStates = nStates
self.nActions = nActions
self.discount_factor = 0.7
self.learning_rate = 0.5
self.state = array([0] * nStates)
self.action_taken = 0
def pick_action(self, state):
self.state = array(state)
self.action_taken = 0
best_score = float('-inf')
print 'find best action'
for i in range(self.nActions):
input_array = self._get_input_array(state, i)
reward = self.network.forward(input_array)
score = reward[0][0]
print '\taction:', i, ', score:', score
if score > best_score:
self.action_taken = i
best_score = score
return self.action_taken
'''
Update Q-value according to the new state after peforming an action
'''
def update(self, new_state, immediate_reward, is_terminal=False):
new_state = array(new_state)
# get the best new qvalue
best_new_qvalue = float('-inf')
for action in range(self.nActions):
input_array = self._get_input_array(new_state, action)
new_qvalue = self.network.forward(input_array)[0][0]
best_new_qvalue = max(best_new_qvalue, new_qvalue)
# get the old qvalue
old_input_array = self._get_input_array(self.state, self.action_taken)
old_qvalue = self.network.forward(old_input_array)[0][0]
# find the update value
if is_terminal:
update_value = immediate_reward
else:
update_value = immediate_reward + self.discount_factor * best_new_qvalue
self.network.backward(old_input_array, update_value)
def _get_input_array(self, state, action):
input_array = array([0.0] * (self.nActions + self.nStates))
input_array[:self.nStates] = state
input_array[self.nStates + action] = 1
return input_array
class QLearningNeuralNetwork:
def __init__(self, nIn, nHidden):
self.nIn = nIn
self.nHidden = nHidden
self.hWeights = random.random((nHidden, nIn+1)) - 0.5 # subtract 0.5 to avoid saturation of the sigmoid
self.oWeights = random.random((1, nHidden+1)) - 0.5
self.step_size = 0.01 # arbitrarily chosen
def forward(self, example):
iOutput = zeros((self.nIn+1, 1), dtype=float)
hOutput = zeros((self.nHidden+1, 1), dtype=float)
oOutput = zeros((1), dtype=float)
hActivation = zeros((self.nHidden, 1), dtype=float)
oActivation = zeros((1, 1), dtype=float)
iOutput[:-1, 0] = example
iOutput[-1:, 0] = 1.0
hActivation = dot(self.hWeights, iOutput)
hOutput[:-1, :] = sigmoid(hActivation)
hOutput[-1:, :] = 1.0
oActivation = dot(self.oWeights, hOutput)
oOutput = linear(oActivation)
return oOutput # also known as the reward
def backward(self, example, actual):
#print 'example', example
# Below is copied from forward method
iOutput = zeros((self.nIn+1, 1), dtype=float)
hOutput = zeros((self.nHidden+1, 1), dtype=float)
oOutput = zeros((1), dtype=float)
hActivation = zeros((self.nHidden, 1), dtype=float)
oActivation = zeros((1, 1), dtype=float)
iOutput[:-1, 0] = example
iOutput[-1:, 0] = 1.0
#print 'iOutput', iOutput
hActivation = dot(self.hWeights, iOutput)
#print 'hActivation', hActivation
hOutput[:-1, :] = sigmoid(hActivation)
hOutput[-1:, :] = 1.0
oActivation = dot(self.oWeights, hOutput)
#print 'oActivation', oActivation
oOutput = linear(oActivation)
# Above is copied over from forward method
error_derivative = 2 * (oOutput - actual)
#print 'error_derivative', error_derivative
self.oDelta = error_derivative # * (1 - sigmoid(oActivation)) * sigmoid(oActivation)
self.hDelta = (1 - sigmoid(hActivation)) * sigmoid(hActivation) * dot(self.oWeights[:,:-1].transpose(), self.oDelta)
self.hWeights = self.hWeights - self.step_size * dot(self.hDelta, iOutput.transpose())
self.oWeights = self.oWeights - self.step_size * dot(self.oDelta, hOutput.transpose())
def sigmoid(x):
x[ x > 100 ] = 100
x[ x < -100 ] = -100
return 1 / (1 + exp(-x))
def linear(x):
return x
if __name__ == '__main__':
'''
nStates = 1
nActions = 3
qlearning = QLearning(nStates, nActions)
negative_reward = -10
immediate_reward = 10
# action 0 = go left (if possible)
# action 1 = go right (if possible)
# action 2 = stay
for j in range(10000):
if (j % 10 == 0): print j
# from 1, it is best to stay at 1 (action 2)
qlearning.state = array([1])
qlearning.action_taken = 2
qlearning.update([1], immediate_reward, True)
# but actions 0 and 1 are bad
qlearning.state = array([1])
qlearning.action_taken = 0
qlearning.update([0], negative_reward, True)
qlearning.state = array([1])
qlearning.action_taken = 1
qlearning.update([2], negative_reward, True)
# from 0, going to 1 is good,
qlearning.state = array([0])
qlearning.action_taken = 1
qlearning.update([1], immediate_reward, True)
# but actions 0 and 2 are bad
qlearning.state = array([0])
qlearning.action_taken = 0
qlearning.update([0], negative_reward, True)
qlearning.state = array([0])
qlearning.action_taken = 2
qlearning.update([0], negative_reward, True)
# from 2, going to 1 is good,
qlearning.state = array([2])
qlearning.action_taken = 0
qlearning.update([1], immediate_reward, True)
# but actions 1 and 2 are bad
qlearning.state = array([2])
qlearning.action_taken = 1
qlearning.update([2], negative_reward, True)
qlearning.state = array([2])
qlearning.action_taken = 2
qlearning.update([2], negative_reward, True)
for i in range(3):
print i, qlearning.pick_action([i])
distances = [ 0.1, 0.9, 1.9, 2.9]
for distance in distances:
print distance, qlearning.pick_action([distance])
'''
nStates = 1 # this is the dimension of the state actually
nActions = 3
qlearning = QLearning(nStates, nActions)
negative_reward = -3
immediate_reward = 3
for j in range(2000):
if j % 10 == 0: print j
for dist in range(100):
lower_dist = array([(dist - 1) / 200.0])
good_dist = array([dist / 200.0])
upper_dist = array([(dist + 1) / 200.0])
state = [dist / 200.0]
qlearning.state = lower_dist
qlearning.action_taken = 1
qlearning.update(state, immediate_reward, True)
qlearning.state = upper_dist
qlearning.action_taken = 0
qlearning.update(state, negative_reward, True)
qlearning.state = good_dist
qlearning.action_taken = 2
qlearning.update(state, negative_reward, True)
for dist in range(100, 110):
lower_dist = array([(dist - 1) / 200.0])
good_dist = array([dist / 200.0])
upper_dist = array([(dist + 1) / 200.0])
state = [dist / 200.0]
qlearning.state = good_dist
qlearning.action_taken = 2
qlearning.update(state, immediate_reward, True)
qlearning.state = lower_dist
qlearning.action_taken = 0
qlearning.update(state, negative_reward, True)
qlearning.state = upper_dist
qlearning.action_taken = 1
qlearning.update(state, negative_reward, True)
for dist in range(110, 200):
lower_dist = array([(dist - 1) / 200.0])
good_dist = array([dist / 200.0])
upper_dist = array([(dist + 1) / 200.0])
state = [dist / 200.0]
qlearning.state = lower_dist
qlearning.action_taken = 1
qlearning.update(state, negative_reward, True)
qlearning.state = upper_dist
qlearning.action_taken = 0
qlearning.update(state, immediate_reward, True)
qlearning.state = good_dist
qlearning.action_taken = 2
qlearning.update(state, negative_reward, True)
for i in range(200):
print i, qlearning.pick_action([i/200.0])
'''
# define training set
xorSet = [[0, 0], [0, 1], [1, 0], [1, 1]]
xorTeach = [ [0], [1.0], [-0.5], [1.75] ]
# create network
network = QLearningNeuralNetwork(2, 20)
i = 0
while(i < 60000):
i += 1
# choose one training sample at random
rnd = random.randint(0,4)
# forward and backward pass
oOutput = network.forward(xorSet[rnd])
network.backward(xorSet[rnd], xorTeach[rnd])
# output for verification
print i, xorSet[rnd], oOutput[0]
'''
'''
network = QLearningNeuralNetwork(2, 20)
for i in range(40000):
if i % 10 == 0: print 'training', i
network.backward([1,0], [10])
network.backward([0,1], [-30])
network.backward([1,1], [20])
arrays = [ [1,0], [0,1], [1,1] ]
for array in arrays:
print array, network.forward(array)
'''
'''
network = QLearningNeuralNetwork(1, 20)
for i in range(100000):
if i % 10 == 0: print 'training', i
network.backward([100 / 300.0], [100])
network.backward([200 / 300.0], [-60])
network.backward([300 / 300.0], [50])
arrays = [ [100 / 300.0], [200 / 300.0], [300 / 300.0] ]
for array in arrays:
print array, network.forward(array)
'''