Debian Codegraph @

ot/dr.py

raw symbols SCIP
1 # -*- coding: utf-8 -*-
2 """
3 Dimension reduction with OT
4
5
6 .. warning::
7 Note that by default the module is not imported in :mod:`ot`. In order to
8 use it you need to explicitly import :mod:`ot.dr`
9
10 """
11
12 # Author: Remi Flamary <[email protected]>
13 # Minhui Huang <[email protected]>
14 # Jakub Zadrozny <[email protected]>
15 # Antoine Collas <[email protected]>
16 #
17 # License: MIT License
18
19 from scipy import linalg
20
21 try:
22 import autograd.numpy as np
23 from sklearn.decomposition import PCA
24
25 import pymanopt
26 import pymanopt.manifolds
27 import pymanopt.optimizers
28 except ImportError:
29 raise ImportError(
30 "Missing dependency for ot.dr. Requires autograd, pymanopt, scikit-learn. You can install with install with 'pip install POT[dr]', or 'conda install autograd pymanopt scikit-learn'"
31 )
32
33 from .bregman import sinkhorn as sinkhorn_bregman
34 from .utils import dist as dist_utils, check_random_state
35
36
37 def dist(x1, x2):
38 r"""Compute squared euclidean distance between samples (autograd)"""
39 x1p2 = np.sum(np.square(x1), 1)
40 x2p2 = np.sum(np.square(x2), 1)
41 return x1p2.reshape((-1, 1)) + x2p2.reshape((1, -1)) - 2 * np.dot(x1, x2.T)
42
43
44 def sinkhorn(w1, w2, M, reg, k):
45 r"""Sinkhorn algorithm with fixed number of iteration (autograd)"""
46 K = np.exp(-M / reg)
47 ui = np.ones((M.shape[0],))
48 vi = np.ones((M.shape[1],))
49 for i in range(k):
50 vi = w2 / (np.dot(K.T, ui) + 1e-50)
51 ui = w1 / (np.dot(K, vi) + 1e-50)
52 G = ui.reshape((M.shape[0], 1)) * K * vi.reshape((1, M.shape[1]))
53 return G
54
55
56 def logsumexp(M, axis):
57 r"""Log-sum-exp reduction compatible with autograd (no numpy implementation)"""
58 amax = np.amax(M, axis=axis, keepdims=True)
59 return np.log(np.sum(np.exp(M - amax), axis=axis)) + np.squeeze(amax, axis=axis)
60
61
62 def sinkhorn_log(w1, w2, M, reg, k):
63 r"""Sinkhorn algorithm in log-domain with fixed number of iteration (autograd)"""
64 Mr = -M / reg
65 ui = np.zeros((M.shape[0],))
66 vi = np.zeros((M.shape[1],))
67 log_w1 = np.log(w1)
68 log_w2 = np.log(w2)
69 for i in range(k):
70 vi = log_w2 - logsumexp(Mr + ui[:, None], 0)
71 ui = log_w1 - logsumexp(Mr + vi[None, :], 1)
72 G = np.exp(ui[:, None] + Mr + vi[None, :])
73 return G
74
75
76 def split_classes(X, y):
77 r"""split samples in :math:`\mathbf{X}` by classes in :math:`\mathbf{y}`"""
78 lstsclass = np.unique(y)
79 return [X[y == i, :].astype(np.float32) for i in lstsclass]
80
81
82 def fda(X, y, p=2, reg=1e-16):
83 r"""Fisher Discriminant Analysis
84
85 Parameters
86 ----------
87 X : ndarray, shape (n, d)
88 Training samples.
89 y : ndarray, shape (n,)
90 Labels for training samples.
91 p : int, optional
92 Size of dimensionality reduction.
93 reg : float, optional
94 Regularization term >0 (ridge regularization)
95
96 Returns
97 -------
98 P : ndarray, shape (d, p)
99 Optimal transportation matrix for the given parameters
100 proj : callable
101 projection function including mean centering
102 """
103
104 mx = np.mean(X)
105 X -= mx.reshape((1, -1))
106
107 # data split between classes
108 d = X.shape[1]
109 xc = split_classes(X, y)
110 nc = len(xc)
111
112 p = min(nc - 1, p)
113
114 Cw = 0
115 for x in xc:
116 Cw += np.cov(x, rowvar=False)
117 Cw /= nc
118
119 mxc = np.zeros((d, nc))
120
121 for i in range(nc):
122 mxc[:, i] = np.mean(xc[i])
123
124 mx0 = np.mean(mxc, 1)
125 Cb = 0
126 for i in range(nc):
127 Cb += (mxc[:, i] - mx0).reshape((-1, 1)) * (mxc[:, i] - mx0).reshape((1, -1))
128
129 w, V = linalg.eig(Cb, Cw + reg * np.eye(d))
130
131 idx = np.argsort(w.real)
132
133 Popt = V[:, idx[-p:]]
134
135 def proj(X):
136 return (X - mx.reshape((1, -1))).dot(Popt)
137
138 return Popt, proj
139
140
141 def wda(
142 X,
143 y,
144 p=2,
145 reg=1,
146 k=10,
147 solver=None,
148 sinkhorn_method="sinkhorn",
149 maxiter=100,
150 verbose=0,
151 P0=None,
152 normalize=False,
153 ):
154 r"""
155 Wasserstein Discriminant Analysis :ref:`[11] <references-wda>`
156
157 The function solves the following optimization problem:
158
159 .. math::
160 \mathbf{P} = \mathop{\arg \min}_\mathbf{P} \quad
161 \frac{\sum\limits_i W(P \mathbf{X}^i, P \mathbf{X}^i)}{\sum\limits_{i, j \neq i} W(P \mathbf{X}^i, P \mathbf{X}^j)}
162
163 where :
164
165 - :math:`P` is a linear projection operator in the Stiefel(`p`, `d`) manifold
166 - :math:`W` is entropic regularized Wasserstein distances
167 - :math:`\mathbf{X}^i` are samples in the dataset corresponding to class i
168
169 **Choosing a Sinkhorn solver**
170
171 By default and when using a regularization parameter that is not too small
172 the default sinkhorn solver should be enough. If you need to use a small
173 regularization to get sparse cost matrices, you should use the
174 :py:func:`ot.dr.sinkhorn_log` solver that will avoid numerical
175 errors, but can be slow in practice.
176
177 Parameters
178 ----------
179 X : ndarray, shape (n, d)
180 Training samples.
181 y : ndarray, shape (n,)
182 Labels for training samples.
183 p : int, optional
184 Size of dimensionality reduction.
185 reg : float, optional
186 Regularization term >0 (entropic regularization)
187 solver : None | str, optional
188 None for steepest descent or 'TrustRegions' for trust regions algorithm
189 else should be a pymanopt.solvers
190 sinkhorn_method : str
191 method used for the Sinkhorn solver, either 'sinkhorn' or 'sinkhorn_log'
192 P0 : ndarray, shape (d, p)
193 Initial starting point for projection.
194 normalize : bool, optional
195 Normalize the Wasserstaiun distance by the average distance on P0 (default : False)
196 verbose : int, optional
197 Print information along iterations.
198
199 Returns
200 -------
201 P : ndarray, shape (d, p)
202 Optimal transportation matrix for the given parameters
203 proj : callable
204 Projection function including mean centering.
205
206
207 .. _references-wda:
208 References
209 ----------
210 .. [11] Flamary, R., Cuturi, M., Courty, N., & Rakotomamonjy, A. (2016).
211 Wasserstein Discriminant Analysis. arXiv preprint arXiv:1608.08063.
212 """ # noqa
213
214 if sinkhorn_method.lower() == "sinkhorn":
215 sinkhorn_solver = sinkhorn
216 elif sinkhorn_method.lower() == "sinkhorn_log":
217 sinkhorn_solver = sinkhorn_log
218 else:
219 raise ValueError("Unknown Sinkhorn method '%s'." % sinkhorn_method)
220
221 mx = np.mean(X)
222 X -= mx.reshape((1, -1))
223
224 # data split between classes
225 d = X.shape[1]
226 xc = split_classes(X, y)
227 # compute uniform weighs
228 wc = [np.ones((x.shape[0]), dtype=np.float32) / x.shape[0] for x in xc]
229
230 # pre-compute reg_c,c'
231 if P0 is not None and normalize:
232 regmean = np.zeros((len(xc), len(xc)))
233 for i, xi in enumerate(xc):
234 xi = np.dot(xi, P0)
235 for j, xj in enumerate(xc[i:]):
236 xj = np.dot(xj, P0)
237 M = dist(xi, xj)
238 regmean[i, j] = np.sum(M) / (len(xi) * len(xj))
239 else:
240 regmean = np.ones((len(xc), len(xc)))
241
242 manifold = pymanopt.manifolds.Stiefel(d, p)
243
244 @pymanopt.function.autograd(manifold)
245 def cost(P):
246 # wda loss
247 loss_b = 0
248 loss_w = 0
249
250 for i, xi in enumerate(xc):
251 xi = np.dot(xi, P)
252 for j, xj in enumerate(xc[i:]):
253 xj = np.dot(xj, P)
254 M = dist(xi, xj)
255 G = sinkhorn_solver(wc[i], wc[j + i], M, reg * regmean[i, j], k)
256 if j == 0:
257 loss_w += np.sum(G * M)
258 else:
259 loss_b += np.sum(G * M)
260
261 # loss inversed because minimization
262 return loss_w / loss_b
263
264 # declare manifold and problem
265
266 problem = pymanopt.Problem(manifold=manifold, cost=cost)
267
268 # declare solver and solve
269 if solver is None:
270 solver = pymanopt.optimizers.SteepestDescent(
271 max_iterations=maxiter, log_verbosity=verbose
272 )
273 elif solver in ["tr", "TrustRegions"]:
274 solver = pymanopt.optimizers.TrustRegions(
275 max_iterations=maxiter, log_verbosity=verbose
276 )
277
278 Popt = solver.run(problem, initial_point=P0)
279
280 def proj(X):
281 return (X - mx.reshape((1, -1))).dot(Popt.point)
282
283 return Popt.point, proj
284
285
286 def projection_robust_wasserstein(
287 X,
288 Y,
289 a,
290 b,
291 tau,
292 U0=None,
293 reg=0.1,
294 k=2,
295 stopThr=1e-3,
296 maxiter=100,
297 verbose=0,
298 random_state=None,
299 ):
300 r"""
301 Projection Robust Wasserstein Distance :ref:`[32] <references-projection-robust-wasserstein>`
302
303 The function solves the following optimization problem:
304
305 .. math::
306 \max_{U \in St(d, k)} \ \min_{\pi \in \Pi(\mu,\nu)} \quad \sum_{i,j} \pi_{i,j}
307 \|U^T(\mathbf{x}_i - \mathbf{y}_j)\|^2 - \mathrm{reg} \cdot H(\pi)
308
309 - :math:`U` is a linear projection operator in the Stiefel(`d`, `k`) manifold
310 - :math:`H(\pi)` is entropy regularizer
311 - :math:`\mathbf{x}_i`, :math:`\mathbf{y}_j` are samples of measures :math:`\mu` and :math:`\nu` respectively
312
313 Parameters
314 ----------
315 X : ndarray, shape (n, d)
316 Samples from measure :math:`\mu`
317 Y : ndarray, shape (n, d)
318 Samples from measure :math:`\nu`
319 a : ndarray, shape (n, )
320 weights for measure :math:`\mu`
321 b : ndarray, shape (n, )
322 weights for measure :math:`\nu`
323 tau : float
324 stepsize for Riemannian Gradient Descent
325 U0 : ndarray, shape (d, p)
326 Initial starting point for projection.
327 reg : float, optional
328 Regularization term >0 (entropic regularization)
329 k : int
330 Subspace dimension
331 stopThr : float, optional
332 Stop threshold on error (>0)
333 verbose : int, optional
334 Print information along iterations.
335 random_state : int, RandomState instance or None, default=None
336 Determines random number generation for initial value of projection
337 operator when U0 is not given.
338
339 Returns
340 -------
341 pi : ndarray, shape (n, n)
342 Optimal transportation matrix for the given parameters
343 U : ndarray, shape (d, k)
344 Projection operator.
345
346
347 .. _references-projection-robust-wasserstein:
348 References
349 ----------
350 .. [32] Huang, M. , Ma S. & Lai L. (2021).
351 A Riemannian Block Coordinate Descent Method for Computing
352 the Projection Robust Wasserstein Distance, ICML.
353 """ # noqa
354
355 # initialization
356 n, d = X.shape
357 m, d = Y.shape
358 a = np.asarray(a, dtype=np.float64)
359 b = np.asarray(b, dtype=np.float64)
360 u = np.ones(n) / n
361 v = np.ones(m) / m
362 ones = np.ones((n, m))
363
364 assert d > k
365
366 if U0 is None:
367 rng = check_random_state(random_state)
368 U = rng.randn(d, k)
369 U, _ = np.linalg.qr(U)
370 else:
371 U = U0
372
373 def Vpi(X, Y, a, b, pi):
374 # Return the second order matrix of the displacements: sum_ij { (pi)_ij (X_i-Y_j)(X_i-Y_j)^T }.
375 A = X.T.dot(pi).dot(Y)
376 return (
377 X.T.dot(np.diag(a)).dot(X)
378 + Y.T.dot(np.diag(np.sum(pi, 0))).dot(Y)
379 - A
380 - A.T
381 )
382
383 err = 1
384 iter = 0
385
386 while err > stopThr and iter < maxiter:
387 # Projected cost matrix
388 UUT = U.dot(U.T)
389 M = (
390 np.diag(np.diag(X.dot(UUT.dot(X.T)))).dot(ones)
391 + ones.dot(np.diag(np.diag(Y.dot(UUT.dot(Y.T)))))
392 - 2 * X.dot(UUT.dot(Y.T))
393 )
394
395 A = np.empty(M.shape, dtype=M.dtype)
396 np.divide(M, -reg, out=A)
397 np.exp(A, out=A)
398
399 # Sinkhorn update
400 Ap = (1 / a).reshape(-1, 1) * A
401 AtransposeU = np.dot(A.T, u)
402 v = np.divide(b, AtransposeU)
403 u = 1.0 / np.dot(Ap, v)
404 pi = u.reshape((-1, 1)) * A * v.reshape((1, -1))
405
406 V = Vpi(X, Y, a, b, pi)
407
408 # Riemannian gradient descent
409 G = 2 / reg * V.dot(U)
410 GTU = G.T.dot(U)
411 xi = G - U.dot(GTU + GTU.T) / 2 # Riemannian gradient
412 U, _ = np.linalg.qr(U + tau * xi) # Retraction by QR decomposition
413
414 grad_norm = np.linalg.norm(xi)
415 err = max(reg * grad_norm, np.linalg.norm(np.sum(pi, 0) - b, 1))
416
417 f_val = np.trace(U.T.dot(V.dot(U)))
418 if verbose:
419 print("RBCD Iteration: ", iter, " error", err, "\t fval: ", f_val)
420
421 iter = iter + 1
422
423 return pi, U
424
425
426 def ewca(
427 X,
428 U0=None,
429 reg=1,
430 k=2,
431 method="BCD",
432 sinkhorn_method="sinkhorn",
433 stopThr=1e-6,
434 maxiter=100,
435 maxiter_sink=1000,
436 maxiter_MM=10,
437 verbose=0,
438 ):
439 r"""
440 Entropic Wasserstein Component Analysis :ref:`[52] <references-entropic-wasserstein-component_analysis>`.
441
442 The function solves the following optimization problem:
443
444 .. math::
445 \mathbf{U} = \mathop{\arg \min}_\mathbf{U} \quad
446 W(\mathbf{X}, \mathbf{U}\mathbf{U}^T \mathbf{X})
447
448 where :
449
450 - :math:`\mathbf{U}` is a matrix in the Stiefel(`p`, `d`) manifold
451 - :math:`W` is entropic regularized Wasserstein distances
452 - :math:`\mathbf{X}` are samples
453
454 Parameters
455 ----------
456 X : ndarray, shape (n, d)
457 Samples from measure :math:`\mu`.
458 U0 : ndarray, shape (d, k), optional
459 Initial starting point for projection.
460 reg : float, optional
461 Regularization term >0 (entropic regularization).
462 k : int, optional
463 Subspace dimension.
464 method : str, optional
465 Eather 'BCD' or 'MM' (Block Coordinate Descent or Majorization-Minimization).
466 Prefer MM when d is large.
467 sinkhorn_method : str
468 Method used for the Sinkhorn solver, see :ref:`ot.bregman.sinkhorn` for more details.
469 stopThr : float, optional
470 Stop threshold on error (>0).
471 maxiter : int, optional
472 Maximum number of iterations of the BCD/MM.
473 maxiter_sink : int, optional
474 Maximum number of iterations of the Sinkhorn solver.
475 maxiter_MM : int, optional
476 Maximum number of iterations of the MM (only used when method='MM').
477 verbose : int, optional
478 Print information along iterations.
479
480 Returns
481 -------
482 pi : ndarray, shape (n, n)
483 Optimal transportation matrix for the given parameters.
484 U : ndarray, shape (d, k)
485 Matrix Stiefel manifold.
486
487
488 .. _references-entropic-wasserstein-component_analysis:
489 References
490 ----------
491 .. [52] Collas, A., Vayer, T., Flamary, F., & Breloy, A. (2023).
492 Entropic Wasserstein Component Analysis.
493 """ # noqa
494 n, d = X.shape
495 X = X - X.mean(0)
496
497 if U0 is None:
498 pca_fitted = PCA(n_components=k).fit(X)
499 U = pca_fitted.components_.T
500 if method == "MM":
501 lambda_scm = pca_fitted.explained_variance_[0]
502 else:
503 U = U0
504
505 # marginals
506 u0 = (1.0 / n) * np.ones(n)
507
508 # print iterations
509 if verbose > 0:
510 print(
511 "{:4s}|{:13s}|{:12s}|{:12s}".format("It.", "Loss", "Crit.", "Thres.")
512 + "\n"
513 + "-" * 40
514 )
515
516 def compute_loss(M, pi, reg):
517 return np.sum(M * pi) + reg * np.sum(pi * (np.log(pi) - 1))
518
519 def grassmann_distance(U1, U2):
520 proj = U1.T @ U2
521 _, s, _ = np.linalg.svd(proj)
522 s[s > 1] = 1
523 s = np.arccos(s)
524 return np.linalg.norm(s)
525
526 # loop
527 it = 0
528 crit = np.inf
529 sinkhorn_warmstart = None
530
531 while (it < maxiter) and (crit > stopThr):
532 U_old = U
533
534 # Solve transport
535 M = dist_utils(X, (X @ U) @ U.T)
536 pi, log_sinkhorn = sinkhorn_bregman(
537 u0,
538 u0,
539 M,
540 reg,
541 numItermax=maxiter_sink,
542 method=sinkhorn_method,
543 warmstart=sinkhorn_warmstart,
544 warn=False,
545 log=True,
546 )
547 key_warmstart = "warmstart"
548 if key_warmstart in log_sinkhorn:
549 sinkhorn_warmstart = log_sinkhorn[key_warmstart]
550 if (pi >= 1e-300).all():
551 loss = compute_loss(M, pi, reg)
552 else:
553 loss = np.inf
554
555 # Solve PCA
556 pi_sym = (pi + pi.T) / 2
557
558 if method == "BCD":
559 # block coordinate descent
560 S = X.T @ (2 * pi_sym - (1.0 / n) * np.eye(n)) @ X
561 _, U = np.linalg.eigh(S)
562 U = U[:, ::-1][:, :k]
563
564 elif method == "MM":
565 # majorization-minimization
566 eig, _ = np.linalg.eigh(pi_sym)
567 lambda_pi = eig[0]
568
569 for _ in range(maxiter_MM):
570 X_proj = X @ U
571 X_T_X_proj = X.T @ X_proj
572
573 R = (1 / n) * X_T_X_proj
574 alpha = 1 - 2 * n * lambda_pi
575 if alpha > 0:
576 R = alpha * (R - lambda_scm * U)
577 else:
578 R = alpha * R
579
580 R = R - (2 * X.T @ (pi_sym @ X_proj)) + (2 * lambda_pi * X_T_X_proj)
581 U, _ = np.linalg.qr(R)
582
583 else:
584 raise ValueError(f"Unknown method '{method}', use 'BCD' or 'MM'.")
585
586 # stop or not
587 it += 1
588 crit = grassmann_distance(U_old, U)
589
590 # print
591 if verbose > 0:
592 print("{:4d}|{:8e}|{:8e}|{:8e}".format(it, loss, crit, stopThr))
593
594 return pi, U