/
ReinforcementLearning.py
84 lines (64 loc) · 2.16 KB
/
ReinforcementLearning.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
import math
def randomElement(l):
s = len(l)
return l[s*math.random()]
def maxValue(d):
n = -math.inf
for (k, v) in d:
n = max(n, v)
return n
def maxKey(d):
n = -math.inf
key = None
for (k,v) in d:
if v > n:
n = v
key = k
return key
def emptyHeuristic(states, actions):
policy = dict()
for s in states:
d = dict()
for a in actions:
d[a] = 0.0
policy[s] = d
return policy
# Solves a Problem using Reinforcement Learning
# by performing Q-Updates
class RLProblem:
# states: [States]
# actions: [Action]
# performAction: (State, Action) -> (Action, reward = Number)
def __init__(self, states, actions, performAction):
self.states = states
self.actions = actions
self.performAction = performAction
# TODO figure reward with random policy for
# choosing actions
# use Q updates
self.heuristic = emptyHeuristic(states, actions)
self.policy = dict()
for s in states:
self.policy[s] = randomElement(actions)
# The actual learning process.
# Using q Updates the policy of the agent get's further an further refined
# initialState will be chosen at random, if it's set to None (default)
def qUpdate(self, falloff, steps = 16, initialState = None):
if initialState == None:
initialState = randomElement(self.states)
state = initialState
while steps > 0:
steps -= 1
action = randomElement(self.actions)
(nextState, reward) = self.performAction(state, action)
if nextState == None:
return
self.heuristic[state][action] = falloff*reward + (1-falloff)*maxValue(self.heuristic[nextState])
state = nextState
# returns the policy aquired via reinforcement learning.
# One needs to perform various Q-Updates before receiving a policy that's
# any good. How many episodes are needed depends on the problem.
def getPolicy(self):
policy = dict()
for s in self.states:
policy[s] = maxKey(self.heuristic[s])