Debian Codegraph @

ot/gmm.py

raw symbols SCIP
1 # -*- coding: utf-8 -*-
2 """
3 Optimal transport for Gaussian Mixtures
4 """
5
6 # Author: Eloi Tanguy <eloi.tanguy@u-paris>
7 # Remi Flamary <[email protected]>
8 # Julie Delon <[email protected]>
9 #
10 # License: MIT License
11
12 from .backend import get_backend
13 from .lp import emd2, emd
14 import numpy as np
15 from .lp import dist
16 from .gaussian import bures_wasserstein_mapping
17
18
19 def gaussian_pdf(x, m, C):
20 r"""
21 Compute the probability density function of a multivariate
22 Gaussian distribution.
23
24 Parameters
25 ----------
26 x : array-like, shape (..., d)
27 The input samples.
28 m : array-like, shape (d,)
29 The mean vector of the Gaussian distribution.
30 C : array-like, shape (d, d)
31 The covariance matrix of the Gaussian distribution.
32
33 Returns
34 -------
35 pdf : array-like, shape (...,)
36 The probability density function evaluated at each sample.
37
38 """
39 assert (
40 x.shape[-1] == m.shape[-1] == C.shape[-1] == C.shape[-2]
41 ), "Dimension mismatch"
42 nx = get_backend(x, m, C)
43 d = x.shape[-1]
44 z = (2 * np.pi) ** (-d / 2) * nx.det(C) ** (-0.5)
45 exp = nx.exp(-0.5 * nx.sum(((x - m) @ nx.inv(C)) * (x - m), axis=-1))
46 return z * exp
47
48
49 def gmm_pdf(x, m, C, w):
50 r"""
51 Compute the probability density function (PDF) of a
52 Gaussian Mixture Model (GMM) at given points.
53
54 Parameters
55 ----------
56 x : array-like, shape (..., d)
57 The input samples.
58 m : array-like, shape (n_components, d)
59 The means of the Gaussian components.
60 C : array-like, shape (n_components, d, d)
61 The covariance matrices of the Gaussian components.
62 w : array-like, shape (n_components,)
63 The weights of the Gaussian components.
64
65 Returns
66 -------
67 out : array-like, shape (...,)
68 The PDF values at the given points.
69
70 """
71 assert (
72 m.shape[0] == C.shape[0] == w.shape[0]
73 ), "All GMM parameters must have the same amount of components"
74 nx = get_backend(x, m, C, w)
75 out = nx.zeros((x.shape[:-1]))
76 for k in range(m.shape[0]):
77 out = out + w[k] * gaussian_pdf(x, m[k], C[k])
78 return out
79
80
81 def dist_bures_squared(m_s, m_t, C_s, C_t):
82 r"""
83 Compute the matrix of the squared Bures distances between the components of
84 two Gaussian Mixture Models (GMMs). Used to compute the GMM Optimal
85 Transport distance [69].
86
87 Parameters
88 ----------
89 m_s : array-like, shape (k_s, d)
90 Mean vectors of the source GMM.
91 m_t : array-like, shape (k_t, d)
92 Mean vectors of the target GMM.
93 C_s : array-like, shape (k_s, d, d)
94 Covariance matrices of the source GMM.
95 C_t : array-like, shape (k_t, d, d)
96 Covariance matrices of the target GMM.
97
98 Returns
99 -------
100 dist : array-like, shape (k_s, k_t)
101 Matrix of squared Bures distances between the components of the source
102 and target GMMs.
103
104 References
105 ----------
106 .. [69] Delon, J., & Desolneux, A. (2020). A Wasserstein-type distance in the space of Gaussian mixture models. SIAM Journal on Imaging Sciences, 13(2), 936-970.
107
108 """
109 nx = get_backend(m_s, C_s, m_t, C_t)
110
111 assert m_s.shape[0] == C_s.shape[0], "Source GMM has different amount of components"
112
113 assert m_t.shape[0] == C_t.shape[0], "Target GMM has different amount of components"
114
115 assert (
116 m_s.shape[-1] == m_t.shape[-1] == C_s.shape[-1] == C_t.shape[-1]
117 ), "All GMMs must have the same dimension"
118
119 D_means = dist(m_s, m_t, metric="sqeuclidean")
120
121 # C2[i, j] = Cs12[i] @ C_t[j] @ Cs12[i], shape (k_s, k_t, d, d)
122 Cs12 = nx.sqrtm(C_s) # broadcasts matrix sqrt over (k_s,)
123 C2 = nx.einsum("ikl,jlm,imn->ijkn", Cs12, C_t, Cs12)
124 C = nx.sqrtm(C2) # broadcasts matrix sqrt over (k_s, k_t)
125
126 # D_covs[i,j] = trace(C_s[i] + C_t[j] - 2C[i,j])
127 trace_C_s = nx.einsum("ikk->i", C_s)[:, None] # (k_s, 1)
128 trace_C_t = nx.einsum("ikk->i", C_t)[None, :] # (1, k_t)
129 D_covs = trace_C_s + trace_C_t # broadcasts to (k_s, k_t)
130 D_covs -= 2 * nx.einsum("ijkk->ij", C)
131
132 return nx.maximum(D_means + D_covs, 0)
133
134
135 def gmm_ot_loss(m_s, m_t, C_s, C_t, w_s, w_t, log=False):
136 r"""
137 Compute the Gaussian Mixture Model (GMM) Optimal Transport distance between
138 two GMMs introduced in [69].
139
140 Parameters
141 ----------
142 m_s : array-like, shape (k_s, d)
143 Mean vectors of the source GMM.
144 m_t : array-like, shape (k_t, d)
145 Mean vectors of the target GMM.
146 C_s : array-like, shape (k_s, d, d)
147 Covariance matrices of the source GMM.
148 C_t : array-like, shape (k_t, d, d)
149 Covariance matrices of the target GMM.
150 w_s : array-like, shape (k_s,)
151 Weights of the source GMM components.
152 w_t : array-like, shape (k_t,)
153 Weights of the target GMM components.
154 log: bool, optional (default=False)
155 If True, returns a dictionary containing the cost and dual variables.
156 Otherwise returns only the GMM optimal transportation cost.
157
158 Returns
159 -------
160 loss : float or array-like
161 The GMM-OT loss.
162 log : dict, optional
163 If input log is true, a dictionary containing the
164 cost and dual variables and exit status
165
166 References
167 ----------
168 .. [69] Delon, J., & Desolneux, A. (2020). A Wasserstein-type distance in the space of Gaussian mixture models. SIAM Journal on Imaging Sciences, 13(2), 936-970.
169
170 """
171 get_backend(m_s, C_s, w_s, m_t, C_t, w_t)
172
173 assert m_s.shape[0] == w_s.shape[0], "Source GMM has different amount of components"
174
175 assert m_t.shape[0] == w_t.shape[0], "Target GMM has different amount of components"
176
177 D = dist_bures_squared(m_s, m_t, C_s, C_t)
178 return emd2(w_s, w_t, D, log=log)
179
180
181 def gmm_ot_plan(m_s, m_t, C_s, C_t, w_s, w_t, log=False):
182 r"""
183 Compute the Gaussian Mixture Model (GMM) Optimal Transport plan between
184 two GMMs introduced in [69].
185
186 Parameters
187 ----------
188 m_s : array-like, shape (k_s, d)
189 Mean vectors of the source GMM.
190 m_t : array-like, shape (k_t, d)
191 Mean vectors of the target GMM.
192 C_s : array-like, shape (k_s, d, d)
193 Covariance matrices of the source GMM.
194 C_t : array-like, shape (k_t, d, d)
195 Covariance matrices of the target GMM.
196 w_s : array-like, shape (k_s,)
197 Weights of the source GMM components.
198 w_t : array-like, shape (k_t,)
199 Weights of the target GMM components.
200 log : bool, optional (default=False)
201 If True, returns a dictionary containing the cost and dual variables.
202 Otherwise returns only the GMM optimal transportation matrix.
203
204 Returns
205 -------
206 plan : array-like, shape (k_s, k_t)
207 The GMM-OT plan.
208 log : dict, optional
209 If input log is true, a dictionary containing the
210 cost and dual variables and exit status
211
212 References
213 ----------
214 .. [69] Delon, J., & Desolneux, A. (2020). A Wasserstein-type distance in the space of Gaussian mixture models. SIAM Journal on Imaging Sciences, 13(2), 936-970.
215
216 """
217 get_backend(m_s, C_s, w_s, m_t, C_t, w_t)
218
219 assert m_s.shape[0] == w_s.shape[0], "Source GMM has different amount of components"
220
221 assert m_t.shape[0] == w_t.shape[0], "Target GMM has different amount of components"
222
223 D = dist_bures_squared(m_s, m_t, C_s, C_t)
224 return emd(w_s, w_t, D, log=log)
225
226
227 def gmm_ot_apply_map(
228 x, m_s, m_t, C_s, C_t, w_s, w_t, plan=None, method="bary", seed=None
229 ):
230 r"""
231 Apply Gaussian Mixture Model (GMM) optimal transport (OT) mapping to input
232 data. The 'barycentric' mapping corresponds to the barycentric projection
233 of the GMM-OT plan, and is called T_bary in [69]. The 'random' mapping takes
234 for each input point a random pair (i,j) of components of the GMMs and
235 applied the Gaussian map, it is called T_rand in [69].
236
237 Parameters
238 ----------
239 x : array-like, shape (n_samples, d)
240 Input data points.
241 m_s : array-like, shape (k_s, d)
242 Mean vectors of the source GMM components.
243 m_t : array-like, shape (k_t, d)
244 Mean vectors of the target GMM components.
245 C_s : array-like, shape (k_s, d, d)
246 Covariance matrices of the source GMM components.
247 C_t : array-like, shape (k_t, d, d)
248 Covariance matrices of the target GMM components.
249 w_s : array-like, shape (k_s,)
250 Weights of the source GMM components.
251 w_t : array-like, shape (k_t,)
252 Weights of the target GMM components.
253 plan : array-like, shape (k_s, k_t), optional
254 Optimal transport plan between the source and target GMM components.
255 If not provided, it will be computed internally.
256 method : {'bary', 'rand'}, optional
257 Method for applying the GMM OT mapping. 'bary' uses barycentric mapping,
258 while 'rand' uses random sampling. Default is 'bary'.
259 seed : int, optional
260 Seed for the random number generator. Only used when method='rand'.
261
262 Returns
263 -------
264 out : array-like, shape (n_samples, d)
265 Output data points after applying the GMM OT mapping.
266
267 References
268 ----------
269 .. [69] Delon, J., & Desolneux, A. (2020). A Wasserstein-type distance in the space of Gaussian mixture models. SIAM Journal on Imaging Sciences, 13(2), 936-970.
270
271 """
272
273 if plan is None:
274 plan = gmm_ot_plan(m_s, m_t, C_s, C_t, w_s, w_t)
275 nx = get_backend(x, m_s, m_t, C_s, C_t, w_s, w_t)
276 else:
277 nx = get_backend(x, m_s, m_t, C_s, C_t, w_s, w_t, plan)
278
279 k_s, k_t = m_s.shape[0], m_t.shape[0]
280 d = m_s.shape[1]
281 n_samples = x.shape[0]
282
283 if method == "bary":
284 normalization = gmm_pdf(x, m_s, C_s, w_s)[:, None]
285 out = nx.zeros(x.shape)
286 print("where plan > 0", nx.where(plan > 0))
287
288 # only need to compute for non-zero plan entries
289 for i, j in zip(*nx.where(plan > 0)):
290 Cs12 = nx.sqrtm(C_s[i])
291 Cs12inv = nx.inv(Cs12)
292 g = gaussian_pdf(x, m_s[i], C_s[i])[:, None]
293
294 M0 = nx.sqrtm(Cs12 @ C_t[j] @ Cs12)
295 A = Cs12inv @ M0 @ Cs12inv
296 b = m_t[j] - A @ m_s[i]
297
298 # gaussian mapping between components i and j applied to x
299 T_ij_x = x @ A + b
300 out = out + plan[i, j] * g * T_ij_x
301
302 return out / normalization
303
304 else: # rand
305 # A[i, j] is the linear part of the gaussian mapping between components
306 # i and j, b[i, j] is the translation part
307 rng = np.random.RandomState(seed)
308
309 A = nx.zeros((k_s, k_t, d, d))
310 b = nx.zeros((k_s, k_t, d))
311
312 # only need to compute for non-zero plan entries
313 for i, j in zip(*nx.where(plan > 0)):
314 Cs12 = nx.sqrtm(C_s[i])
315 Cs12inv = nx.inv(Cs12)
316
317 M0 = nx.sqrtm(Cs12 @ C_t[j] @ Cs12)
318 A[i, j] = Cs12inv @ M0 @ Cs12inv
319 b[i, j] = m_t[j] - A[i, j] @ m_s[i]
320
321 normalization = gmm_pdf(x, m_s, C_s, w_s) # (n_samples,)
322 gs = np.stack([gaussian_pdf(x, m_s[i], C_s[i]) for i in range(k_s)], axis=-1)
323 # (n_samples, k_s)
324 out = nx.zeros(x.shape)
325
326 for i_sample in range(n_samples):
327 p_mat = plan * gs[i_sample][:, None] / normalization[i_sample]
328 p = p_mat.reshape(k_s * k_t) # stack line-by-line
329 # sample between 0 and k_s * k_t - 1
330 ij_mat = rng.choice(k_s * k_t, p=p)
331 i = ij_mat // k_t
332 j = ij_mat % k_t
333 out[i_sample] = A[i, j] @ x[i_sample] + b[i, j]
334
335 return out
336
337
338 def gmm_ot_plan_density(x, y, m_s, m_t, C_s, C_t, w_s, w_t, plan=None, atol=1e-2):
339 """
340 Compute the density of the Gaussian Mixture Model - Optimal Transport
341 coupling between GMMS at given points, as introduced in [69].
342 Given two arrays of points x and y, the function computes the density at
343 each point `(x[i], y[i])` of the product space.
344
345 Parameters
346 ----------
347 x : array-like, shape (n, d)
348 Entry points in source space for density computation.
349 y : array-like, shape (m, d)
350 Entry points in target space for density computation.
351 m_s : array-like, shape (k_s, d)
352 The means of the source GMM components.
353 m_t : array-like, shape (k_t, d)
354 The means of the target GMM components.
355 C_s : array-like, shape (k_s, d, d)
356 The covariance matrices of the source GMM components.
357 C_t : array-like, shape (k_t, d, d)
358 The covariance matrices of the target GMM components.
359 w_s : array-like, shape (k_s,)
360 The weights of the source GMM components.
361 w_t : array-like, shape (k_t,)
362 The weights of the target GMM components.
363 plan : array-like, shape (k_s, k_t), optional
364 The optimal transport plan between the source and target GMMs.
365 If not provided, it will be computed using `gmm_ot_plan`.
366 atol : float, optional
367 The absolute tolerance used to determine the support of the GMM-OT
368 coupling.
369
370 Returns
371 -------
372 density : array-like, shape (n, m)
373 The density of the GMM-OT coupling between the two GMMs.
374
375 References
376 ----------
377 .. [69] Delon, J., & Desolneux, A. (2020). A Wasserstein-type distance in the space of Gaussian mixture models. SIAM Journal on Imaging Sciences, 13(2), 936-970.
378
379 """
380 assert (
381 x.shape[-1] == y.shape[-1]
382 ), "x (n, d) and y (m, d) must have the same dimension d"
383 n, m = x.shape[0], y.shape[0]
384 nx = get_backend(x, y, m_s, m_t, C_s, C_t, w_s, w_t)
385
386 # hand-made d-variate meshgrid in ij indexing
387 xx = x[:, None, :] * nx.ones((1, m, 1)) # shapes (n, m, d)
388 yy = y[None, :, :] * nx.ones((n, 1, 1)) # shapes (n, m, d)
389
390 if plan is None:
391 plan = gmm_ot_plan(m_s, m_t, C_s, C_t, w_s, w_t)
392
393 def Tk0k1(k0, k1):
394 A, b = bures_wasserstein_mapping(m_s[k0], m_t[k1], C_s[k0], C_t[k1])
395 Tx = xx @ A + b
396 g = gaussian_pdf(xx, m_s[k0], C_s[k0])
397 out = plan[k0, k1] * g
398 norms = nx.norm(Tx - yy, axis=-1)
399 out = out * ((norms < atol) * 1.0)
400 return out
401
402 mat = nx.stack(
403 [
404 nx.stack([Tk0k1(k0, k1) for k1 in range(m_t.shape[0])])
405 for k0 in range(m_s.shape[0])
406 ]
407 )
408 return nx.sum(mat, axis=(0, 1))