Debian Codegraph @

ot/da.py

raw symbols SCIP
1 # -*- coding: utf-8 -*-
2 """
3 Domain adaptation with optimal transport
4 """
5
6 # Author: Remi Flamary <[email protected]>
7 # Nicolas Courty <[email protected]>
8 # Michael Perrot <[email protected]>
9 # Nathalie Gayraud <[email protected]>
10 # Ievgen Redko <[email protected]>
11 # Eloi Tanguy <[email protected]>
12 #
13 # License: MIT License
14
15 import numpy as np
16 import warnings
17
18 from .backend import get_backend
19 from .bregman import sinkhorn, jcpot_barycenter
20 from .lp import emd
21 from .utils import (
22 unif,
23 dist,
24 kernel,
25 cost_normalization,
26 label_normalization,
27 laplacian,
28 dots,
29 )
30 from .utils import (
31 BaseEstimator,
32 check_params,
33 deprecated,
34 labels_to_masks,
35 list_to_array,
36 )
37 from .unbalanced import sinkhorn_unbalanced
38 from .gaussian import (
39 empirical_bures_wasserstein_mapping,
40 empirical_gaussian_gromov_wasserstein_mapping,
41 )
42 from .optim import cg
43 from .optim import gcg
44 from .mapping import (
45 nearest_brenier_potential_fit,
46 nearest_brenier_potential_predict_bounds,
47 joint_OT_mapping_linear,
48 joint_OT_mapping_kernel,
49 )
50
51
52 def sinkhorn_lpl1_mm(
53 a,
54 labels_a,
55 b,
56 M,
57 reg,
58 eta=0.1,
59 numItermax=10,
60 numInnerItermax=200,
61 stopInnerThr=1e-9,
62 verbose=False,
63 log=False,
64 ):
65 r"""
66 Solve the entropic regularization optimal transport problem with non-convex
67 group lasso regularization
68
69 The function solves the following optimization problem:
70
71 .. math::
72 \gamma = \mathop{\arg \min}_\gamma \quad \langle \gamma, \mathbf{M} \rangle_F +
73 \mathrm{reg} \cdot \Omega_e(\gamma) + \eta \ \Omega_g(\gamma)
74
75 s.t. \ \gamma \mathbf{1} = \mathbf{a}
76
77 \gamma^T \mathbf{1} = \mathbf{b}
78
79 \gamma \geq 0
80
81
82 where :
83
84 - :math:`\mathbf{M}` is the (`ns`, `nt`) metric cost matrix
85 - :math:`\Omega_e` is the entropic regularization term :math:`\Omega_e
86 (\gamma)=\sum_{i,j} \gamma_{i,j}\log(\gamma_{i,j})`
87 - :math:`\Omega_g` is the group lasso regularization term
88 :math:`\Omega_g(\gamma)=\sum_{i,c} \|\gamma_{i,\mathcal{I}_c}\|^{1/2}_1`
89 where :math:`\mathcal{I}_c` are the index of samples from class `c`
90 in the source domain.
91 - :math:`\mathbf{a}` and :math:`\mathbf{b}` are source and target weights (sum to 1)
92
93 The algorithm used for solving the problem is the generalized conditional
94 gradient as proposed in :ref:`[5, 7] <references-sinkhorn-lpl1-mm>`.
95
96
97 Parameters
98 ----------
99 a : array-like (ns,)
100 samples weights in the source domain
101 labels_a : array-like (ns,)
102 labels of samples in the source domain
103 b : array-like (nt,)
104 samples weights in the target domain
105 M : array-like (ns,nt)
106 loss matrix
107 reg : float
108 Regularization term for entropic regularization >0
109 eta : float, optional
110 Regularization term for group lasso regularization >0
111 numItermax : int, optional
112 Max number of iterations
113 numInnerItermax : int, optional
114 Max number of iterations (inner sinkhorn solver)
115 stopInnerThr : float, optional
116 Stop threshold on error (inner sinkhorn solver) (>0)
117 verbose : bool, optional
118 Print information along iterations
119 log : bool, optional
120 record log if True
121
122
123 Returns
124 -------
125 gamma : (ns, nt) array-like
126 Optimal transportation matrix for the given parameters
127 log : dict
128 log dictionary return only if log==True in parameters
129
130
131 .. _references-sinkhorn-lpl1-mm:
132 References
133 ----------
134 .. [5] N. Courty; R. Flamary; D. Tuia; A. Rakotomamonjy,
135 "Optimal Transport for Domain Adaptation," in IEEE
136 Transactions on Pattern Analysis and Machine Intelligence ,
137 vol.PP, no.99, pp.1-1
138
139 .. [7] Rakotomamonjy, A., Flamary, R., & Courty, N. (2015).
140 Generalized conditional gradient: analysis of convergence
141 and applications. arXiv preprint arXiv:1510.06567.
142
143 See Also
144 --------
145 ot.lp.emd : Unregularized OT
146 ot.bregman.sinkhorn : Entropic regularized OT
147 ot.optim.cg : General regularized OT
148
149 """
150 a, labels_a, b, M = list_to_array(a, labels_a, b, M)
151 nx = get_backend(a, labels_a, b, M)
152
153 p = 0.5
154 epsilon = 1e-3
155
156 labels_u, labels_idx = nx.unique(labels_a, return_inverse=True)
157 n_labels = labels_u.shape[0]
158 unroll_labels_idx = nx.eye(n_labels, type_as=M)[labels_idx]
159
160 W = nx.zeros(M.shape, type_as=M)
161 for _ in range(numItermax):
162 Mreg = M + eta * W
163 if log:
164 transp, log = sinkhorn(
165 a,
166 b,
167 Mreg,
168 reg,
169 numItermax=numInnerItermax,
170 stopThr=stopInnerThr,
171 log=True,
172 )
173 else:
174 transp = sinkhorn(
175 a, b, Mreg, reg, numItermax=numInnerItermax, stopThr=stopInnerThr
176 )
177 # the transport has been computed
178 # check if classes are really separated
179 W = (
180 nx.repeat(transp.T[:, :, None], n_labels, axis=2)
181 * unroll_labels_idx[None, :, :]
182 )
183 W = nx.sum(W, axis=1)
184 W = nx.dot(W, unroll_labels_idx.T)
185 W = p * ((W.T + epsilon) ** (p - 1))
186
187 if log:
188 return transp, log
189 else:
190 return transp
191
192
193 def sinkhorn_l1l2_gl(
194 a,
195 labels_a,
196 b,
197 M,
198 reg,
199 eta=0.1,
200 numItermax=10,
201 numInnerItermax=200,
202 stopInnerThr=1e-9,
203 eps=1e-12,
204 verbose=False,
205 log=False,
206 ):
207 r"""
208 Solve the entropic regularization optimal transport problem with group
209 lasso regularization
210
211 The function solves the following optimization problem:
212
213 .. math::
214 \gamma = \mathop{\arg \min}_\gamma \quad \langle \gamma, \mathbf{M} \rangle_F +
215 \mathrm{reg} \cdot \Omega_e(\gamma) + \eta \ \Omega_g(\gamma)
216
217 s.t. \ \gamma \mathbf{1} = \mathbf{a}
218
219 \gamma^T \mathbf{1} = \mathbf{b}
220
221 \gamma \geq 0
222
223
224 where :
225
226 - :math:`\mathbf{M}` is the (`ns`, `nt`) metric cost matrix
227 - :math:`\Omega_e` is the entropic regularization term
228 :math:`\Omega_e(\gamma)=\sum_{i,j} \gamma_{i,j}\log(\gamma_{i,j})`
229 - :math:`\Omega_g` is the group lasso regularization term
230 :math:`\Omega_g(\gamma)=\sum_{i,c} \|\gamma_{i,\mathcal{I}_c}\|^2`
231 where :math:`\mathcal{I}_c` are the index of samples from class
232 `c` in the source domain.
233 - :math:`\mathbf{a}` and :math:`\mathbf{b}` are source and target weights (sum to 1)
234
235 The algorithm used for solving the problem is the generalized conditional
236 gradient as proposed in :ref:`[5, 7] <references-sinkhorn-l1l2-gl>`.
237
238
239 Parameters
240 ----------
241 a : array-like (ns,)
242 samples weights in the source domain
243 labels_a : array-like (ns,)
244 labels of samples in the source domain
245 b : array-like (nt,)
246 samples in the target domain
247 M : array-like (ns,nt)
248 loss matrix
249 reg : float
250 Regularization term for entropic regularization >0
251 eta : float, optional
252 Regularization term for group lasso regularization >0
253 numItermax : int, optional
254 Max number of iterations
255 numInnerItermax : int, optional
256 Max number of iterations (inner sinkhorn solver)
257 stopInnerThr : float, optional
258 Stop threshold on error (inner sinkhorn solver) (>0)
259 eps: float, optional (default=1e-12)
260 Small value to avoid division by zero
261 verbose : bool, optional
262 Print information along iterations
263 log : bool, optional
264 record log if True
265
266
267 Returns
268 -------
269 gamma : (ns, nt) array-like
270 Optimal transportation matrix for the given parameters
271 log : dict
272 log dictionary return only if log==True in parameters
273
274
275 .. _references-sinkhorn-l1l2-gl:
276 References
277 ----------
278 .. [5] N. Courty; R. Flamary; D. Tuia; A. Rakotomamonjy,
279 "Optimal Transport for Domain Adaptation," in IEEE Transactions
280 on Pattern Analysis and Machine Intelligence , vol.PP, no.99, pp.1-1
281
282 .. [7] Rakotomamonjy, A., Flamary, R., & Courty, N. (2015).
283 Generalized conditional gradient: analysis of convergence and
284 applications. arXiv preprint arXiv:1510.06567.
285
286 See Also
287 --------
288 ot.optim.gcg : Generalized conditional gradient for OT problems
289
290 """
291 a, labels_a, b, M = list_to_array(a, labels_a, b, M)
292 nx = get_backend(a, labels_a, b, M)
293
294 labels_u, labels_idx = nx.unique(labels_a, return_inverse=True)
295 n_labels = labels_u.shape[0]
296 unroll_labels_idx = nx.eye(n_labels, type_as=labels_u)[None, labels_idx]
297
298 def f(G):
299 G_split = nx.repeat(G.T[:, :, None], n_labels, axis=2)
300 return nx.sum(nx.norm(G_split * unroll_labels_idx, axis=1))
301
302 def df(G):
303 G_split = nx.repeat(G.T[:, :, None], n_labels, axis=2) * unroll_labels_idx
304 W = nx.norm(G_split * unroll_labels_idx, axis=1, keepdims=True)
305 G_norm = G_split / nx.clip(W, eps, None)
306 return nx.sum(G_norm, axis=2).T
307
308 return gcg(
309 a,
310 b,
311 M,
312 reg,
313 eta,
314 f,
315 df,
316 G0=None,
317 numItermax=numItermax,
318 numInnerItermax=numInnerItermax,
319 stopThr=stopInnerThr,
320 verbose=verbose,
321 log=log,
322 )
323
324
325 OT_mapping_linear = deprecated(empirical_bures_wasserstein_mapping)
326
327
328 def emd_laplace(
329 a,
330 b,
331 xs,
332 xt,
333 M,
334 sim="knn",
335 sim_param=None,
336 reg="pos",
337 eta=1,
338 alpha=0.5,
339 numItermax=100,
340 stopThr=1e-9,
341 numInnerItermax=100000,
342 stopInnerThr=1e-9,
343 log=False,
344 verbose=False,
345 ):
346 r"""Solve the optimal transport problem (OT) with Laplacian regularization
347
348 .. math::
349 \gamma = \mathop{\arg \min}_\gamma \quad \langle \gamma, \mathbf{M} \rangle_F +
350 \eta \cdot \Omega_\alpha(\gamma)
351
352 s.t. \ \gamma \mathbf{1} = \mathbf{a}
353
354 \gamma^T \mathbf{1} = \mathbf{b}
355
356 \gamma \geq 0
357
358 where:
359
360 - :math:`\mathbf{a}` and :math:`\mathbf{b}` are source and target weights (sum to 1)
361 - :math:`\mathbf{x_s}` and :math:`\mathbf{x_t}` are source and target samples
362 - :math:`\mathbf{M}` is the (`ns`, `nt`) metric cost matrix
363 - :math:`\Omega_\alpha` is the Laplacian regularization term
364
365 .. math::
366 \Omega_\alpha = \frac{1 - \alpha}{n_s^2} \sum_{i,j}
367 \mathbf{S^s}_{i,j} \|T(\mathbf{x}^s_i) - T(\mathbf{x}^s_j) \|^2 +
368 \frac{\alpha}{n_t^2} \sum_{i,j}
369 \mathbf{S^t}_{i,j} \|T(\mathbf{x}^t_i) - T(\mathbf{x}^t_j) \|^2
370
371
372 with :math:`\mathbf{S^s}_{i,j}, \mathbf{S^t}_{i,j}` denoting source and target similarity
373 matrices and :math:`T(\cdot)` being a barycentric mapping.
374
375 The algorithm used for solving the problem is the conditional gradient algorithm as proposed in
376 :ref:`[5] <references-emd-laplace>`.
377
378 Parameters
379 ----------
380 a : array-like (ns,)
381 samples weights in the source domain
382 b : array-like (nt,)
383 samples weights in the target domain
384 xs : array-like (ns,d)
385 samples in the source domain
386 xt : array-like (nt,d)
387 samples in the target domain
388 M : array-like (ns,nt)
389 loss matrix
390 sim : string, optional
391 Type of similarity ('knn' or 'gauss') used to construct the Laplacian.
392 sim_param : int or float, optional
393 Parameter (number of the nearest neighbors for sim='knn'
394 or bandwidth for sim='gauss') used to compute the Laplacian.
395 reg : string
396 Type of Laplacian regularization
397 eta : float
398 Regularization term for Laplacian regularization
399 alpha : float
400 Regularization term for source domain's importance in regularization
401 numItermax : int, optional
402 Max number of iterations
403 stopThr : float, optional
404 Stop threshold on error (inner emd solver) (>0)
405 numInnerItermax : int, optional
406 Max number of iterations (inner CG solver)
407 stopInnerThr : float, optional
408 Stop threshold on error (inner CG solver) (>0)
409 verbose : bool, optional
410 Print information along iterations
411 log : bool, optional
412 record log if True
413
414 Returns
415 -------
416 gamma : (ns, nt) array-like
417 Optimal transportation matrix for the given parameters
418 log : dict
419 log dictionary return only if log==True in parameters
420
421
422 .. _references-emd-laplace:
423 References
424 ----------
425 .. [5] N. Courty; R. Flamary; D. Tuia; A. Rakotomamonjy,
426 "Optimal Transport for Domain Adaptation," in IEEE
427 Transactions on Pattern Analysis and Machine Intelligence,
428 vol.PP, no.99, pp.1-1
429
430 .. [30] R. Flamary, N. Courty, D. Tuia, A. Rakotomamonjy,
431 "Optimal transport with Laplacian regularization: Applications to domain adaptation and shape matching,"
432 in NIPS Workshop on Optimal Transport and Machine Learning OTML, 2014.
433
434 See Also
435 --------
436 ot.lp.emd : Unregularized OT
437 ot.optim.cg : General regularized OT
438
439 """
440 if not isinstance(sim_param, (int, float, type(None))):
441 raise ValueError(
442 "Similarity parameter should be an int or a float. Got {type} instead.".format(
443 type=type(sim_param).__name__
444 )
445 )
446
447 a, b, xs, xt, M = list_to_array(a, b, xs, xt, M)
448 nx = get_backend(a, b, xs, xt, M)
449
450 if sim == "gauss":
451 if sim_param is None:
452 sim_param = 1 / (2 * (nx.mean(dist(xs, xs, "sqeuclidean")) ** 2))
453 sS = kernel(xs, xs, method=sim, sigma=sim_param)
454 sT = kernel(xt, xt, method=sim, sigma=sim_param)
455
456 elif sim == "knn":
457 if sim_param is None:
458 sim_param = 3
459 try:
460 from sklearn.neighbors import kneighbors_graph
461 except ImportError:
462 raise ValueError(
463 "scikit-learn must be installed to use knn similarity. Install with `$pip install scikit-learn`."
464 )
465
466 sS = nx.from_numpy(
467 kneighbors_graph(X=nx.to_numpy(xs), n_neighbors=int(sim_param)).toarray(),
468 type_as=xs,
469 )
470 sS = (sS + sS.T) / 2
471 sT = nx.from_numpy(
472 kneighbors_graph(X=nx.to_numpy(xt), n_neighbors=int(sim_param)).toarray(),
473 type_as=xt,
474 )
475 sT = (sT + sT.T) / 2
476 else:
477 raise ValueError(
478 'Unknown similarity type {sim}. Currently supported similarity types are "knn" and "gauss".'.format(
479 sim=sim
480 )
481 )
482
483 lS = laplacian(sS)
484 lT = laplacian(sT)
485
486 def f(G):
487 return alpha * nx.trace(dots(xt.T, G.T, lS, G, xt)) + (1 - alpha) * nx.trace(
488 dots(xs.T, G, lT, G.T, xs)
489 )
490
491 ls2 = lS + lS.T
492 lt2 = lT + lT.T
493 xt2 = nx.dot(xt, xt.T)
494
495 if reg == "disp":
496 Cs = -eta * alpha / xs.shape[0] * dots(ls2, xs, xt.T)
497 Ct = -eta * (1 - alpha) / xt.shape[0] * dots(xs, xt.T, lt2)
498 M = M + Cs + Ct
499
500 def df(G):
501 return alpha * dots(ls2, G, xt2) + (1 - alpha) * dots(xs, xs.T, G, lt2)
502
503 return cg(
504 a,
505 b,
506 M,
507 reg=eta,
508 f=f,
509 df=df,
510 G0=None,
511 numItermax=numItermax,
512 numItermaxEmd=numInnerItermax,
513 stopThr=stopThr,
514 stopThr2=stopInnerThr,
515 verbose=verbose,
516 log=log,
517 )
518
519
520 def distribution_estimation_uniform(X):
521 r"""estimates a uniform distribution from an array of samples :math:`\mathbf{X}`
522
523 Parameters
524 ----------
525 X : array-like, shape (n_samples, n_features)
526 The array of samples
527
528 Returns
529 -------
530 mu : array-like, shape (n_samples,)
531 The uniform distribution estimated from :math:`\mathbf{X}`
532 """
533
534 return unif(X.shape[0], type_as=X)
535
536
537 class BaseTransport(BaseEstimator):
538 """Base class for OTDA objects
539
540 .. note::
541 All estimators should specify all the parameters that can be set
542 at the class level in their ``__init__`` as explicit keyword
543 arguments (no ``*args`` or ``**kwargs``).
544
545 The fit method should:
546
547 - estimate a cost matrix and store it in a `cost_` attribute
548 - estimate a coupling matrix and store it in a `coupling_` attribute
549 - estimate distributions from source and target data and store them in
550 `mu_s` and `mu_t` attributes
551 - store `Xs` and `Xt` in attributes to be used later on in `transform` and
552 `inverse_transform` methods
553
554 `transform` method should always get as input a `Xs` parameter
555
556 `inverse_transform` method should always get as input a `Xt` parameter
557
558 `transform_labels` method should always get as input a `ys` parameter
559
560 `inverse_transform_labels` method should always get as input a `yt` parameter
561 """
562
563 def fit(self, Xs=None, ys=None, Xt=None, yt=None):
564 r"""Build a coupling matrix from source and target sets of samples
565 :math:`(\mathbf{X_s}, \mathbf{y_s})` and :math:`(\mathbf{X_t}, \mathbf{y_t})`
566
567 Parameters
568 ----------
569 Xs : array-like, shape (n_source_samples, n_features)
570 The training input samples.
571 ys : array-like, shape (n_source_samples,)
572 The training class labels
573 Xt : array-like, shape (n_target_samples, n_features)
574 The training input samples.
575 yt : array-like, shape (n_target_samples,)
576 The class labels. If some target samples are unlabelled, fill the
577 :math:`\mathbf{y_t}`'s elements with -1.
578
579 Warning: Note that, due to this convention -1 cannot be used as a
580 class label
581
582 Returns
583 -------
584 self : object
585 Returns self.
586 """
587 nx = self._get_backend(Xs, ys, Xt, yt)
588
589 # check the necessary inputs parameters are here
590 if check_params(Xs=Xs, Xt=Xt):
591 # pairwise distance
592 self.cost_ = dist(Xs, Xt, metric=self.metric)
593 self.cost_, self.norm_cost_ = cost_normalization(
594 self.cost_, self.norm, return_value=True
595 )
596
597 if (ys is not None) and (yt is not None):
598 if self.limit_max != np.inf:
599 self.limit_max = self.limit_max * nx.max(self.cost_)
600
601 # missing_labels is a (ns, nt) matrix of {0, 1} such that
602 # the cells (i, j) has 0 iff either ys[i] or yt[j] is masked
603 missing_ys = (ys == -1) + nx.zeros(ys.shape, type_as=ys)
604 missing_yt = (yt == -1) + nx.zeros(yt.shape, type_as=yt)
605 missing_labels = missing_ys[:, None] @ missing_yt[None, :]
606 # labels_match is a (ns, nt) matrix of {True, False} such that
607 # the cells (i, j) has False if ys[i] != yt[i]
608 label_match = (ys[:, None] - yt[None, :]) != 0
609 # cost correction is a (ns, nt) matrix of {-Inf, float, Inf} such
610 # that he cells (i, j) has -Inf where there's no correction necessary
611 # by 'correction' we mean setting cost to a large value when
612 # labels do not match
613 # we suppress potential RuntimeWarning caused by Inf multiplication
614 # (as we explicitly cover potential NANs later)
615 with warnings.catch_warnings():
616 warnings.simplefilter("ignore", category=RuntimeWarning)
617 cost_correction = label_match * missing_labels * self.limit_max
618 # this operation is necessary because 0 * Inf = NAN
619 # thus is irrelevant when limit_max is finite
620 cost_correction = nx.nan_to_num(cost_correction, -np.inf)
621 self.cost_ = nx.maximum(self.cost_, cost_correction)
622
623 # distribution estimation
624 self.mu_s = self.distribution_estimation(Xs)
625 self.mu_t = self.distribution_estimation(Xt)
626
627 # store arrays of samples
628 self.xs_ = Xs
629 self.xt_ = Xt
630
631 return self
632
633 def fit_transform(self, Xs=None, ys=None, Xt=None, yt=None):
634 r"""Build a coupling matrix from source and target sets of samples
635 :math:`(\mathbf{X_s}, \mathbf{y_s})` and :math:`(\mathbf{X_t}, \mathbf{y_t})`
636 and transports source samples :math:`\mathbf{X_s}` onto target ones :math:`\mathbf{X_t}`
637
638 Parameters
639 ----------
640 Xs : array-like, shape (n_source_samples, n_features)
641 The training input samples.
642 ys : array-like, shape (n_source_samples,)
643 The class labels for training samples
644 Xt : array-like, shape (n_target_samples, n_features)
645 The training input samples.
646 yt : array-like, shape (n_target_samples,)
647 The class labels. If some target samples are unlabelled, fill the
648 :math:`\mathbf{y_t}`'s elements with -1.
649
650 Warning: Note that, due to this convention -1 cannot be used as a
651 class label
652
653 Returns
654 -------
655 transp_Xs : array-like, shape (n_source_samples, n_features)
656 The source samples samples.
657 """
658
659 return self.fit(Xs, ys, Xt, yt).transform(Xs, ys, Xt, yt)
660
661 def transform(self, Xs=None, ys=None, Xt=None, yt=None, batch_size=128):
662 r"""Transports source samples :math:`\mathbf{X_s}` onto target ones :math:`\mathbf{X_t}`
663
664 Parameters
665 ----------
666 Xs : array-like, shape (n_source_samples, n_features)
667 The source input samples.
668 ys : array-like, shape (n_source_samples,)
669 The class labels for source samples
670 Xt : array-like, shape (n_target_samples, n_features)
671 The target input samples.
672 yt : array-like, shape (n_target_samples,)
673 The class labels for target. If some target samples are unlabelled, fill the
674 :math:`\mathbf{y_t}`'s elements with -1.
675
676 Warning: Note that, due to this convention -1 cannot be used as a
677 class label
678 batch_size : int, optional (default=128)
679 The batch size for out of sample inverse transform
680
681 Returns
682 -------
683 transp_Xs : array-like, shape (n_source_samples, n_features)
684 The transport source samples.
685 """
686 nx = self.nx
687
688 # check the necessary inputs parameters are here
689 if check_params(Xs=Xs):
690 if nx.array_equal(self.xs_, Xs):
691 # perform standard barycentric mapping
692 transp = self.coupling_ / nx.sum(self.coupling_, axis=1)[:, None]
693
694 # set nans to 0
695 transp = nx.nan_to_num(transp, nan=0, posinf=0, neginf=0)
696
697 # compute transported samples
698 transp_Xs = nx.dot(transp, self.xt_)
699 else:
700 # perform out of sample mapping
701 indices = nx.arange(Xs.shape[0])
702 batch_ind = [
703 indices[i : i + batch_size]
704 for i in range(0, len(indices), batch_size)
705 ]
706
707 transp_Xs = []
708 for bi in batch_ind:
709 # get the nearest neighbor in the source domain
710 D0 = dist(Xs[bi], self.xs_)
711 idx = nx.argmin(D0, axis=1)
712
713 # transport the source samples
714 transp = self.coupling_ / nx.sum(self.coupling_, axis=1)[:, None]
715 transp = nx.nan_to_num(transp, nan=0, posinf=0, neginf=0)
716 transp_Xs_ = nx.dot(transp, self.xt_)
717
718 # define the transported points
719 transp_Xs_ = transp_Xs_[idx, :] + Xs[bi] - self.xs_[idx, :]
720
721 transp_Xs.append(transp_Xs_)
722
723 transp_Xs = nx.concatenate(transp_Xs, axis=0)
724
725 return transp_Xs
726
727 def transform_labels(self, ys=None):
728 r"""Propagate source labels :math:`\mathbf{y_s}` to obtain estimated target labels as in
729 :ref:`[27] <references-basetransport-transform-labels>`.
730
731 Parameters
732 ----------
733 ys : array-like, shape (n_source_samples,)
734 The source class labels
735
736 Returns
737 -------
738 transp_ys : array-like, shape (n_target_samples, nb_classes)
739 Estimated soft target labels.
740
741
742 .. _references-basetransport-transform-labels:
743 References
744 ----------
745 .. [27] Ievgen Redko, Nicolas Courty, Rémi Flamary, Devis Tuia
746 "Optimal transport for multi-source domain adaptation under target shift",
747 International Conference on Artificial Intelligence and Statistics (AISTATS), 2019.
748
749 """
750 nx = self.nx
751
752 # check the necessary inputs parameters are here
753 if check_params(ys=ys):
754 # perform label propagation
755 transp = self.coupling_ / nx.sum(self.coupling_, axis=0)[None, :]
756
757 # set nans to 0
758 transp = nx.nan_to_num(transp, nan=0, posinf=0, neginf=0)
759
760 # compute propagated labels
761 labels = label_normalization(ys)
762 masks = labels_to_masks(labels, nx=nx, type_as=transp)
763 transp_ys = nx.dot(masks.T, transp)
764
765 return transp_ys.T
766
767 def inverse_transform(self, Xs=None, ys=None, Xt=None, yt=None, batch_size=128):
768 r"""Transports target samples :math:`\mathbf{X_t}` onto source samples :math:`\mathbf{X_s}`
769
770 Parameters
771 ----------
772 Xs : array-like, shape (n_source_samples, n_features)
773 The source input samples.
774 ys : array-like, shape (n_source_samples,)
775 The source class labels
776 Xt : array-like, shape (n_target_samples, n_features)
777 The target input samples.
778 yt : array-like, shape (n_target_samples,)
779 The target class labels. If some target samples are unlabelled, fill the
780 :math:`\mathbf{y_t}`'s elements with -1.
781
782 Warning: Note that, due to this convention -1 cannot be used as a
783 class label
784 batch_size : int, optional (default=128)
785 The batch size for out of sample inverse transform
786
787 Returns
788 -------
789 transp_Xt : array-like, shape (n_source_samples, n_features)
790 The transported target samples.
791 """
792 nx = self.nx
793
794 # check the necessary inputs parameters are here
795 if check_params(Xt=Xt):
796 if nx.array_equal(self.xt_, Xt):
797 # perform standard barycentric mapping
798 transp_ = self.coupling_.T / nx.sum(self.coupling_, 0)[:, None]
799
800 # set nans to 0
801 transp_ = nx.nan_to_num(transp_, nan=0, posinf=0, neginf=0)
802
803 # compute transported samples
804 transp_Xt = nx.dot(transp_, self.xs_)
805 else:
806 # perform out of sample mapping
807 indices = nx.arange(Xt.shape[0])
808 batch_ind = [
809 indices[i : i + batch_size]
810 for i in range(0, len(indices), batch_size)
811 ]
812
813 transp_Xt = []
814 for bi in batch_ind:
815 D0 = dist(Xt[bi], self.xt_)
816 idx = nx.argmin(D0, axis=1)
817
818 # transport the target samples
819 transp_ = self.coupling_.T / nx.sum(self.coupling_, 0)[:, None]
820 transp_ = nx.nan_to_num(transp_, nan=0, posinf=0, neginf=0)
821 transp_Xt_ = nx.dot(transp_, self.xs_)
822
823 # define the transported points
824 transp_Xt_ = transp_Xt_[idx, :] + Xt[bi] - self.xt_[idx, :]
825
826 transp_Xt.append(transp_Xt_)
827
828 transp_Xt = nx.concatenate(transp_Xt, axis=0)
829
830 return transp_Xt
831
832 def inverse_transform_labels(self, yt=None):
833 r"""Propagate target labels :math:`\mathbf{y_t}` to obtain estimated source labels
834 :math:`\mathbf{y_s}`
835
836 Parameters
837 ----------
838 yt : array-like, shape (n_target_samples,)
839
840 Returns
841 -------
842 transp_ys : array-like, shape (n_source_samples, nb_classes)
843 Estimated soft source labels.
844 """
845 nx = self.nx
846
847 # check the necessary inputs parameters are here
848 if check_params(yt=yt):
849 # perform label propagation
850 transp = self.coupling_ / nx.sum(self.coupling_, 1)[:, None]
851 # set nans to 0
852 transp = nx.nan_to_num(transp, nan=0, posinf=0, neginf=0)
853
854 # compute propagated labels
855 labels = label_normalization(yt)
856 masks = labels_to_masks(labels, nx=nx, type_as=transp)
857 transp_ys = nx.dot(masks.T, transp.T)
858
859 return transp_ys.T
860
861
862 class LinearTransport(BaseTransport):
863 r"""OT linear operator between empirical distributions
864
865 The function estimates the optimal linear operator that aligns the two
866 empirical distributions. This is equivalent to estimating the closed
867 form mapping between two Gaussian distributions :math:`\mathcal{N}(\mu_s,\Sigma_s)`
868 and :math:`\mathcal{N}(\mu_t,\Sigma_t)` as proposed in
869 :ref:`[14] <references-lineartransport>` and discussed in remark 2.29 in
870 :ref:`[15] <references-lineartransport>`.
871
872 The linear operator from source to target :math:`M`
873
874 .. math::
875 M(\mathbf{x})= \mathbf{A} \mathbf{x} + \mathbf{b}
876
877 where :
878
879 .. math::
880 \mathbf{A} &= \Sigma_s^{-1/2} \left(\Sigma_s^{1/2}\Sigma_t\Sigma_s^{1/2} \right)^{1/2}
881 \Sigma_s^{-1/2}
882
883 \mathbf{b} &= \mu_t - \mathbf{A} \mu_s
884
885 Parameters
886 ----------
887 reg : float,optional
888 regularization added to the daigonals of covariances (>0)
889 bias: boolean, optional
890 estimate bias :math:`\mathbf{b}` else :math:`\mathbf{b} = 0` (default:True)
891 log : bool, optional
892 record log if True
893
894
895 .. _references-lineartransport:
896 References
897 ----------
898 .. [14] Knott, M. and Smith, C. S. "On the optimal mapping of
899 distributions", Journal of Optimization Theory and Applications
900 Vol 43, 1984
901
902 .. [15] Peyré, G., & Cuturi, M. (2017). "Computational Optimal
903 Transport", 2018.
904
905 """
906
907 def __init__(
908 self,
909 reg=1e-8,
910 bias=True,
911 log=False,
912 distribution_estimation=distribution_estimation_uniform,
913 ):
914 self.bias = bias
915 self.log = log
916 self.reg = reg
917 self.distribution_estimation = distribution_estimation
918
919 def fit(self, Xs=None, ys=None, Xt=None, yt=None):
920 r"""Build a coupling matrix from source and target sets of samples
921 :math:`(\mathbf{X_s}, \mathbf{y_s})` and :math:`(\mathbf{X_t}, \mathbf{y_t})`
922
923 Parameters
924 ----------
925 Xs : array-like, shape (n_source_samples, n_features)
926 The training input samples.
927 ys : array-like, shape (n_source_samples,)
928 The class labels
929 Xt : array-like, shape (n_target_samples, n_features)
930 The training input samples.
931 yt : array-like, shape (n_target_samples,)
932 The class labels. If some target samples are unlabelled, fill the
933 :math:`\mathbf{y_t}`'s elements with -1.
934
935 Warning: Note that, due to this convention -1 cannot be used as a
936 class label
937
938 Returns
939 -------
940 self : object
941 Returns self.
942 """
943 nx = self._get_backend(Xs, ys, Xt, yt)
944 self.nx = nx
945
946 self.mu_s = self.distribution_estimation(Xs)
947 self.mu_t = self.distribution_estimation(Xt)
948
949 # coupling estimation
950 returned_ = empirical_bures_wasserstein_mapping(
951 Xs,
952 Xt,
953 reg=self.reg,
954 ws=nx.reshape(self.mu_s, (-1, 1)),
955 wt=nx.reshape(self.mu_t, (-1, 1)),
956 bias=self.bias,
957 log=self.log,
958 )
959
960 # deal with the value of log
961 if self.log:
962 self.A_, self.B_, self.log_ = returned_
963 else:
964 (
965 self.A_,
966 self.B_,
967 ) = returned_
968 self.log_ = dict()
969
970 # re compute inverse mapping
971 self.A1_ = nx.inv(self.A_)
972 self.B1_ = -nx.dot(self.B_, self.A1_)
973
974 return self
975
976 def transform(self, Xs=None, ys=None, Xt=None, yt=None, batch_size=128):
977 r"""Transports source samples :math:`\mathbf{X_s}` onto target ones :math:`\mathbf{X_t}`
978
979 Parameters
980 ----------
981 Xs : array-like, shape (n_source_samples, n_features)
982 The training input samples.
983 ys : array-like, shape (n_source_samples,)
984 The class labels
985 Xt : array-like, shape (n_target_samples, n_features)
986 The training input samples.
987 yt : array-like, shape (n_target_samples,)
988 The class labels. If some target samples are unlabelled, fill the
989 :math:`\mathbf{y_t}`'s elements with -1.
990
991 Warning: Note that, due to this convention -1 cannot be used as a
992 class label
993 batch_size : int, optional (default=128)
994 The batch size for out of sample inverse transform
995
996 Returns
997 -------
998 transp_Xs : array-like, shape (n_source_samples, n_features)
999 The transport source samples.
1000 """
1001 nx = self.nx
1002
1003 # check the necessary inputs parameters are here
1004 if check_params(Xs=Xs):
1005 transp_Xs = nx.dot(Xs, self.A_) + self.B_
1006
1007 return transp_Xs
1008
1009 def inverse_transform(self, Xs=None, ys=None, Xt=None, yt=None, batch_size=128):
1010 r"""Transports target samples :math:`\mathbf{X_t}` onto source samples :math:`\mathbf{X_s}`
1011
1012 Parameters
1013 ----------
1014 Xs : array-like, shape (n_source_samples, n_features)
1015 The training input samples.
1016 ys : array-like, shape (n_source_samples,)
1017 The class labels
1018 Xt : array-like, shape (n_target_samples, n_features)
1019 The training input samples.
1020 yt : array-like, shape (n_target_samples,)
1021 The class labels. If some target samples are unlabelled, fill the
1022 :math:`\mathbf{y_t}`'s elements with -1.
1023
1024 Warning: Note that, due to this convention -1 cannot be used as a
1025 class label
1026 batch_size : int, optional (default=128)
1027 The batch size for out of sample inverse transform
1028
1029 Returns
1030 -------
1031 transp_Xt : array-like, shape (n_source_samples, n_features)
1032 The transported target samples.
1033 """
1034 nx = self.nx
1035
1036 # check the necessary inputs parameters are here
1037 if check_params(Xt=Xt):
1038 transp_Xt = nx.dot(Xt, self.A1_) + self.B1_
1039
1040 return transp_Xt
1041
1042
1043 class LinearGWTransport(LinearTransport):
1044 r"""OT Gaussian Gromov-Wasserstein linear operator between empirical distributions
1045
1046 The function estimates the optimal linear operator that aligns the two
1047 empirical distributions optimally wrt the Gromov-Wasserstein distance. This is equivalent to estimating the closed
1048 form mapping between two Gaussian distributions :math:`\mathcal{N}(\mu_s,\Sigma_s)`
1049 and :math:`\mathcal{N}(\mu_t,\Sigma_t)` as proposed in
1050 :ref:`[57] <references-lineargwtransport>`.
1051
1052 The linear operator from source to target :math:`M`
1053
1054 .. math::
1055 M(\mathbf{x})= \mathbf{A} \mathbf{x} + \mathbf{b}
1056
1057 where the matrix :math:`\mathbf{A}` and the vector :math:`\mathbf{b}` are
1058 defined in :ref:`[57] <references-lineargwtransport>`.
1059
1060
1061
1062 Parameters
1063 ----------
1064 sign_eigs : array-like (n_features), str, optional
1065 sign of the eigenvalues of the mapping matrix, by default all signs will
1066 be positive. If 'skewness' is provided, the sign of the eigenvalues is
1067 selected as the product of the sign of the skewness of the projected data.
1068 log : bool, optional
1069 record log if True
1070
1071
1072 .. _references-lineargwtransport:
1073 References
1074 ----------
1075 .. [57] Delon, J., Desolneux, A., & Salmona, A. (2022). Gromov–Wasserstein
1076 distances between Gaussian distributions. Journal of Applied Probability,
1077 59(4), 1178-1198.
1078
1079 """
1080
1081 def __init__(
1082 self,
1083 log=False,
1084 sign_eigs=None,
1085 distribution_estimation=distribution_estimation_uniform,
1086 ):
1087 self.sign_eigs = sign_eigs
1088 self.log = log
1089 self.distribution_estimation = distribution_estimation
1090
1091 def fit(self, Xs=None, ys=None, Xt=None, yt=None):
1092 r"""Build a coupling matrix from source and target sets of samples
1093 :math:`(\mathbf{X_s}, \mathbf{y_s})` and :math:`(\mathbf{X_t}, \mathbf{y_t})`
1094
1095 Parameters
1096 ----------
1097 Xs : array-like, shape (n_source_samples, n_features)
1098 The training input samples.
1099 ys : array-like, shape (n_source_samples,)
1100 The class labels
1101 Xt : array-like, shape (n_target_samples, n_features)
1102 The training input samples.
1103 yt : array-like, shape (n_target_samples,)
1104 The class labels. If some target samples are unlabelled, fill the
1105 :math:`\mathbf{y_t}`'s elements with -1.
1106
1107 Warning: Note that, due to this convention -1 cannot be used as a
1108 class label
1109
1110 Returns
1111 -------
1112 self : object
1113 Returns self.
1114 """
1115 nx = self._get_backend(Xs, ys, Xt, yt)
1116 self.nx = nx
1117
1118 self.mu_s = self.distribution_estimation(Xs)
1119 self.mu_t = self.distribution_estimation(Xt)
1120
1121 # coupling estimation
1122 returned_ = empirical_gaussian_gromov_wasserstein_mapping(
1123 Xs,
1124 Xt,
1125 ws=self.mu_s[:, None],
1126 wt=self.mu_t[:, None],
1127 sign_eigs=self.sign_eigs,
1128 log=self.log,
1129 )
1130
1131 # deal with the value of log
1132 if self.log:
1133 self.A_, self.B_, self.log_ = returned_
1134 else:
1135 (
1136 self.A_,
1137 self.B_,
1138 ) = returned_
1139 self.log_ = dict()
1140
1141 # re compute inverse mapping
1142 returned_1_ = empirical_gaussian_gromov_wasserstein_mapping(
1143 Xt,
1144 Xs,
1145 ws=self.mu_t[:, None],
1146 wt=self.mu_s[:, None],
1147 sign_eigs=self.sign_eigs,
1148 log=self.log,
1149 )
1150 if self.log:
1151 self.A1_, self.B1_, self.log_1_ = returned_1_
1152 else:
1153 (
1154 self.A1_,
1155 self.B1_,
1156 ) = returned_1_
1157 self.log_ = dict()
1158
1159 return self
1160
1161
1162 class SinkhornTransport(BaseTransport):
1163 """Domain Adaptation OT method based on Sinkhorn Algorithm
1164
1165 Parameters
1166 ----------
1167 reg_e : float, optional (default=1)
1168 Entropic regularization parameter
1169 max_iter : int, float, optional (default=1000)
1170 The minimum number of iteration before stopping the optimization
1171 algorithm if it has not converged
1172 tol : float, optional (default=10e-9)
1173 The precision required to stop the optimization algorithm.
1174 verbose : bool, optional (default=False)
1175 Controls the verbosity of the optimization algorithm
1176 log : int, optional (default=False)
1177 Controls the logs of the optimization algorithm
1178 metric : string, optional (default="sqeuclidean")
1179 The ground metric for the Wasserstein problem
1180 norm : string, optional (default=None)
1181 If given, normalize the ground metric to avoid numerical errors that
1182 can occur with large metric values. Accepted values are 'median',
1183 'max', 'log' and 'loglog'.
1184 distribution_estimation : callable, optional (defaults to the uniform)
1185 The kind of distribution estimation to employ
1186 out_of_sample_map : string, optional (default="continuous")
1187 The kind of out of sample mapping to apply to transport samples
1188 from a domain into another one. Currently the only possible option is
1189 "ferradans" which uses the nearest neighbor method proposed in :ref:`[6]
1190 <references-sinkhorntransport>` while "continuous" use the out of sample
1191 method from :ref:`[66]
1192 <references-sinkhorntransport>` and :ref:`[19]
1193 <references-sinkhorntransport>`.
1194 limit_max: float, optional (default=np.inf)
1195 Controls the semi supervised mode. Transport between labeled source
1196 and target samples of different classes will exhibit an cost defined
1197 by this variable
1198
1199 Attributes
1200 ----------
1201 coupling_ : array-like, shape (n_source_samples, n_target_samples)
1202 The optimal coupling
1203 log_ : dictionary
1204 The dictionary of log, empty dict if parameter log is not True
1205
1206
1207 .. _references-sinkhorntransport:
1208 References
1209 ----------
1210 .. [1] N. Courty; R. Flamary; D. Tuia; A. Rakotomamonjy,
1211 "Optimal Transport for Domain Adaptation," in IEEE Transactions
1212 on Pattern Analysis and Machine Intelligence , vol.PP, no.99, pp.1-1
1213
1214 .. [2] M. Cuturi, Sinkhorn Distances : Lightspeed Computation of Optimal
1215 Transport, Advances in Neural Information Processing Systems (NIPS)
1216 26, 2013
1217
1218 .. [6] Ferradans, S., Papadakis, N., Peyré, G., & Aujol, J. F. (2014).
1219 Regularized discrete optimal transport. SIAM Journal on Imaging
1220 Sciences, 7(3), 1853-1882.
1221
1222 .. [19] Seguy, V., Bhushan Damodaran, B., Flamary, R., Courty, N., Rolet, A.
1223 & Blondel, M. Large-scale Optimal Transport and Mapping Estimation.
1224 International Conference on Learning Representation (2018)
1225
1226 .. [66] Pooladian, Aram-Alexandre, and Jonathan Niles-Weed. "Entropic
1227 estimation of optimal transport maps." arXiv preprint
1228 arXiv:2109.12004 (2021).
1229
1230 """
1231
1232 def __init__(
1233 self,
1234 reg_e=1.0,
1235 method="sinkhorn_log",
1236 max_iter=1000,
1237 tol=10e-9,
1238 verbose=False,
1239 log=False,
1240 metric="sqeuclidean",
1241 norm=None,
1242 distribution_estimation=distribution_estimation_uniform,
1243 out_of_sample_map="continuous",
1244 limit_max=np.inf,
1245 ):
1246 if out_of_sample_map not in ["ferradans", "continuous"]:
1247 raise ValueError("Unknown out_of_sample_map method")
1248
1249 self.reg_e = reg_e
1250 self.method = method
1251 self.max_iter = max_iter
1252 self.tol = tol
1253 self.verbose = verbose
1254 self.log = log
1255 self.metric = metric
1256 self.norm = norm
1257 self.limit_max = limit_max
1258 self.distribution_estimation = distribution_estimation
1259 self.out_of_sample_map = out_of_sample_map
1260
1261 def fit(self, Xs=None, ys=None, Xt=None, yt=None):
1262 r"""Build a coupling matrix from source and target sets of samples
1263 :math:`(\mathbf{X_s}, \mathbf{y_s})` and :math:`(\mathbf{X_t}, \mathbf{y_t})`
1264
1265 Parameters
1266 ----------
1267 Xs : array-like, shape (n_source_samples, n_features)
1268 The training input samples.
1269 ys : array-like, shape (n_source_samples,)
1270 The class labels
1271 Xt : array-like, shape (n_target_samples, n_features)
1272 The training input samples.
1273 yt : array-like, shape (n_target_samples,)
1274 The class labels. If some target samples are unlabelled, fill the
1275 :math:`\mathbf{y_t}`'s elements with -1.
1276
1277 Warning: Note that, due to this convention -1 cannot be used as a
1278 class label
1279
1280 Returns
1281 -------
1282 self : object
1283 Returns self.
1284 """
1285
1286 super(SinkhornTransport, self).fit(Xs, ys, Xt, yt)
1287
1288 if self.out_of_sample_map == "continuous":
1289 self.log = True
1290 if not self.method == "sinkhorn_log":
1291 self.method = "sinkhorn_log"
1292 warnings.warn(
1293 "The method has been set to 'sinkhorn_log' as it is the only method available for out_of_sample_map='continuous'"
1294 )
1295
1296 # coupling estimation
1297 returned_ = sinkhorn(
1298 a=self.mu_s,
1299 b=self.mu_t,
1300 M=self.cost_,
1301 reg=self.reg_e,
1302 method=self.method,
1303 numItermax=self.max_iter,
1304 stopThr=self.tol,
1305 verbose=self.verbose,
1306 log=self.log,
1307 )
1308
1309 # deal with the value of log
1310 if self.log:
1311 self.coupling_, self.log_ = returned_
1312 else:
1313 self.coupling_ = returned_
1314 self.log_ = dict()
1315
1316 return self
1317
1318 def transform(self, Xs=None, ys=None, Xt=None, yt=None, batch_size=128):
1319 r"""Transports source samples :math:`\mathbf{X_s}` onto target ones :math:`\mathbf{X_t}`
1320
1321 Parameters
1322 ----------
1323 Xs : array-like, shape (n_source_samples, n_features)
1324 The source input samples.
1325 ys : array-like, shape (n_source_samples,)
1326 The class labels for source samples
1327 Xt : array-like, shape (n_target_samples, n_features)
1328 The target input samples.
1329 yt : array-like, shape (n_target_samples,)
1330 The class labels for target. If some target samples are unlabelled, fill the
1331 :math:`\mathbf{y_t}`'s elements with -1.
1332
1333 Warning: Note that, due to this convention -1 cannot be used as a
1334 class label
1335 batch_size : int, optional (default=128)
1336 The batch size for out of sample inverse transform
1337
1338 Returns
1339 -------
1340 transp_Xs : array-like, shape (n_source_samples, n_features)
1341 The transport source samples.
1342 """
1343 nx = self.nx
1344
1345 if self.out_of_sample_map == "ferradans":
1346 return super(SinkhornTransport, self).transform(Xs, ys, Xt, yt, batch_size)
1347
1348 else: # self.out_of_sample_map == 'continuous':
1349 # check the necessary inputs parameters are here
1350 g = self.log_["log_v"]
1351
1352 indices = nx.arange(Xs.shape[0])
1353 batch_ind = [
1354 indices[i : i + batch_size] for i in range(0, len(indices), batch_size)
1355 ]
1356
1357 transp_Xs = []
1358 for bi in batch_ind:
1359 # get the nearest neighbor in the source domain
1360 M = dist(Xs[bi], self.xt_, metric=self.metric)
1361
1362 M = cost_normalization(M, self.norm, value=self.norm_cost_)
1363
1364 K = nx.exp(-M / self.reg_e + g[None, :])
1365
1366 transp_Xs_ = nx.dot(K, self.xt_) / nx.sum(K, axis=1)[:, None]
1367
1368 transp_Xs.append(transp_Xs_)
1369
1370 transp_Xs = nx.concatenate(transp_Xs, axis=0)
1371
1372 return transp_Xs
1373
1374 def inverse_transform(self, Xs=None, ys=None, Xt=None, yt=None, batch_size=128):
1375 r"""Transports target samples :math:`\mathbf{X_t}` onto source samples :math:`\mathbf{X_s}`
1376
1377 Parameters
1378 ----------
1379 Xs : array-like, shape (n_source_samples, n_features)
1380 The source input samples.
1381 ys : array-like, shape (n_source_samples,)
1382 The class labels for source samples
1383 Xt : array-like, shape (n_target_samples, n_features)
1384 The target input samples.
1385 yt : array-like, shape (n_target_samples,)
1386 The class labels for target. If some target samples are unlabelled, fill the
1387 :math:`\mathbf{y_t}`'s elements with -1.
1388
1389 Warning: Note that, due to this convention -1 cannot be used as a
1390 class label
1391 batch_size : int, optional (default=128)
1392 The batch size for out of sample inverse transform
1393
1394 Returns
1395 -------
1396 transp_Xt : array-like, shape (n_source_samples, n_features)
1397 The transport target samples.
1398 """
1399
1400 nx = self.nx
1401
1402 if self.out_of_sample_map == "ferradans":
1403 return super(SinkhornTransport, self).inverse_transform(
1404 Xs, ys, Xt, yt, batch_size
1405 )
1406
1407 else: # self.out_of_sample_map == 'continuous':
1408 f = self.log_["log_u"]
1409
1410 indices = nx.arange(Xt.shape[0])
1411 batch_ind = [
1412 indices[i : i + batch_size] for i in range(0, len(indices), batch_size)
1413 ]
1414
1415 transp_Xt = []
1416 for bi in batch_ind:
1417 M = dist(Xt[bi], self.xs_, metric=self.metric)
1418 M = cost_normalization(M, self.norm, value=self.norm_cost_)
1419
1420 K = nx.exp(-M / self.reg_e + f[None, :])
1421
1422 transp_Xt_ = nx.dot(K, self.xs_) / nx.sum(K, axis=1)[:, None]
1423
1424 transp_Xt.append(transp_Xt_)
1425
1426 transp_Xt = nx.concatenate(transp_Xt, axis=0)
1427
1428 return transp_Xt
1429
1430
1431 class EMDTransport(BaseTransport):
1432 """Domain Adaptation OT method based on Earth Mover's Distance
1433
1434 Parameters
1435 ----------
1436 metric : string, optional (default="sqeuclidean")
1437 The ground metric for the Wasserstein problem
1438 norm : string, optional (default=None)
1439 If given, normalize the ground metric to avoid numerical errors that
1440 can occur with large metric values.
1441 log : int, optional (default=False)
1442 Controls the logs of the optimization algorithm
1443 distribution_estimation : callable, optional (defaults to the uniform)
1444 The kind of distribution estimation to employ
1445 out_of_sample_map : string, optional (default="ferradans")
1446 The kind of out of sample mapping to apply to transport samples
1447 from a domain into another one. Currently the only possible option is
1448 "ferradans" which uses the method proposed in :ref:`[6] <references-emdtransport>`.
1449 limit_max: float, optional (default=10)
1450 Controls the semi supervised mode. Transport between labeled source
1451 and target samples of different classes will exhibit an infinite cost
1452 (10 times the maximum value of the cost matrix)
1453 max_iter : int, optional (default=100000)
1454 The maximum number of iterations before stopping the optimization
1455 algorithm if it has not converged.
1456
1457 Attributes
1458 ----------
1459 coupling_ : array-like, shape (n_source_samples, n_target_samples)
1460 The optimal coupling
1461
1462
1463 .. _references-emdtransport:
1464 References
1465 ----------
1466 .. [1] N. Courty; R. Flamary; D. Tuia; A. Rakotomamonjy,
1467 "Optimal Transport for Domain Adaptation," in IEEE Transactions
1468 on Pattern Analysis and Machine Intelligence , vol.PP, no.99, pp.1-1
1469 .. [6] Ferradans, S., Papadakis, N., Peyré, G., & Aujol, J. F. (2014).
1470 Regularized discrete optimal transport. SIAM Journal on Imaging
1471 Sciences, 7(3), 1853-1882.
1472 """
1473
1474 def __init__(
1475 self,
1476 metric="sqeuclidean",
1477 norm=None,
1478 log=False,
1479 distribution_estimation=distribution_estimation_uniform,
1480 out_of_sample_map="ferradans",
1481 limit_max=10,
1482 max_iter=100000,
1483 ):
1484 self.metric = metric
1485 self.norm = norm
1486 self.log = log
1487 self.limit_max = limit_max
1488 self.distribution_estimation = distribution_estimation
1489 self.out_of_sample_map = out_of_sample_map
1490 self.max_iter = max_iter
1491
1492 def fit(self, Xs, ys=None, Xt=None, yt=None):
1493 r"""Build a coupling matrix from source and target sets of samples
1494 :math:`(\mathbf{X_s}, \mathbf{y_s})` and :math:`(\mathbf{X_t}, \mathbf{y_t})`
1495
1496 Parameters
1497 ----------
1498 Xs : array-like, shape (n_source_samples, n_features)
1499 The training input samples.
1500 ys : array-like, shape (n_source_samples,)
1501 The class labels
1502 Xt : array-like, shape (n_target_samples, n_features)
1503 The training input samples.
1504 yt : array-like, shape (n_target_samples,)
1505 The class labels. If some target samples are unlabelled, fill the
1506 :math:`\mathbf{y_t}`'s elements with -1.
1507
1508 Warning: Note that, due to this convention -1 cannot be used as a
1509 class label
1510
1511 Returns
1512 -------
1513 self : object
1514 Returns self.
1515 """
1516
1517 super(EMDTransport, self).fit(Xs, ys, Xt, yt)
1518
1519 returned_ = emd(
1520 a=self.mu_s,
1521 b=self.mu_t,
1522 M=self.cost_,
1523 numItermax=self.max_iter,
1524 log=self.log,
1525 )
1526
1527 # coupling estimation
1528 if self.log:
1529 self.coupling_, self.log_ = returned_
1530 else:
1531 self.coupling_ = returned_
1532 self.log_ = dict()
1533 return self
1534
1535
1536 class SinkhornLpl1Transport(BaseTransport):
1537 r"""Domain Adaptation OT method based on sinkhorn algorithm +
1538 LpL1 class regularization.
1539
1540 Parameters
1541 ----------
1542 reg_e : float, optional (default=1)
1543 Entropic regularization parameter
1544 reg_cl : float, optional (default=0.1)
1545 Class regularization parameter
1546 max_iter : int, float, optional (default=10)
1547 The minimum number of iteration before stopping the optimization
1548 algorithm if it has not converged
1549 max_inner_iter : int, float, optional (default=200)
1550 The number of iteration in the inner loop
1551 log : bool, optional (default=False)
1552 Controls the logs of the optimization algorithm
1553 tol : float, optional (default=10e-9)
1554 Stop threshold on error (inner sinkhorn solver) (>0)
1555 verbose : bool, optional (default=False)
1556 Controls the verbosity of the optimization algorithm
1557 metric : string, optional (default="sqeuclidean")
1558 The ground metric for the Wasserstein problem
1559 norm : string, optional (default=None)
1560 If given, normalize the ground metric to avoid numerical errors that
1561 can occur with large metric values.
1562 distribution_estimation : callable, optional (defaults to the uniform)
1563 The kind of distribution estimation to employ
1564 out_of_sample_map : string, optional (default="ferradans")
1565 The kind of out of sample mapping to apply to transport samples
1566 from a domain into another one. Currently the only possible option is
1567 "ferradans" which uses the method proposed in :ref:`[6] <references-sinkhornlpl1transport>`.
1568 limit_max: float, optional (default=np.inf)
1569 Controls the semi supervised mode. Transport between labeled source
1570 and target samples of different classes will exhibit a cost defined by
1571 limit_max.
1572
1573 Attributes
1574 ----------
1575 coupling_ : array-like, shape (n_source_samples, n_target_samples)
1576 The optimal coupling
1577
1578
1579 .. _references-sinkhornlpl1transport:
1580 References
1581 ----------
1582 .. [1] N. Courty; R. Flamary; D. Tuia; A. Rakotomamonjy,
1583 "Optimal Transport for Domain Adaptation," in IEEE
1584 Transactions on Pattern Analysis and Machine Intelligence ,
1585 vol.PP, no.99, pp.1-1
1586
1587 .. [2] Rakotomamonjy, A., Flamary, R., & Courty, N. (2015).
1588 Generalized conditional gradient: analysis of convergence
1589 and applications. arXiv preprint arXiv:1510.06567.
1590
1591 .. [6] Ferradans, S., Papadakis, N., Peyré, G., & Aujol, J. F. (2014).
1592 Regularized discrete optimal transport. SIAM Journal on Imaging
1593 Sciences, 7(3), 1853-1882.
1594 """
1595
1596 def __init__(
1597 self,
1598 reg_e=1.0,
1599 reg_cl=0.1,
1600 max_iter=10,
1601 max_inner_iter=200,
1602 log=False,
1603 tol=10e-9,
1604 verbose=False,
1605 metric="sqeuclidean",
1606 norm=None,
1607 distribution_estimation=distribution_estimation_uniform,
1608 out_of_sample_map="ferradans",
1609 limit_max=np.inf,
1610 ):
1611 self.reg_e = reg_e
1612 self.reg_cl = reg_cl
1613 self.max_iter = max_iter
1614 self.max_inner_iter = max_inner_iter
1615 self.tol = tol
1616 self.log = log
1617 self.verbose = verbose
1618 self.metric = metric
1619 self.norm = norm
1620 self.distribution_estimation = distribution_estimation
1621 self.out_of_sample_map = out_of_sample_map
1622 self.limit_max = limit_max
1623
1624 def fit(self, Xs, ys=None, Xt=None, yt=None):
1625 r"""Build a coupling matrix from source and target sets of samples
1626 :math:`(\mathbf{X_s}, \mathbf{y_s})` and :math:`(\mathbf{X_t}, \mathbf{y_t})`
1627
1628 Parameters
1629 ----------
1630 Xs : array-like, shape (n_source_samples, n_features)
1631 The training input samples.
1632 ys : array-like, shape (n_source_samples,)
1633 The class labels
1634 Xt : array-like, shape (n_target_samples, n_features)
1635 The training input samples.
1636 yt : array-like, shape (n_target_samples,)
1637 The class labels. If some target samples are unlabelled, fill the
1638 :math:`\mathbf{y_t}`'s elements with -1.
1639
1640 Warning: Note that, due to this convention -1 cannot be used as a
1641 class label
1642
1643 Returns
1644 -------
1645 self : object
1646 Returns self.
1647 """
1648
1649 # check the necessary inputs parameters are here
1650 if check_params(Xs=Xs, Xt=Xt, ys=ys):
1651 super(SinkhornLpl1Transport, self).fit(Xs, ys, Xt, yt)
1652
1653 returned_ = sinkhorn_lpl1_mm(
1654 a=self.mu_s,
1655 labels_a=ys,
1656 b=self.mu_t,
1657 M=self.cost_,
1658 reg=self.reg_e,
1659 eta=self.reg_cl,
1660 numItermax=self.max_iter,
1661 numInnerItermax=self.max_inner_iter,
1662 stopInnerThr=self.tol,
1663 verbose=self.verbose,
1664 log=self.log,
1665 )
1666
1667 # deal with the value of log
1668 if self.log:
1669 self.coupling_, self.log_ = returned_
1670 else:
1671 self.coupling_ = returned_
1672 self.log_ = dict()
1673 return self
1674
1675
1676 class EMDLaplaceTransport(BaseTransport):
1677 """Domain Adaptation OT method based on Earth Mover's Distance with Laplacian regularization
1678
1679 Parameters
1680 ----------
1681 reg_type : string optional (default='pos')
1682 Type of the regularization term: 'pos' and 'disp' for
1683 regularization term defined in :ref:`[2] <references-emdlaplacetransport>` and
1684 :ref:`[6] <references-emdlaplacetransport>`, respectively.
1685 reg_lap : float, optional (default=1)
1686 Laplacian regularization parameter
1687 reg_src : float, optional (default=0.5)
1688 Source relative importance in regularization
1689 metric : string, optional (default="sqeuclidean")
1690 The ground metric for the Wasserstein problem
1691 norm : string, optional (default=None)
1692 If given, normalize the ground metric to avoid numerical errors that
1693 can occur with large metric values.
1694 similarity : string, optional (default="knn")
1695 The similarity to use either knn or gaussian
1696 similarity_param : int or float, optional (default=None)
1697 Parameter for the similarity: number of nearest neighbors or bandwidth
1698 if similarity="knn" or "gaussian", respectively. If None is provided,
1699 it is set to 3 or the average pairwise squared Euclidean distance, respectively.
1700 max_iter : int, optional (default=100)
1701 Max number of BCD iterations
1702 tol : float, optional (default=1e-5)
1703 Stop threshold on relative loss decrease (>0)
1704 max_inner_iter : int, optional (default=10)
1705 Max number of iterations (inner CG solver)
1706 inner_tol : float, optional (default=1e-6)
1707 Stop threshold on error (inner CG solver) (>0)
1708 log : int, optional (default=False)
1709 Controls the logs of the optimization algorithm
1710 distribution_estimation : callable, optional (defaults to the uniform)
1711 The kind of distribution estimation to employ
1712 out_of_sample_map : string, optional (default="ferradans")
1713 The kind of out of sample mapping to apply to transport samples
1714 from a domain into another one. Currently the only possible option is
1715 "ferradans" which uses the method proposed in :ref:`[6] <references-emdlaplacetransport>`.
1716
1717 Attributes
1718 ----------
1719 coupling_ : array-like, shape (n_source_samples, n_target_samples)
1720 The optimal coupling
1721
1722
1723 .. _references-emdlaplacetransport:
1724 References
1725 ----------
1726 .. [1] N. Courty; R. Flamary; D. Tuia; A. Rakotomamonjy,
1727 "Optimal Transport for Domain Adaptation," in IEEE Transactions
1728 on Pattern Analysis and Machine Intelligence , vol.PP, no.99, pp.1-1
1729
1730 .. [2] R. Flamary, N. Courty, D. Tuia, A. Rakotomamonjy,
1731 "Optimal transport with Laplacian regularization: Applications to domain adaptation and shape matching,"
1732 in NIPS Workshop on Optimal Transport and Machine Learning OTML, 2014.
1733
1734 .. [6] Ferradans, S., Papadakis, N., Peyré, G., & Aujol, J. F. (2014).
1735 Regularized discrete optimal transport. SIAM Journal on Imaging Sciences, 7(3), 1853-1882.
1736 """
1737
1738 def __init__(
1739 self,
1740 reg_type="pos",
1741 reg_lap=1.0,
1742 reg_src=1.0,
1743 metric="sqeuclidean",
1744 norm=None,
1745 similarity="knn",
1746 similarity_param=None,
1747 max_iter=100,
1748 tol=1e-9,
1749 max_inner_iter=100000,
1750 inner_tol=1e-9,
1751 log=False,
1752 verbose=False,
1753 distribution_estimation=distribution_estimation_uniform,
1754 out_of_sample_map="ferradans",
1755 ):
1756 self.reg = reg_type
1757 self.reg_lap = reg_lap
1758 self.reg_src = reg_src
1759 self.metric = metric
1760 self.norm = norm
1761 self.similarity = similarity
1762 self.sim_param = similarity_param
1763 self.max_iter = max_iter
1764 self.tol = tol
1765 self.max_inner_iter = max_inner_iter
1766 self.inner_tol = inner_tol
1767 self.log = log
1768 self.verbose = verbose
1769 self.distribution_estimation = distribution_estimation
1770 self.out_of_sample_map = out_of_sample_map
1771
1772 def fit(self, Xs, ys=None, Xt=None, yt=None):
1773 r"""Build a coupling matrix from source and target sets of samples
1774 :math:`(\mathbf{X_s}, \mathbf{y_s})` and :math:`(\mathbf{X_t}, \mathbf{y_t})`
1775
1776 Parameters
1777 ----------
1778 Xs : array-like, shape (n_source_samples, n_features)
1779 The training input samples.
1780 ys : array-like, shape (n_source_samples,)
1781 The class labels
1782 Xt : array-like, shape (n_target_samples, n_features)
1783 The training input samples.
1784 yt : array-like, shape (n_target_samples,)
1785 The class labels. If some target samples are unlabelled, fill the
1786 :math:`\mathbf{y_t}`'s elements with -1.
1787
1788 Warning: Note that, due to this convention -1 cannot be used as a
1789 class label
1790
1791 Returns
1792 -------
1793 self : object
1794 Returns self.
1795 """
1796
1797 super(EMDLaplaceTransport, self).fit(Xs, ys, Xt, yt)
1798
1799 returned_ = emd_laplace(
1800 a=self.mu_s,
1801 b=self.mu_t,
1802 xs=self.xs_,
1803 xt=self.xt_,
1804 M=self.cost_,
1805 sim=self.similarity,
1806 sim_param=self.sim_param,
1807 reg=self.reg,
1808 eta=self.reg_lap,
1809 alpha=self.reg_src,
1810 numItermax=self.max_iter,
1811 stopThr=self.tol,
1812 numInnerItermax=self.max_inner_iter,
1813 stopInnerThr=self.inner_tol,
1814 log=self.log,
1815 verbose=self.verbose,
1816 )
1817
1818 # coupling estimation
1819 if self.log:
1820 self.coupling_, self.log_ = returned_
1821 else:
1822 self.coupling_ = returned_
1823 self.log_ = dict()
1824 return self
1825
1826
1827 class SinkhornL1l2Transport(BaseTransport):
1828 """Domain Adaptation OT method based on sinkhorn algorithm +
1829 L1L2 class regularization.
1830
1831 Parameters
1832 ----------
1833 reg_e : float, optional (default=1)
1834 Entropic regularization parameter
1835 reg_cl : float, optional (default=0.1)
1836 Class regularization parameter
1837 max_iter : int, float, optional (default=10)
1838 The minimum number of iteration before stopping the optimization
1839 algorithm if it has not converged
1840 max_inner_iter : int, float, optional (default=200)
1841 The number of iteration in the inner loop
1842 tol : float, optional (default=10e-9)
1843 Stop threshold on error (inner sinkhorn solver) (>0)
1844 verbose : bool, optional (default=False)
1845 Controls the verbosity of the optimization algorithm
1846 log : bool, optional (default=False)
1847 Controls the logs of the optimization algorithm
1848 metric : string, optional (default="sqeuclidean")
1849 The ground metric for the Wasserstein problem
1850 norm : string, optional (default=None)
1851 If given, normalize the ground metric to avoid numerical errors that
1852 can occur with large metric values.
1853 distribution_estimation : callable, optional (defaults to the uniform)
1854 The kind of distribution estimation to employ
1855 out_of_sample_map : string, optional (default="ferradans")
1856 The kind of out of sample mapping to apply to transport samples
1857 from a domain into another one. Currently the only possible option is
1858 "ferradans" which uses the method proposed in :ref:`[6] <references-sinkhornl1l2transport>`.
1859 limit_max: float, optional (default=10)
1860 Controls the semi supervised mode. Transport between labeled source
1861 and target samples of different classes will exhibit an infinite cost
1862 (10 times the maximum value of the cost matrix)
1863
1864 Attributes
1865 ----------
1866 coupling_ : array-like, shape (n_source_samples, n_target_samples)
1867 The optimal coupling
1868 log_ : dictionary
1869 The dictionary of log, empty dict if parameter log is not True
1870
1871
1872 .. _references-sinkhornl1l2transport:
1873 References
1874 ----------
1875 .. [1] N. Courty; R. Flamary; D. Tuia; A. Rakotomamonjy,
1876 "Optimal Transport for Domain Adaptation," in IEEE
1877 Transactions on Pattern Analysis and Machine Intelligence ,
1878 vol.PP, no.99, pp.1-1
1879
1880 .. [2] Rakotomamonjy, A., Flamary, R., & Courty, N. (2015).
1881 Generalized conditional gradient: analysis of convergence
1882 and applications. arXiv preprint arXiv:1510.06567.
1883
1884 .. [6] Ferradans, S., Papadakis, N., Peyré, G., & Aujol, J. F. (2014).
1885 Regularized discrete optimal transport. SIAM Journal on Imaging
1886 Sciences, 7(3), 1853-1882.
1887 """
1888
1889 def __init__(
1890 self,
1891 reg_e=1.0,
1892 reg_cl=0.1,
1893 max_iter=10,
1894 max_inner_iter=200,
1895 tol=10e-9,
1896 verbose=False,
1897 log=False,
1898 metric="sqeuclidean",
1899 norm=None,
1900 distribution_estimation=distribution_estimation_uniform,
1901 out_of_sample_map="ferradans",
1902 limit_max=10,
1903 ):
1904 self.reg_e = reg_e
1905 self.reg_cl = reg_cl
1906 self.max_iter = max_iter
1907 self.max_inner_iter = max_inner_iter
1908 self.tol = tol
1909 self.verbose = verbose
1910 self.log = log
1911 self.metric = metric
1912 self.norm = norm
1913 self.distribution_estimation = distribution_estimation
1914 self.out_of_sample_map = out_of_sample_map
1915 self.limit_max = limit_max
1916
1917 def fit(self, Xs, ys=None, Xt=None, yt=None):
1918 r"""Build a coupling matrix from source and target sets of samples
1919 :math:`(\mathbf{X_s}, \mathbf{y_s})` and :math:`(\mathbf{X_t}, \mathbf{y_t})`
1920
1921 Parameters
1922 ----------
1923 Xs : array-like, shape (n_source_samples, n_features)
1924 The training input samples.
1925 ys : array-like, shape (n_source_samples,)
1926 The class labels
1927 Xt : array-like, shape (n_target_samples, n_features)
1928 The training input samples.
1929 yt : array-like, shape (n_target_samples,)
1930 The class labels. If some target samples are unlabelled, fill the
1931 :math:`\mathbf{y_t}`'s elements with -1.
1932
1933 Warning: Note that, due to this convention -1 cannot be used as a
1934 class label
1935
1936 Returns
1937 -------
1938 self : object
1939 Returns self.
1940 """
1941
1942 # check the necessary inputs parameters are here
1943 if check_params(Xs=Xs, Xt=Xt, ys=ys):
1944 super(SinkhornL1l2Transport, self).fit(Xs, ys, Xt, yt)
1945
1946 returned_ = sinkhorn_l1l2_gl(
1947 a=self.mu_s,
1948 labels_a=ys,
1949 b=self.mu_t,
1950 M=self.cost_,
1951 reg=self.reg_e,
1952 eta=self.reg_cl,
1953 numItermax=self.max_iter,
1954 numInnerItermax=self.max_inner_iter,
1955 stopInnerThr=self.tol,
1956 verbose=self.verbose,
1957 log=self.log,
1958 )
1959
1960 # deal with the value of log
1961 if self.log:
1962 self.coupling_, self.log_ = returned_
1963 else:
1964 self.coupling_ = returned_
1965 self.log_ = dict()
1966
1967 return self
1968
1969
1970 class MappingTransport(BaseEstimator):
1971 """MappingTransport: DA methods that aims at jointly estimating a optimal
1972 transport coupling and the associated mapping
1973
1974 Parameters
1975 ----------
1976 mu : float, optional (default=1)
1977 Weight for the linear OT loss (>0)
1978 eta : float, optional (default=0.001)
1979 Regularization term for the linear mapping `L` (>0)
1980 bias : bool, optional (default=False)
1981 Estimate linear mapping with constant bias
1982 metric : string, optional (default="sqeuclidean")
1983 The ground metric for the Wasserstein problem
1984 norm : string, optional (default=None)
1985 If given, normalize the ground metric to avoid numerical errors that
1986 can occur with large metric values.
1987 kernel : string, optional (default="linear")
1988 The kernel to use either linear or gaussian
1989 sigma : float, optional (default=1)
1990 The gaussian kernel parameter
1991 max_iter : int, optional (default=100)
1992 Max number of BCD iterations
1993 tol : float, optional (default=1e-5)
1994 Stop threshold on relative loss decrease (>0)
1995 max_inner_iter : int, optional (default=10)
1996 Max number of iterations (inner CG solver)
1997 inner_tol : float, optional (default=1e-6)
1998 Stop threshold on error (inner CG solver) (>0)
1999 log : bool, optional (default=False)
2000 record log if True
2001 verbose : bool, optional (default=False)
2002 Print information along iterations
2003 verbose2 : bool, optional (default=False)
2004 Print information along iterations
2005
2006 Attributes
2007 ----------
2008 coupling_ : array-like, shape (n_source_samples, n_target_samples)
2009 The optimal coupling
2010 mapping_ :
2011 The associated mapping
2012
2013 - array-like, shape (`n_features` (+ 1), `n_features`),
2014 (if bias) for kernel == linear
2015
2016 - array-like, shape (`n_source_samples` (+ 1), `n_features`),
2017 (if bias) for kernel == gaussian
2018 log_ : dictionary
2019 The dictionary of log, empty dict if parameter log is not True
2020
2021
2022 References
2023 ----------
2024 .. [8] M. Perrot, N. Courty, R. Flamary, A. Habrard,
2025 "Mapping estimation for discrete optimal transport",
2026 Neural Information Processing Systems (NIPS), 2016.
2027
2028 """
2029
2030 def __init__(
2031 self,
2032 mu=1,
2033 eta=0.001,
2034 bias=False,
2035 metric="sqeuclidean",
2036 norm=None,
2037 kernel="linear",
2038 sigma=1,
2039 max_iter=100,
2040 tol=1e-5,
2041 max_inner_iter=10,
2042 inner_tol=1e-6,
2043 log=False,
2044 verbose=False,
2045 verbose2=False,
2046 ):
2047 self.metric = metric
2048 self.norm = norm
2049 self.mu = mu
2050 self.eta = eta
2051 self.bias = bias
2052 self.kernel = kernel
2053 self.sigma = sigma
2054 self.max_iter = max_iter
2055 self.tol = tol
2056 self.max_inner_iter = max_inner_iter
2057 self.inner_tol = inner_tol
2058 self.log = log
2059 self.verbose = verbose
2060 self.verbose2 = verbose2
2061
2062 def fit(self, Xs=None, ys=None, Xt=None, yt=None):
2063 r"""Builds an optimal coupling and estimates the associated mapping
2064 from source and target sets of samples
2065 :math:`(\mathbf{X_s}, \mathbf{y_s})` and :math:`(\mathbf{X_t}, \mathbf{y_t})`
2066
2067 Parameters
2068 ----------
2069 Xs : array-like, shape (n_source_samples, n_features)
2070 The training input samples.
2071 ys : array-like, shape (n_source_samples,)
2072 The class labels
2073 Xt : array-like, shape (n_target_samples, n_features)
2074 The training input samples.
2075 yt : array-like, shape (n_target_samples,)
2076 The class labels. If some target samples are unlabelled, fill the
2077 :math:`\mathbf{y_t}`'s elements with -1.
2078
2079 Warning: Note that, due to this convention -1 cannot be used as a
2080 class label
2081
2082 Returns
2083 -------
2084 self : object
2085 Returns self
2086 """
2087 self._get_backend(Xs, ys, Xt, yt)
2088
2089 # check the necessary inputs parameters are here
2090 if check_params(Xs=Xs, Xt=Xt):
2091 self.xs_ = Xs
2092 self.xt_ = Xt
2093
2094 if self.kernel == "linear":
2095 returned_ = joint_OT_mapping_linear(
2096 Xs,
2097 Xt,
2098 mu=self.mu,
2099 eta=self.eta,
2100 bias=self.bias,
2101 verbose=self.verbose,
2102 verbose2=self.verbose2,
2103 numItermax=self.max_iter,
2104 numInnerItermax=self.max_inner_iter,
2105 stopThr=self.tol,
2106 stopInnerThr=self.inner_tol,
2107 log=self.log,
2108 )
2109
2110 elif self.kernel == "gaussian":
2111 returned_ = joint_OT_mapping_kernel(
2112 Xs,
2113 Xt,
2114 mu=self.mu,
2115 eta=self.eta,
2116 bias=self.bias,
2117 sigma=self.sigma,
2118 verbose=self.verbose,
2119 verbose2=self.verbose,
2120 numItermax=self.max_iter,
2121 numInnerItermax=self.max_inner_iter,
2122 stopInnerThr=self.inner_tol,
2123 stopThr=self.tol,
2124 log=self.log,
2125 )
2126
2127 # deal with the value of log
2128 if self.log:
2129 self.coupling_, self.mapping_, self.log_ = returned_
2130 else:
2131 self.coupling_, self.mapping_ = returned_
2132 self.log_ = dict()
2133
2134 return self
2135
2136 def transform(self, Xs):
2137 r"""Transports source samples :math:`\mathbf{X_s}` onto target ones :math:`\mathbf{X_t}`
2138
2139 Parameters
2140 ----------
2141 Xs : array-like, shape (n_source_samples, n_features)
2142 The training input samples.
2143
2144 Returns
2145 -------
2146 transp_Xs : array-like, shape (n_source_samples, n_features)
2147 The transport source samples.
2148 """
2149 nx = self.nx
2150
2151 # check the necessary inputs parameters are here
2152 if check_params(Xs=Xs):
2153 if nx.array_equal(self.xs_, Xs):
2154 # perform standard barycentric mapping
2155 transp = self.coupling_ / nx.sum(self.coupling_, 1)[:, None]
2156
2157 # set nans to 0
2158 transp = nx.nan_to_num(transp, nan=0, posinf=0, neginf=0)
2159
2160 # compute transported samples
2161 transp_Xs = nx.dot(transp, self.xt_)
2162 else:
2163 if self.kernel == "gaussian":
2164 K = kernel(Xs, self.xs_, method=self.kernel, sigma=self.sigma)
2165 elif self.kernel == "linear":
2166 K = Xs
2167 if self.bias:
2168 K = nx.concatenate(
2169 [K, nx.ones((Xs.shape[0], 1), type_as=K)], axis=1
2170 )
2171 transp_Xs = nx.dot(K, self.mapping_)
2172
2173 return transp_Xs
2174
2175
2176 class UnbalancedSinkhornTransport(BaseTransport):
2177 """Domain Adaptation unbalanced OT method based on sinkhorn algorithm
2178
2179 Parameters
2180 ----------
2181 reg_e : float, optional (default=1)
2182 Entropic regularization parameter
2183 reg_m : float, optional (default=0.1)
2184 Mass regularization parameter
2185 method : str
2186 method used for the solver either 'sinkhorn', 'sinkhorn_stabilized' or
2187 'sinkhorn_epsilon_scaling', see those function for specific parameters
2188 max_iter : int, float, optional (default=10)
2189 The minimum number of iteration before stopping the optimization
2190 algorithm if it has not converged
2191 tol : float, optional (default=10e-9)
2192 Stop threshold on error (inner sinkhorn solver) (>0)
2193 verbose : bool, optional (default=False)
2194 Controls the verbosity of the optimization algorithm
2195 log : bool, optional (default=False)
2196 Controls the logs of the optimization algorithm
2197 metric : string, optional (default="sqeuclidean")
2198 The ground metric for the Wasserstein problem
2199 norm : string, optional (default=None)
2200 If given, normalize the ground metric to avoid numerical errors that
2201 can occur with large metric values.
2202 distribution_estimation : callable, optional (defaults to the uniform)
2203 The kind of distribution estimation to employ
2204 out_of_sample_map : string, optional (default="ferradans")
2205 The kind of out of sample mapping to apply to transport samples
2206 from a domain into another one. Currently the only possible option is
2207 "ferradans" which uses the method proposed in :ref:`[6] <references-unbalancedsinkhorntransport>`.
2208 limit_max: float, optional (default=10)
2209 Controls the semi supervised mode. Transport between labeled source
2210 and target samples of different classes will exhibit an infinite cost
2211 (10 times the maximum value of the cost matrix)
2212
2213 Attributes
2214 ----------
2215 coupling_ : array-like, shape (n_source_samples, n_target_samples)
2216 The optimal coupling
2217 log_ : dictionary
2218 The dictionary of log, empty dict if parameter log is not True
2219
2220
2221 .. _references-unbalancedsinkhorntransport:
2222 References
2223 ----------
2224 .. [1] Chizat, L., Peyré, G., Schmitzer, B., & Vialard, F. X. (2016).
2225 Scaling algorithms for unbalanced transport problems. arXiv preprint
2226 arXiv:1607.05816.
2227
2228 .. [6] Ferradans, S., Papadakis, N., Peyré, G., & Aujol, J. F. (2014).
2229 Regularized discrete optimal transport. SIAM Journal on Imaging
2230 Sciences, 7(3), 1853-1882.
2231 """
2232
2233 def __init__(
2234 self,
2235 reg_e=1.0,
2236 reg_m=0.1,
2237 method="sinkhorn",
2238 max_iter=10,
2239 tol=1e-9,
2240 verbose=False,
2241 log=False,
2242 metric="sqeuclidean",
2243 norm=None,
2244 distribution_estimation=distribution_estimation_uniform,
2245 out_of_sample_map="ferradans",
2246 limit_max=10,
2247 ):
2248 self.reg_e = reg_e
2249 self.reg_m = reg_m
2250 self.method = method
2251 self.max_iter = max_iter
2252 self.tol = tol
2253 self.verbose = verbose
2254 self.log = log
2255 self.metric = metric
2256 self.norm = norm
2257 self.distribution_estimation = distribution_estimation
2258 self.out_of_sample_map = out_of_sample_map
2259 self.limit_max = limit_max
2260
2261 def fit(self, Xs, ys=None, Xt=None, yt=None):
2262 r"""Build a coupling matrix from source and target sets of samples
2263 :math:`(\mathbf{X_s}, \mathbf{y_s})` and :math:`(\mathbf{X_t}, \mathbf{y_t})`
2264
2265 Parameters
2266 ----------
2267 Xs : array-like, shape (n_source_samples, n_features)
2268 The training input samples.
2269 ys : array-like, shape (n_source_samples,)
2270 The class labels
2271 Xt : array-like, shape (n_target_samples, n_features)
2272 The training input samples.
2273 yt : array-like, shape (n_target_samples,)
2274 The class labels. If some target samples are unlabelled, fill the
2275 :math:`\mathbf{y_t}`'s elements with -1.
2276
2277 Warning: Note that, due to this convention -1 cannot be used as a
2278 class label
2279
2280 Returns
2281 -------
2282 self : object
2283 Returns self.
2284 """
2285
2286 # check the necessary inputs parameters are here
2287 if check_params(Xs=Xs, Xt=Xt):
2288 super(UnbalancedSinkhornTransport, self).fit(Xs, ys, Xt, yt)
2289
2290 returned_ = sinkhorn_unbalanced(
2291 a=self.mu_s,
2292 b=self.mu_t,
2293 M=self.cost_,
2294 reg=self.reg_e,
2295 reg_m=self.reg_m,
2296 method=self.method,
2297 numItermax=self.max_iter,
2298 stopThr=self.tol,
2299 verbose=self.verbose,
2300 log=self.log,
2301 )
2302
2303 # deal with the value of log
2304 if self.log:
2305 self.coupling_, self.log_ = returned_
2306 else:
2307 self.coupling_ = returned_
2308 self.log_ = dict()
2309
2310 return self
2311
2312
2313 class JCPOTTransport(BaseTransport):
2314 """Domain Adaptation OT method for multi-source target shift based on Wasserstein barycenter algorithm.
2315
2316 Parameters
2317 ----------
2318 reg_e : float, optional (default=1)
2319 Entropic regularization parameter
2320 max_iter : int, float, optional (default=10)
2321 The minimum number of iteration before stopping the optimization
2322 algorithm if it has not converged
2323 tol : float, optional (default=10e-9)
2324 Stop threshold on error (inner sinkhorn solver) (>0)
2325 verbose : bool, optional (default=False)
2326 Controls the verbosity of the optimization algorithm
2327 log : bool, optional (default=False)
2328 Controls the logs of the optimization algorithm
2329 metric : string, optional (default="sqeuclidean")
2330 The ground metric for the Wasserstein problem
2331 norm : string, optional (default=None)
2332 If given, normalize the ground metric to avoid numerical errors that
2333 can occur with large metric values.
2334 distribution_estimation : callable, optional (defaults to the uniform)
2335 The kind of distribution estimation to employ
2336 out_of_sample_map : string, optional (default="ferradans")
2337 The kind of out of sample mapping to apply to transport samples
2338 from a domain into another one. Currently the only possible option is
2339 "ferradans" which uses the method proposed in :ref:`[6] <references-jcpottransport>`.
2340
2341 Attributes
2342 ----------
2343 coupling_ : list of array-like objects, shape K x (n_source_samples, n_target_samples)
2344 A set of optimal couplings between each source domain and the target domain
2345 proportions_ : array-like, shape (n_classes,)
2346 Estimated class proportions in the target domain
2347 log_ : dictionary
2348 The dictionary of log, empty dict if parameter log is not True
2349
2350
2351 .. _references-jcpottransport:
2352 References
2353 ----------
2354 .. [1] Ievgen Redko, Nicolas Courty, Rémi Flamary, Devis Tuia
2355 "Optimal transport for multi-source domain adaptation under target shift",
2356 International Conference on Artificial Intelligence and Statistics (AISTATS),
2357 vol. 89, p.849-858, 2019.
2358
2359 .. [6] Ferradans, S., Papadakis, N., Peyré, G., & Aujol, J. F. (2014).
2360 Regularized discrete optimal transport. SIAM Journal on Imaging
2361 Sciences, 7(3), 1853-1882.
2362
2363
2364 """
2365
2366 def __init__(
2367 self,
2368 reg_e=0.1,
2369 max_iter=10,
2370 tol=10e-9,
2371 verbose=False,
2372 log=False,
2373 metric="sqeuclidean",
2374 out_of_sample_map="ferradans",
2375 ):
2376 self.reg_e = reg_e
2377 self.max_iter = max_iter
2378 self.tol = tol
2379 self.verbose = verbose
2380 self.log = log
2381 self.metric = metric
2382 self.out_of_sample_map = out_of_sample_map
2383
2384 def fit(self, Xs, ys=None, Xt=None, yt=None):
2385 r"""Building coupling matrices from a list of source and target sets of samples
2386 :math:`(\mathbf{X_s}, \mathbf{y_s})` and :math:`(\mathbf{X_t}, \mathbf{y_t})`
2387
2388 Parameters
2389 ----------
2390 Xs : list of K array-like objects, shape K x (nk_source_samples, n_features)
2391 A list of the training input samples.
2392 ys : list of K array-like objects, shape K x (nk_source_samples,)
2393 A list of the class labels
2394 Xt : array-like, shape (n_target_samples, n_features)
2395 The training input samples.
2396 yt : array-like, shape (n_target_samples,)
2397 The class labels. If some target samples are unlabelled, fill the
2398 :math:`\mathbf{y_t}`'s elements with -1.
2399
2400 Warning: Note that, due to this convention -1 cannot be used as a
2401 class label
2402
2403 Returns
2404 -------
2405 self : object
2406 Returns self.
2407 """
2408 self._get_backend(*Xs, *ys, Xt, yt)
2409
2410 # check the necessary inputs parameters are here
2411 if check_params(Xs=Xs, Xt=Xt, ys=ys):
2412 self.xs_ = Xs
2413 self.xt_ = Xt
2414
2415 returned_ = jcpot_barycenter(
2416 Xs=Xs,
2417 Ys=ys,
2418 Xt=Xt,
2419 reg=self.reg_e,
2420 metric=self.metric,
2421 distrinumItermax=self.max_iter,
2422 stopThr=self.tol,
2423 verbose=self.verbose,
2424 log=True,
2425 )
2426
2427 self.coupling_ = returned_[1]["gamma"]
2428
2429 # deal with the value of log
2430 if self.log:
2431 self.proportions_, self.log_ = returned_
2432 else:
2433 self.proportions_ = returned_
2434 self.log_ = dict()
2435
2436 return self
2437
2438 def transform(self, Xs=None, ys=None, Xt=None, yt=None, batch_size=128):
2439 r"""Transports source samples :math:`\mathbf{X_s}` onto target ones :math:`\mathbf{X_t}`
2440
2441 Parameters
2442 ----------
2443 Xs : list of K array-like objects, shape K x (nk_source_samples, n_features)
2444 A list of the training input samples.
2445 ys : list of K array-like objects, shape K x (nk_source_samples,)
2446 A list of the class labels
2447 Xt : array-like, shape (n_target_samples, n_features)
2448 The training input samples.
2449 yt : array-like, shape (n_target_samples,)
2450 The class labels. If some target samples are unlabelled, fill the
2451 :math:`\mathbf{y_t}`'s elements with -1.
2452
2453 Warning: Note that, due to this convention -1 cannot be used as a
2454 class label
2455 batch_size : int, optional (default=128)
2456 The batch size for out of sample inverse transform
2457 """
2458 nx = self.nx
2459
2460 transp_Xs = []
2461
2462 # check the necessary inputs parameters are here
2463 if check_params(Xs=Xs):
2464 if all([nx.allclose(x, y) for x, y in zip(self.xs_, Xs)]):
2465 # perform standard barycentric mapping for each source domain
2466
2467 for coupling in self.coupling_:
2468 transp = coupling / nx.sum(coupling, 1)[:, None]
2469
2470 # set nans to 0
2471 transp = nx.nan_to_num(transp, nan=0, posinf=0, neginf=0)
2472
2473 # compute transported samples
2474 transp_Xs.append(nx.dot(transp, self.xt_))
2475 else:
2476 # perform out of sample mapping
2477 indices = nx.arange(Xs.shape[0])
2478 batch_ind = [
2479 indices[i : i + batch_size]
2480 for i in range(0, len(indices), batch_size)
2481 ]
2482
2483 transp_Xs = []
2484
2485 for bi in batch_ind:
2486 transp_Xs_ = []
2487
2488 # get the nearest neighbor in the sources domains
2489 xs = nx.concatenate(self.xs_, axis=0)
2490 idx = nx.argmin(dist(Xs[bi], xs), axis=1)
2491
2492 # transport the source samples
2493 for coupling in self.coupling_:
2494 transp = coupling / nx.sum(coupling, 1)[:, None]
2495 transp = nx.nan_to_num(transp, nan=0, posinf=0, neginf=0)
2496 transp_Xs_.append(nx.dot(transp, self.xt_))
2497
2498 transp_Xs_ = nx.concatenate(transp_Xs_, axis=0)
2499
2500 # define the transported points
2501 transp_Xs_ = transp_Xs_[idx, :] + Xs[bi] - xs[idx, :]
2502 transp_Xs.append(transp_Xs_)
2503
2504 transp_Xs = nx.concatenate(transp_Xs, axis=0)
2505
2506 return transp_Xs
2507
2508 def transform_labels(self, ys=None):
2509 r"""Propagate source labels :math:`\mathbf{y_s}` to obtain target labels as in
2510 :ref:`[27] <references-jcpottransport-transform-labels>`
2511
2512 Parameters
2513 ----------
2514 ys : list of K array-like objects, shape K x (nk_source_samples,)
2515 A list of the class labels
2516
2517 Returns
2518 -------
2519 yt : array-like, shape (n_target_samples, nb_classes)
2520 Estimated soft target labels.
2521
2522
2523 .. _references-jcpottransport-transform-labels:
2524 References
2525 ----------
2526 .. [27] Ievgen Redko, Nicolas Courty, Rémi Flamary, Devis Tuia
2527 "Optimal transport for multi-source domain adaptation under target shift",
2528 International Conference on Artificial Intelligence and Statistics (AISTATS), 2019.
2529 """
2530 nx = self.nx
2531
2532 # check the necessary inputs parameters are here
2533 if check_params(ys=ys):
2534 yt = nx.zeros(
2535 (len(nx.unique(nx.concatenate(ys))), self.xt_.shape[0]), type_as=ys[0]
2536 )
2537 for i in range(len(ys)):
2538 ysTemp = label_normalization(ys[i])
2539 classes = nx.unique(ysTemp)
2540 n = len(classes)
2541 ns = len(ysTemp)
2542
2543 # perform label propagation
2544 transp = self.coupling_[i] / nx.sum(self.coupling_[i], 1)[:, None]
2545
2546 # set nans to 0
2547 transp = nx.nan_to_num(transp, nan=0, posinf=0, neginf=0)
2548
2549 if self.log:
2550 D1 = self.log_["D1"][i]
2551 else:
2552 D1 = nx.zeros((n, ns), type_as=transp)
2553
2554 for c in classes:
2555 D1[int(c), ysTemp == c] = 1
2556
2557 # compute propagated labels
2558 yt = yt + nx.dot(D1, transp) / len(ys)
2559
2560 return yt.T
2561
2562 def inverse_transform_labels(self, yt=None):
2563 r"""Propagate target labels :math:`\mathbf{y_t}` to obtain estimated source labels
2564 :math:`\mathbf{y_s}`
2565
2566 Parameters
2567 ----------
2568 yt : array-like, shape (n_target_samples,)
2569 The target class labels
2570
2571 Returns
2572 -------
2573 transp_ys : list of K array-like objects, shape K x (nk_source_samples, nb_classes)
2574 A list of estimated soft source labels
2575 """
2576 nx = self.nx
2577
2578 # check the necessary inputs parameters are here
2579 if check_params(yt=yt):
2580 transp_ys = []
2581 ytTemp = label_normalization(yt)
2582 classes = nx.unique(ytTemp)
2583 n = len(classes)
2584 D1 = nx.zeros((n, len(ytTemp)), type_as=self.coupling_[0])
2585
2586 for c in classes:
2587 D1[int(c), ytTemp == c] = 1
2588
2589 for i in range(len(self.xs_)):
2590 # perform label propagation
2591 transp = self.coupling_[i] / nx.sum(self.coupling_[i], 1)[:, None]
2592
2593 # set nans to 0
2594 transp = nx.nan_to_num(transp, nan=0, posinf=0, neginf=0)
2595
2596 # compute propagated labels
2597 transp_ys.append(nx.dot(D1, transp.T).T)
2598
2599 return transp_ys
2600
2601
2602 class NearestBrenierPotential(BaseTransport):
2603 r"""
2604 Smooth Strongly Convex Nearest Brenier Potentials (SSNB) is a method from :ref:`[58]` that computes
2605 an l-strongly convex potential :math:`\varphi` with an L-Lipschitz gradient such that
2606 :math:`\nabla \varphi \# \mu \approx \nu`. This regularity can be enforced only on the components of a partition
2607 of the ambient space (encoded by point classes), which is a relaxation compared to imposing global regularity.
2608
2609 SSNBs approach the target measure by solving the optimisation problem:
2610
2611 .. math::
2612 :nowrap:
2613
2614 \begin{gather*}
2615 \varphi \in \text{argmin}_{\varphi \in \mathcal{F}}\ \text{W}_2(\nabla \varphi \#\mu_s, \mu_t),
2616 \end{gather*}
2617
2618 where :math:`\mathcal{F}` is the space functions that are on every set :math:`E_k` l-strongly convex
2619 with an L-Lipschitz gradient, given :math:`(E_k)_{k \in [K]}` a partition of the ambient source space.
2620
2621 The problem is solved on "fitting" source and target data via a convex Quadratically Constrained Quadratic Program,
2622 yielding the values :code:`phi` and the gradients :code:`G` at at the source points.
2623 The images of "new" source samples are then found by solving a (simpler) Quadratically Constrained Linear Program
2624 at each point, using the fitting "parameters" :code:`phi` and :code:`G`. We provide two possible images, which
2625 correspond to "lower" and "upper potentials" (:ref:`[59]`, Theorem 3.14). Each of these two images are optimal
2626 solutions of the SSNB problem, and can be used in practice.
2627
2628 .. warning:: This function requires the CVXPY library
2629 .. warning:: Accepts any backend but will convert to Numpy then back to the backend.
2630
2631 Parameters
2632 ----------
2633 strongly_convex_constant : float, optional
2634 constant for the strong convexity of the input potential phi, defaults to 0.6
2635 gradient_lipschitz_constant : float, optional
2636 constant for the Lipschitz property of the input gradient G, defaults to 1.4
2637 its: int, optional
2638 number of iterations, defaults to 100
2639 log : bool, optional
2640 record log if true
2641 seed: int or RandomState or None, optional
2642 Seed used for random number generator (for the initialisation in :code:`fit`.
2643
2644 References
2645 ----------
2646
2647 .. [58] François-Pierre Paty, Alexandre d’Aspremont, and Marco Cuturi. Regularity as regularization:
2648 Smooth and strongly convex brenier potentials in optimal transport. In International Conference
2649 on Artificial Intelligence and Statistics, pages 1222–1232. PMLR, 2020.
2650
2651 .. [59] Adrien B Taylor. Convex interpolation and performance estimation of first-order methods for
2652 convex optimization. PhD thesis, Catholic University of Louvain, Louvain-la-Neuve, Belgium,
2653 2017.
2654
2655 See Also
2656 --------
2657 ot.mapping.nearest_brenier_potential_fit : Fitting the SSNB on source and target data
2658 ot.mapping.nearest_brenier_potential_predict_bounds : Predicting SSNB images on new source data
2659 """
2660
2661 def __init__(
2662 self,
2663 strongly_convex_constant=0.6,
2664 gradient_lipschitz_constant=1.4,
2665 log=False,
2666 its=100,
2667 seed=None,
2668 ):
2669 self.strongly_convex_constant = strongly_convex_constant
2670 self.gradient_lipschitz_constant = gradient_lipschitz_constant
2671 self.log = log
2672 self.its = its
2673 self.seed = seed
2674 self.fit_log, self.predict_log = None, None
2675 self.phi, self.G = None, None
2676 self.fit_Xs, self.fit_ys, self.fit_Xt = None, None, None
2677
2678 def fit(self, Xs=None, ys=None, Xt=None, yt=None):
2679 r"""
2680 Fits the Smooth Strongly Convex Nearest Brenier Potential [58] to the source data :code:`Xs` to the target data
2681 :code:`Xt`, with the partition given by the (optional) labels :code:`ys`.
2682
2683 Wrapper for :code:`ot.mapping.nearest_brenier_potential_fit`.
2684
2685 .. warning:: This function requires the CVXPY library
2686 .. warning:: Accepts any backend but will convert to Numpy then back to the backend.
2687
2688 Parameters
2689 ----------
2690 Xs : array-like (n, d)
2691 source points used to compute the optimal values phi and G
2692 ys : array-like (n,), optional
2693 classes of the reference points, defaults to a single class
2694 Xt : array-like (n, d)
2695 values of the gradients at the reference points X
2696 yt : optional
2697 ignored.
2698
2699 Returns
2700 -------
2701 self : object
2702 Returns self.
2703
2704 References
2705 ----------
2706
2707 .. [58] François-Pierre Paty, Alexandre d’Aspremont, and Marco Cuturi. Regularity as regularization:
2708 Smooth and strongly convex brenier potentials in optimal transport. In International Conference
2709 on Artificial Intelligence and Statistics, pages 1222–1232. PMLR, 2020.
2710
2711 See Also
2712 --------
2713 ot.mapping.nearest_brenier_potential_fit : Fitting the SSNB on source and target data
2714
2715 """
2716 self.fit_Xs, self.fit_ys, self.fit_Xt = Xs, ys, Xt
2717 returned = nearest_brenier_potential_fit(
2718 Xs,
2719 Xt,
2720 X_classes=ys,
2721 strongly_convex_constant=self.strongly_convex_constant,
2722 gradient_lipschitz_constant=self.gradient_lipschitz_constant,
2723 its=self.its,
2724 log=self.log,
2725 )
2726
2727 if self.log:
2728 self.phi, self.G, self.fit_log = returned
2729 else:
2730 self.phi, self.G = returned
2731
2732 return self
2733
2734 def transform(self, Xs, ys=None):
2735 r"""
2736 Computes the images of the new source samples :code:`Xs` of classes :code:`ys` by the fitted
2737 Smooth Strongly Convex Nearest Brenier Potentials (SSNB) :ref:`[58]`. The output is the images of two SSNB optimal
2738 maps, called 'lower' and 'upper' potentials (from :ref:`[59]`, Theorem 3.14).
2739
2740 Wrapper for :code:`nearest_brenier_potential_predict_bounds`.
2741
2742 .. warning:: This function requires the CVXPY library
2743 .. warning:: Accepts any backend but will convert to Numpy then back to the backend.
2744
2745 Parameters
2746 ----------
2747 Xs : array-like (m, d)
2748 input source points
2749 ys : : array_like (m,), optional
2750 classes of the input source points, defaults to a single class
2751
2752 Returns
2753 -------
2754 G_lu : array-like (2, m, d)
2755 gradients of the lower and upper bounding potentials at Y (images of the source inputs)
2756
2757 References
2758 ----------
2759
2760 .. [58] François-Pierre Paty, Alexandre d’Aspremont, and Marco Cuturi. Regularity as regularization:
2761 Smooth and strongly convex brenier potentials in optimal transport. In International Conference
2762 on Artificial Intelligence and Statistics, pages 1222–1232. PMLR, 2020.
2763
2764 .. [59] Adrien B Taylor. Convex interpolation and performance estimation of first-order methods for
2765 convex optimization. PhD thesis, Catholic University of Louvain, Louvain-la-Neuve, Belgium,
2766 2017.
2767
2768 See Also
2769 --------
2770 ot.mapping.nearest_brenier_potential_predict_bounds : Predicting SSNB images on new source data
2771
2772 """
2773 returned = nearest_brenier_potential_predict_bounds(
2774 self.fit_Xs,
2775 self.phi,
2776 self.G,
2777 Xs,
2778 X_classes=self.fit_ys,
2779 Y_classes=ys,
2780 strongly_convex_constant=self.strongly_convex_constant,
2781 gradient_lipschitz_constant=self.gradient_lipschitz_constant,
2782 log=self.log,
2783 )
2784 if self.log:
2785 _, G_lu, self.predict_log = returned
2786 else:
2787 _, G_lu = returned
2788 return G_lu