-
Notifications
You must be signed in to change notification settings - Fork 9
/
mdp.py
498 lines (424 loc) · 18.6 KB
/
mdp.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
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
## Q-Learning Algorithm - This code is modified from the code contained in
## the MDP Toolbox Python package
## Source: https://github.com/sawcordwell/pymdptoolbox
"""Markov Decision Process (MDP) Toolbox: ``mdp`` module
=====================================================
The ``mdp`` module provides classes for the resolution of descrete-time Markov
Decision Processes.
Available classes
-----------------
:class:`~mdptoolbox.mdp.MDP`
Base Markov decision process class
:class:`~mdptoolbox.mdp.FiniteHorizon`
Backwards induction finite horizon MDP
:class:`~mdptoolbox.mdp.PolicyIteration`
Policy iteration MDP
:class:`~mdptoolbox.mdp.PolicyIterationModified`
Modified policy iteration MDP
:class:`~mdptoolbox.mdp.QLearning`
Q-learning MDP
:class:`~mdptoolbox.mdp.RelativeValueIteration`
Relative value iteration MDP
:class:`~mdptoolbox.mdp.ValueIteration`
Value iteration MDP
:class:`~mdptoolbox.mdp.ValueIterationGS`
Gauss-Seidel value iteration MDP
"""
# Copyright (c) 2011-2015 Steven A. W. Cordwell
# Copyright (c) 2009 INRA
#
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# * Redistributions of source code must retain the above copyright notice,
# this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright notice,
# this list of conditions and the following disclaimer in the documentation
# and/or other materials provided with the distribution.
# * Neither the name of the <ORGANIZATION> nor the names of its contributors
# may be used to endorse or promote products derived from this software
# without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
import math as _math
import time as _time
import numpy as _np
import scipy.sparse as _sp
import util as _util
_MSG_STOP_MAX_ITER = "Iterating stopped due to maximum number of iterations " \
"condition."
_MSG_STOP_EPSILON_OPTIMAL_POLICY = "Iterating stopped, epsilon-optimal " \
"policy found."
_MSG_STOP_EPSILON_OPTIMAL_VALUE = "Iterating stopped, epsilon-optimal value " \
"function found."
_MSG_STOP_UNCHANGING_POLICY = "Iterating stopped, unchanging policy found."
def _computeDimensions(transition):
A = len(transition)
try:
if transition.ndim == 3:
S = transition.shape[1]
else:
S = transition[0].shape[0]
except AttributeError:
S = transition[0].shape[0]
return S, A
def _printVerbosity(iteration, variation):
if isinstance(variation, float):
print("{:>10}{:>12f}".format(iteration, variation))
elif isinstance(variation, int):
print("{:>10}{:>12d}".format(iteration, variation))
else:
print("{:>10}{:>12}".format(iteration, variation))
class MDP(object):
"""A Markov Decision Problem.
Let ``S`` = the number of states, and ``A`` = the number of acions.
Parameters
----------
transitions : array
Transition probability matrices. These can be defined in a variety of
ways. The simplest is a numpy array that has the shape ``(A, S, S)``,
though there are other possibilities. It can be a tuple or list or
numpy object array of length ``A``, where each element contains a numpy
array or matrix that has the shape ``(S, S)``. This "list of matrices"
form is useful when the transition matrices are sparse as
``scipy.sparse.csr_matrix`` matrices can be used. In summary, each
action's transition matrix must be indexable like ``transitions[a]``
where ``a`` ∈ {0, 1...A-1}, and ``transitions[a]`` returns an ``S`` ×
``S`` array-like object.
reward : array
Reward matrices or vectors. Like the transition matrices, these can
also be defined in a variety of ways. Again the simplest is a numpy
array that has the shape ``(S, A)``, ``(S,)`` or ``(A, S, S)``. A list
of lists can be used, where each inner list has length ``S`` and the
outer list has length ``A``. A list of numpy arrays is possible where
each inner array can be of the shape ``(S,)``, ``(S, 1)``, ``(1, S)``
or ``(S, S)``. Also ``scipy.sparse.csr_matrix`` can be used instead of
numpy arrays. In addition, the outer list can be replaced by any object
that can be indexed like ``reward[a]`` such as a tuple or numpy object
array of length ``A``.
discount : float
Discount factor. The per time-step discount factor on future rewards.
Valid values are greater than 0 upto and including 1. If the discount
factor is 1, then convergence is cannot be assumed and a warning will
be displayed. Subclasses of ``MDP`` may pass ``None`` in the case where
the algorithm does not use a discount factor.
epsilon : float
Stopping criterion. The maximum change in the value function at each
iteration is compared against ``epsilon``. Once the change falls below
this value, then the value function is considered to have converged to
the optimal value function. Subclasses of ``MDP`` may pass ``None`` in
the case where the algorithm does not use an epsilon-optimal stopping
criterion.
max_iter : int
Maximum number of iterations. The algorithm will be terminated once
this many iterations have elapsed. This must be greater than 0 if
specified. Subclasses of ``MDP`` may pass ``None`` in the case where
the algorithm does not use a maximum number of iterations.
skip_check : bool
By default we run a check on the ``transitions`` and ``rewards``
arguments to make sure they describe a valid MDP. You can set this
argument to True in order to skip this check.
Attributes
----------
P : array
Transition probability matrices.
R : array
Reward vectors.
V : tuple
The optimal value function. Each element is a float corresponding to
the expected value of being in that state assuming the optimal policy
is followed.
discount : float
The discount rate on future rewards.
max_iter : int
The maximum number of iterations.
policy : tuple
The optimal policy.
time : float
The time used to converge to the optimal policy.
verbose : boolean
Whether verbose output should be displayed or not.
Methods
-------
run
Implemented in child classes as the main algorithm loop. Raises an
exception if it has not been overridden.
setSilent
Turn the verbosity off
setVerbose
Turn the verbosity on
"""
def __init__(self, transitions, reward, discount, epsilon, max_iter,
skip_check=False):
# Initialise a MDP based on the input parameters.
# if the discount is None then the algorithm is assumed to not use it
# in its computations
if discount is not None:
self.discount = float(discount)
assert 0.0 < self.discount <= 1.0, (
"Discount rate must be in ]0; 1]"
)
if self.discount == 1:
print("WARNING: check conditions of convergence. With no "
"discount, convergence can not be assumed.")
# if the max_iter is None then the algorithm is assumed to not use it
# in its computations
if max_iter is not None:
self.max_iter = int(max_iter)
assert self.max_iter > 0, (
"The maximum number of iterations must be greater than 0."
)
# check that epsilon is something sane
if epsilon is not None:
self.epsilon = float(epsilon)
assert self.epsilon > 0, "Epsilon must be greater than 0."
if not skip_check:
# We run a check on P and R to make sure they are describing an
# MDP. If an exception isn't raised then they are assumed to be
# correct.
_util.check(transitions, reward)
self.S, self.A = _computeDimensions(transitions)
self.P = self._computeTransition(transitions)
self.R = self._computeReward(reward, transitions)
# the verbosity is by default turned off
self.verbose = False
# Initially the time taken to perform the computations is set to None
self.time = None
# set the initial iteration count to zero
self.iter = 0
# V should be stored as a vector ie shape of (S,) or (1, S)
self.V = None
# policy can also be stored as a vector
self.policy = None
def __repr__(self):
P_repr = "P: \n"
R_repr = "R: \n"
for aa in range(self.A):
P_repr += repr(self.P[aa]) + "\n"
R_repr += repr(self.R[aa]) + "\n"
return(P_repr + "\n" + R_repr)
def _bellmanOperator(self, V=None):
# Apply the Bellman operator on the value function.
#
# Updates the value function and the Vprev-improving policy.
#
# Returns: (policy, value), tuple of new policy and its value
#
# If V hasn't been sent into the method, then we assume to be working
# on the objects V attribute
if V is None:
# this V should be a reference to the data rather than a copy
V = self.V
else:
# make sure the user supplied V is of the right shape
try:
assert V.shape in ((self.S,), (1, self.S)), "V is not the " \
"right shape (Bellman operator)."
except AttributeError:
raise TypeError("V must be a numpy array or matrix.")
# Looping through each action the the Q-value matrix is calculated.
# P and V can be any object that supports indexing, so it is important
# that you know they define a valid MDP before calling the
# _bellmanOperator method. Otherwise the results will be meaningless.
Q = _np.empty((self.A, self.S))
for aa in range(self.A):
Q[aa] = self.R[aa] + self.discount * self.P[aa].dot(V)
# Get the policy and value, for now it is being returned but...
# Which way is better?
# 1. Return, (policy, value)
return (Q.argmax(axis=0), Q.max(axis=0))
# 2. update self.policy and self.V directly
# self.V = Q.max(axis=1)
# self.policy = Q.argmax(axis=1)
def _computeTransition(self, transition):
return tuple(transition[a] for a in range(self.A))
def _computeReward(self, reward, transition):
# Compute the reward for the system in one state chosing an action.
# Arguments
# Let S = number of states, A = number of actions
# P could be an array with 3 dimensions or a cell array (1xA),
# each cell containing a matrix (SxS) possibly sparse
# R could be an array with 3 dimensions (SxSxA) or a cell array
# (1xA), each cell containing a sparse matrix (SxS) or a 2D
# array(SxA) possibly sparse
try:
if reward.ndim == 1:
return self._computeVectorReward(reward)
elif reward.ndim == 2:
return self._computeArrayReward(reward)
else:
r = tuple(map(self._computeMatrixReward, reward, transition))
return r
except (AttributeError, ValueError):
if len(reward) == self.A:
r = tuple(map(self._computeMatrixReward, reward, transition))
return r
else:
return self._computeVectorReward(reward)
def _computeVectorReward(self, reward):
if _sp.issparse(reward):
raise NotImplementedError
else:
r = _np.array(reward).reshape(self.S)
return tuple(r for a in range(self.A))
def _computeArrayReward(self, reward):
if _sp.issparse(reward):
raise NotImplementedError
else:
def func(x):
return _np.array(x).reshape(self.S)
return tuple(func(reward[:, a]) for a in range(self.A))
def _computeMatrixReward(self, reward, transition):
if _sp.issparse(reward):
# An approach like this might be more memory efficeint
# reward.data = reward.data * transition[reward.nonzero()]
# return reward.sum(1).A.reshape(self.S)
# but doesn't work as it is.
return reward.multiply(transition).sum(1).A.reshape(self.S)
elif _sp.issparse(transition):
return transition.multiply(reward).sum(1).A.reshape(self.S)
else:
return _np.multiply(transition, reward).sum(1).reshape(self.S)
def _startRun(self):
if self.verbose:
_printVerbosity('Iteration', 'Variation')
self.time = _time.time()
def _endRun(self):
# store value and policy as tuples
self.V = tuple(self.V.tolist())
try:
self.policy = tuple(self.policy.tolist())
except AttributeError:
self.policy = tuple(self.policy)
self.time = _time.time() - self.time
def run(self):
"""Raises error because child classes should implement this function.
"""
raise NotImplementedError("You should create a run() method.")
def setSilent(self):
"""Set the MDP algorithm to silent mode."""
self.verbose = False
def setVerbose(self):
"""Set the MDP algorithm to verbose mode."""
self.verbose = True
class QLearning(MDP):
"""A discounted MDP solved using the Q learning algorithm.
Parameters
----------
transitions : array
Transition probability matrices. See the documentation for the ``MDP``
class for details.
reward : array
Reward matrices or vectors. See the documentation for the ``MDP`` class
for details.
discount : float
Discount factor. See the documentation for the ``MDP`` class for
details.
alpha : float
Learning rate.
epsilon : float
Probability of selecting a random action.
decay : float
Epsilon decay rate.
n_iter : int, optional
Number of iterations to execute. This is ignored unless it is an
integer greater than the default value. Defaut: 10,000.
skip_check : bool
By default we run a check on the ``transitions`` and ``rewards``
arguments to make sure they describe a valid MDP. You can set this
argument to True in order to skip this check.
Data Attributes
---------------
Q : array
learned Q matrix (SxA)
V : tuple
learned value function (S).
policy : tuple
learned optimal policy (S).
mean_discrepancy : array
Vector of V discrepancy mean over 100 iterations. Then the length of
this vector for the default value of N is 100 (N/100).
"""
def __init__(self, transitions, reward, discount, alpha, epsilon = 0.5,
decay = 1.0, n_iter=10000, skip_check=False):
# Initialise a Q-learning MDP.
# The following check won't be done in MDP()'s initialisation, so let's
# do it here
self.max_iter = int(n_iter)
#assert self.max_iter >= 10000, "'n_iter' should be greater than 10000."
if not skip_check:
# We don't want to send this to MDP because _computePR should not
# be run on it, so check that it defines an MDP
_util.check(transitions, reward)
# Store P, S, and A
self.S, self.A = _computeDimensions(transitions)
self.P = self._computeTransition(transitions)
self.R = reward
self.discount = discount
self.alpha = alpha
self.epsilon = epsilon
self.decay = decay
# Initialisations
self.Q = _np.zeros((self.S, self.A))
self.mean_discrepancy = []
def run(self):
# Run the Q-learning algoritm.
discrepancy = []
self.time = _time.time()
# initial state choice
s = _np.random.randint(0, self.S)
for n in range(1, self.max_iter + 1):
# Reinitialisation of trajectories every 100 transitions
if (n % 100) == 0:
s = _np.random.randint(0, self.S)
# Action choice
pn = _np.random.random()
if pn < (1 - self.epsilon):
# optimal_action = self.Q[s, :].max()
a = self.Q[s, :].argmax()
else:
a = _np.random.randint(0, self.A)
self.epsilon *= self.decay
# Simulating next state s_new and reward associated to <s,s_new,a>
p_s_new = _np.random.random()
p = 0
s_new = -1
while (p < p_s_new) and (s_new < (self.S - 1)):
s_new = s_new + 1
p = p + self.P[a][s, s_new]
try:
r = self.R[a][s, s_new]
except IndexError:
try:
r = self.R[s, a]
except IndexError:
r = self.R[s]
# Updating the value of Q
# Decaying update coefficient (1/sqrt(n+2)) can be changed
delta = r + self.discount * self.Q[s_new, :].max() - self.Q[s, a]
dQ = self.alpha * delta
self.Q[s, a] = self.Q[s, a] + dQ
# current state is updated
s = s_new
# Computing and saving maximal values of the Q variation
discrepancy.append(_np.absolute(dQ))
# Computing means all over maximal Q variations values
if len(discrepancy) == 1000:
self.mean_discrepancy.append(_np.mean(discrepancy))
discrepancy = []
# compute the value function and the policy
self.V = self.Q.max(axis=1)
self.policy = self.Q.argmax(axis=1)
self._endRun()