-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmdp.py
191 lines (156 loc) · 5.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
import random
import numpy as np
class MOMDP(object):
def __init__(self, S, A, H, d):
super(MOMDP, self).__init__()
self.S = S
self.A = A
self.H = H
self.d = d
self.transit = None
self.rewards = None
self._init_transit("uniform")
self._init_rewards("random")
def _init_transit(self, dist=None):
# (x,a,y)
if dist == "uniform":
self.transit = np.random.rand(self.S, self.A, self.S)
self.transit /= np.sum(self.transit, axis=(2), keepdims=True)
def _init_rewards(self, dist=None):
# (d, H, S, A)
if dist == "random":
self.rewards = np.random.rand(self.d, self.H, self.S, self.A)
def get_reward(self):
# (H, S, A)
pref = np.random.rand(self.d)
pref /= np.sum(pref)
return np.sum(self.rewards * np.reshape(pref, (self.d, 1, 1, 1)), axis=0)
def play(self, reward, policy):
# reward: (H, S, A)
# policy: (H, S, A)
trajectory = []
x = 0
V = 0
for h in range(self.H):
a = np.random.choice(self.A, p=policy[h, x, :])
y = np.random.choice(self.S, p=self.transit[x,a,:])
V += reward[h, x, a]
trajectory.append( (x,a,y) )
x = y
return V, trajectory
def _get_rand_policy(self):
pi = np.random.rand(self.H, self.S, self.A)
pi /= np.sum(pi, axis=1, keepdims=True)
return pi
def _get_V_pi(self, reward, policy):
# reward: (H, S, A)
# policy: (H, S, A)
p_x = np.zeros(self.S)
p_x[0] = 1
V = 0
for h in range(self.H):
p_xa = policy[h] * p_x.reshape((self.S, 1)) # (S, A)
p_y = np.sum(p_xa.reshape((self.S, self.A, 1)) * self.transit, axis=(0,1))
V += np.sum(p_xa * reward[h])
p_x = np.copy(p_y)
# print(p_y.shape, p_y.sum())
return V
def _get_V_opt(self, reward):
# reward: (H, S, A)
V = np.zeros(self.S)
pi = np.zeros((self.H, self.S, self.A))
for h in np.arange(self.H-1, -1, -1):
Q = reward[h] + np.sum(self.transit * V.reshape((1, 1, self.S)), axis=2)
V = np.amax(Q, axis=1)
pi[h] = np.eye(self.A)[np.argmax(Q, axis=1)]
return V[0], pi
def regret_opt_stationary_policy(self, Rs):
r_bar = np.zeros((self.H, self.S, self.A))
for R in Rs:
r_bar += R
r_bar /= len(Rs)
_, pi = self._get_V_opt(r_bar)
regret = 0
regrets = [0]
for R in Rs:
V_opt, _ = self._get_V_opt(R)
V_pi = self._get_V_pi(R, pi)
regret += (V_opt - V_pi)
regrets.append(regret)
return regrets
def regret(self, Rs, Pis):
regret = 0
regrets = [0]
for (R, Pi) in zip(Rs, Pis):
V_opt, _ = self._get_V_opt(R)
V_pi = self._get_V_pi(R, Pi)
regret += (V_opt - V_pi)
regrets.append(regret)
return regrets
class MOUCBVI(object):
def __init__(self, momdp):
super(MOUCBVI, self).__init__()
self.momdp = momdp
self.S = self.momdp.S
self.A = self.momdp.A
self.H = self.momdp.H
self.d = self.momdp.d
# self.rewards = self.momdp.rewards
self.histogram = np.ones((self.S, self.A, self.S)) # (S, A, S) # initialize to 1 to avoid boundary cases
def update_history(self, episode_trajectory):
for (x,a,y) in episode_trajectory:
self.histogram[x,a,y] += 1
def get_empi_transit(self):
# (S, A, S)
empi_transit = np.copy(self.histogram)
empi_transit /= np.sum(empi_transit, axis=2, keepdims=True)
return empi_transit
def get_bonus(self, coeff=1.0):
# (S, A)
bonus = np.sqrt( np.minimum(self.d, self.S) * self.H **2 / np.sum(self.histogram, axis=2))
return bonus * coeff
def get_Q_table(self, reward, coeff=1.0):
# reward: (H, S, A)
bonus = self.get_bonus(coeff) # (S, A)
empi_transit = self.get_empi_transit() # (S, A, S)
pi = np.zeros((self.H, self.S, self.A))
Q = np.zeros((self.H, self.S, self.A))
V = np.zeros(self.S)
for h in np.arange(self.H-1, -1, -1):
Q[h] = reward[h] + bonus + np.sum(empi_transit * V.reshape((1, 1, self.S)), axis=2)
Q[h] = np.minimum(Q[h], self.H)
V = np.amax(Q[h], axis=1)
pi[h] = np.eye(self.A)[np.argmax(Q[h], axis=1)]
return Q, pi
def online_game(self, K, coeff=1.0):
Rs = []
Pis = []
for _ in range(K):
reward = self.momdp.get_reward()
_, policy = self.get_Q_table(reward, coeff)
_, trajectory = self.momdp.play(reward, policy)
self.update_history(trajectory)
Rs.append(np.copy(reward))
Pis.append(np.copy(policy))
return Rs, Pis
if __name__ == '__main__':
S = 20
A = 5
H = 10
d = 15
K = 5000
momdp = MOMDP(S, A, H, d)
moucbvi = MOUCBVI(momdp)
Rs, Pis = moucbvi.online_game(K, coeff=0.1)
regrets = momdp.regret(Rs, Pis)
regrets_stay = momdp.regret_opt_stationary_policy(Rs)
print(regrets[-10:])
print(regrets_stay[-10:])
import numpy as np
import matplotlib.pyplot as plt
plt.plot(range(K+1), regrets, "-r")
plt.plot(range(K+1), regrets_stay, "--b")
plt.xlabel("number of episodes", fontsize=15)
plt.ylabel("total regret", fontsize=15)
plt.legend(["MO-UCBVI", "Best stationary policy"], fontsize=15)
plt.savefig("regret.pdf")