-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpolicy.py
210 lines (163 loc) · 6.76 KB
/
policy.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
from __future__ import division
import numpy as np
from rl.util import *
class Policy(object):
def _set_agent(self, agent):
self.agent = agent
@property
def metrics_names(self):
return []
@property
def metrics(self):
return []
def select_action(self, **kwargs):
raise NotImplementedError()
def get_config(self):
return {}
class LinearAnnealedPolicy(Policy):
def __init__(self, inner_policy, attr, value_max, value_min, value_test, nb_steps):
if not hasattr(inner_policy, attr):
raise ValueError('Policy "{}" does not have attribute "{}".'.format(attr))
super(LinearAnnealedPolicy, self).__init__()
self.inner_policy = inner_policy
self.attr = attr
self.value_max = value_max
self.value_min = value_min
self.value_test = value_test
self.nb_steps = nb_steps
def get_current_value(self):
if self.agent.training:
# Linear annealed: f(x) = ax + b.
a = -float(self.value_max - self.value_min) / float(self.nb_steps)
b = float(self.value_max)
value = max(self.value_min, a * float(self.agent.step) + b)
else:
value = self.value_test
return value
def select_action(self, **kwargs):
setattr(self.inner_policy, self.attr, self.get_current_value())
return self.inner_policy.select_action(**kwargs)
@property
def metrics_names(self):
return ['mean_{}'.format(self.attr)]
@property
def metrics(self):
return [getattr(self.inner_policy, self.attr)]
def get_config(self):
config = super(LinearAnnealedPolicy, self).get_config()
config['attr'] = self.attr
config['value_max'] = self.value_max
config['value_min'] = self.value_min
config['value_test'] = self.value_test
config['nb_steps'] = self.nb_steps
config['inner_policy'] = get_object_config(self.inner_policy)
return config
class EpsGreedyQPolicy(Policy):
def __init__(self, eps=.1):
super(EpsGreedyQPolicy, self).__init__()
self.eps = eps
def select_action(self, q_values):
assert q_values.ndim == 1
nb_actions = q_values.shape[0]
if np.random.uniform() < self.eps:
action = np.random.random_integers(0, nb_actions-1)
else:
action = np.argmax(q_values)
return action
def get_config(self):
config = super(EpsGreedyQPolicy, self).get_config()
config['eps'] = self.eps
return config
class GreedyQPolicy(Policy):
def select_action(self, q_values):
assert q_values.ndim == 1
action = np.argmax(q_values)
return action
class BoltzmannQPolicy(Policy):
def __init__(self, tau=1., clip=(-500., 500.)):
super(BoltzmannQPolicy, self).__init__()
self.tau = tau
self.clip = clip
def select_action(self, q_values):
assert q_values.ndim == 1
q_values = q_values.astype('float64')
nb_actions = q_values.shape[0]
exp_values = np.exp(np.clip(q_values / self.tau, self.clip[0], self.clip[1]))
probs = exp_values / np.sum(exp_values)
action = np.random.choice(range(nb_actions), p=probs)
return action
def get_config(self):
config = super(BoltzmannQPolicy, self).get_config()
config['tau'] = self.tau
config['clip'] = self.clip
return config
class MaxBoltzmannQPolicy(Policy):
"""
A combination of the eps-greedy and Boltzman q-policy.
Wiering, M.: Explorations in Efficient Reinforcement Learning.
PhD thesis, University of Amserdam, Amsterdam (1999)
https://pure.uva.nl/ws/files/3153478/8461_UBA003000033.pdf
"""
def __init__(self, eps=.1, tau=1., clip=(-500., 500.)):
super(MaxBoltzmannQPolicy, self).__init__()
self.eps = eps
self.tau = tau
self.clip = clip
def select_action(self, q_values):
assert q_values.ndim == 1
q_values = q_values.astype('float64')
nb_actions = q_values.shape[0]
if np.random.uniform() < self.eps:
exp_values = np.exp(np.clip(q_values / self.tau, self.clip[0], self.clip[1]))
probs = exp_values / np.sum(exp_values)
action = np.random.choice(range(nb_actions), p=probs)
else:
action = np.argmax(q_values)
return action
def get_config(self):
config = super(MaxBoltzmannQPolicy, self).get_config()
config['eps'] = self.eps
config['tau'] = self.tau
config['clip'] = self.clip
return config
class BoltzmannGumbelQPolicy(Policy):
"""Implements Boltzmann-Gumbel exploration (BGE) adapted for Q learning
based on the paper Boltzmann Exploration Done Right
(https://arxiv.org/pdf/1705.10257.pdf).
BGE is invariant with respect to the mean of the rewards but not their
variance. The parameter C, which defaults to 1, can be used to correct for
this, and should be set to the least upper bound on the standard deviation
of the rewards.
BGE is only available for training, not testing. For testing purposes, you
can achieve approximately the same result as BGE after training for N steps
on K actions with parameter C by using the BoltzmannQPolicy and setting
tau = C/sqrt(N/K)."""
def __init__(self, C=1.0):
assert C > 0, "BoltzmannGumbelQPolicy C parameter must be > 0, not " + repr(C)
super(BoltzmannGumbelQPolicy, self).__init__()
self.C = C
self.action_counts = None
def select_action(self, q_values):
# We can't use BGE during testing, since we don't have access to the
# action_counts at the end of training.
assert self.agent.training, "BoltzmannGumbelQPolicy should only be used for training, not testing"
assert q_values.ndim == 1, q_values.ndim
q_values = q_values.astype('float64')
# If we are starting training, we should reset the action_counts.
# Otherwise, action_counts should already be initialized, since we
# always do so when we begin training.
if self.agent.step == 0:
self.action_counts = np.ones(q_values.shape)
assert self.action_counts is not None, self.agent.step
assert self.action_counts.shape == q_values.shape, (self.action_counts.shape, q_values.shape)
beta = self.C/np.sqrt(self.action_counts)
Z = np.random.gumbel(size=q_values.shape)
perturbation = beta * Z
perturbed_q_values = q_values + perturbation
action = np.argmax(perturbed_q_values)
self.action_counts[action] += 1
return action
def get_config(self):
config = super(BoltzmannGumbelQPolicy, self).get_config()
config['C'] = self.C
return config