forked from wboag/Obstacles
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathvalueIterationAgent.py
More file actions
executable file
·93 lines (67 loc) · 2.63 KB
/
valueIterationAgent.py
File metadata and controls
executable file
·93 lines (67 loc) · 2.63 KB
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
#
# Value Iteration
#
# Purpose: Solve MDP using value iteration
#
# Author: Willie Boag
#
from collections import defaultdict
def max0(lst):
if not lst: return 0
return max(lst)
class ValueIterationAgent:
def __init__(self, mdp, discount=0.5, iterations=5):
# parameters
self.discount = discount
# MDP
self.mdp = mdp
# values
self.values = defaultdict(lambda:0)
# Run value iteration for specified number of iterations
for _ in range(iterations):
nextVals = defaultdict(lambda:0)
# Get new value for each state
for state in self.mdp.getStates():
if self.mdp.isTerminal(state): continue
# value is maximum Q-value
nextVals[state] = max0([ self.getQValue(state,a) for a in self.mdp.getPossibleActions(state) ])
self.values = nextVals
def getValue(self, state):
"""
Return the value of the state (computed in __init__).
"""
return self.values[state]
def computeQValueFromValues(self, state, action):
"""
Compute the Q-value of action in state from the
value function stored in self.values.
"""
# Q-value is expected value you get by committing to an action & then acting optimally
qVal = 0
for sPrime,prob in self.mdp.getTransitionStatesAndProbs(state, action):
qVal += prob * (self.mdp.getReward(state,action,sPrime) + self.discount*self.getValue(sPrime))
return qVal
def computeActionFromValues(self, state):
"""
The policy is the best action in the given state
according to the values currently stored in self.values.
You may break ties any way you see fit. Note that if
there are no legal actions, which is the case at the
terminal state, you should return None.
"""
bestAction = None
maxQ = float('-inf')
#print 'state: ', state
for a in self.mdp.getPossibleActions(state):
# choose action that yields highest Q-value
qVal = self.getQValue(state, a)
if qVal > maxQ:
maxQ = qVal
bestAction = a
#print 'action: ', bestAction
return bestAction
def getAction(self, state):
"Returns the policy at the state (no exploration)."
return self.computeActionFromValues(state)
def getQValue(self, state, action):
return self.computeQValueFromValues(state, action)