-
Notifications
You must be signed in to change notification settings - Fork 0
/
localization.py
208 lines (159 loc) · 6.86 KB
/
localization.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
import numpy as np
import matplotlib.pyplot as plt
# Increase font size
plt.rcParams.update({'font.size': 16})
# Monte Carlo localization
def mcl(epsilon=0.1):
def run_mcl(particles, x, u):
# Move particles randomly
particles += epsilon * np.random.randn(*particles.shape) # Shape (n, m)
# Compute the loss of each particle
normalized_particles = particles - u # Shape (n, m)
loss = 0.5 * np.sum(normalized_particles * x, axis=1) ** 2 # Shape (n,)
likelihood = np.exp(-loss) # Shape (n,)
likelihood /= np.sum(likelihood) # Shape (n,)
# Resample particles
indices = np.random.choice(len(particles), len(particles), p=likelihood) # Shape (n,)
particles = particles[indices] # Shape (n, m)
return particles
return run_mcl
def C(m):
# Gamma function
return np.math.gamma(m / 2 + 1) / (m * (m - 2) * np.pi ** (m / 2))
# Our localization algorithm
def ours(gamma=0.1):
def run_ours(particles, x, u):
n = particles.shape[0]
m = particles.shape[1]
# Compute the loss of each particle
normalized_particles = particles - u # Shape (n, m)
loss = 0.5 * np.sum(normalized_particles * x, axis=1) ** 2 # Shape (n,)
# Normalized loss
loss_normed = loss - np.mean(loss) # Shape (n,)
# Gradient of loss with respect to particles
grad = np.outer(np.sum(normalized_particles * x, axis=1), x) # Shape (n, m)
# Distances
deltas = particles[:, None, :] - particles[None, :, :] # Shape (n, n, m)
distances = np.linalg.norm(deltas, axis=2) # Shape (n, n)
epsilon = (gamma / C(m)) ** (1 / (2 - m))
weights = (distances + epsilon) ** (-m)
global_update = np.sum(deltas * weights[:, :, None] * loss_normed[:, None, None], axis=1) # Shape (n, m)
# Update particles
particles -= gamma * grad / n + global_update * C(m) * (m - 2) / n
return particles
return run_ours
def KL_div(particles, u, t):
est_mean = np.mean(particles, axis=0) # Shape (m,)
est_cov = np.cov(particles, rowvar=False) # Shape (m, m)
# Add small identity to avoid division by 0
est_cov += 1e-6 * np.eye(est_cov.shape[0])
m = est_mean.shape[0]
# The other Gaussian has mean u and covariance I
KL = 0.5 * (-m * np.log(t + 1) - np.log(np.linalg.det(est_cov)) - m + np.trace(est_cov) * (t + 1)
+ np.dot(est_mean - u * (t / (t + 1)), est_mean - u * (t / (t + 1))) * (t + 1))
return KL
def test(update_fn, m=3, n=10000, iters=50):
# Random vector with m dimensions
u = np.random.randn(m) # Shape (m,)
# Sample particles
particles = np.random.randn(n, m) # Shape (n, m)
discs = []
for i in range(iters):
discrepancy = KL_div(particles, u, i)
x = np.random.randn(m) # Shape (m,)
particles = update_fn(particles, x, u)
discs.append(discrepancy)
return discs
if __name__ == '__main__':
trials = 10
epsilon = 0.1
iters = 50
ns = [20, 50, 100]
best_epsilon = 0.1
best_gamma = 0.1
# Plot 1: KL divergence over iterations
m = 10
colors = ['xkcd:light blue', 'xkcd:blue', 'xkcd:dark blue']
ls = [':', '--', '-']
for n, color, l in zip(ns, colors, ls):
discss = []
for i in range(trials):
print('n={}, trial={}'.format(n, i))
discs = test(mcl(epsilon=best_epsilon), m=m, n=n, iters=iters)
discss.append(np.asarray(discs))
discss = np.asarray(discss)
# Compute mean and standard error
mean_discs = np.mean(np.asarray(discss), axis=0)
std_discs = np.std(np.asarray(discss), axis=0) / np.sqrt(trials)
# Plot with margins
plt.plot(mean_discs, label='MCL, n={}'.format(n), color=color, linestyle=l)
plt.fill_between(range(len(discs)), mean_discs - std_discs, mean_discs + std_discs, alpha=0.2,
color=color)
colors = ['xkcd:light red', 'xkcd:red', 'xkcd:dark red']
ls = [':', '--', '-']
for n, color, l in zip(ns, colors, ls):
discss = []
for i in range(trials):
print('n={}, trial={}'.format(n, i))
discs = test(ours(gamma=best_gamma * n), m=m, n=n, iters=iters)
discss.append(np.asarray(discs))
discss = np.asarray(discss)
# Compute mean and standard error
mean_discs = np.mean(np.asarray(discss), axis=0)
std_discs = np.std(np.asarray(discss), axis=0) / np.sqrt(trials)
# Plot with margins
plt.plot(mean_discs, label='Ours, n={}'.format(n), color=color, linestyle=l)
plt.fill_between(range(len(discs)), mean_discs - std_discs, mean_discs + std_discs, alpha=0.2,
color=color)
plt.xlabel('Iteration')
plt.ylabel('KL Divergence with Posterior')
plt.tight_layout()
plt.legend()
plt.show()
# Plot 2: KL divergence over m
ms = range(3, 11)
colors = ['xkcd:light blue', 'xkcd:blue', 'xkcd:dark blue']
ls = [':', '--', '-']
for n, color, l in zip(ns, colors, ls):
discss = []
for i in range(trials):
discs = []
for m in ms:
print('n={}, m={}, trial={}'.format(n, m, i))
disc = test(mcl(epsilon=best_epsilon), m=m, n=n, iters=iters)
discs.append(disc[-1])
discss.append(np.asarray(discs))
discss = np.asarray(discss)
# Compute mean and standard error
mean_discs = np.mean(np.asarray(discss), axis=0)
std_discs = np.std(np.asarray(discss), axis=0) / np.sqrt(trials)
# Plot with margins
plt.plot(ms, mean_discs, label='MCL, n={}'.format(n), color=color, linestyle=l)
plt.fill_between(ms, mean_discs - std_discs, mean_discs + std_discs, alpha=0.2,
color=color)
colors = ['xkcd:light red', 'xkcd:red', 'xkcd:dark red']
ls = [':', '--', '-']
for n, color, l in zip(ns, colors, ls):
discss = []
for i in range(trials):
discs = []
for m in ms:
print('n={}, m={}, trial={}'.format(n, m, i))
disc = test(ours(gamma=best_gamma * n), m=m, n=n, iters=iters)
discs.append(disc[-1])
discss.append(np.asarray(discs))
discss = np.asarray(discss)
# Compute mean and standard error
mean_discs = np.mean(np.asarray(discss), axis=0)
std_discs = np.std(np.asarray(discss), axis=0) / np.sqrt(trials)
# Plot with margins
plt.plot(ms, mean_discs, label='Ours, n={}'.format(n), color=color, linestyle=l)
plt.fill_between(ms, mean_discs - std_discs, mean_discs + std_discs, alpha=0.2,
color=color)
# Log scale y axis
plt.yscale('log')
plt.xlabel('Dimensions')
plt.ylabel('KL Divergence with Posterior')
plt.tight_layout()
plt.legend()
plt.show()