Debian Codegraph @

ot/coot.py

raw symbols SCIP
1 # -*- coding: utf-8 -*-
2 """
3 CO-Optimal Transport solver
4 """
5
6 # Author: Quang Huy Tran <[email protected]>
7 #
8 # License: MIT License
9
10 import warnings
11 from .lp import emd
12 from .utils import list_to_array
13 from .backend import get_backend
14 from .bregman import sinkhorn
15
16
17 def co_optimal_transport(
18 X,
19 Y,
20 wx_samp=None,
21 wx_feat=None,
22 wy_samp=None,
23 wy_feat=None,
24 epsilon=0,
25 alpha=0,
26 M_samp=None,
27 M_feat=None,
28 warmstart=None,
29 nits_bcd=100,
30 tol_bcd=1e-7,
31 eval_bcd=1,
32 nits_ot=500,
33 tol_sinkhorn=1e-7,
34 method_sinkhorn="sinkhorn",
35 early_stopping_tol=1e-6,
36 log=False,
37 verbose=False,
38 ):
39 r"""Compute the CO-Optimal Transport between two matrices.
40
41 Return the sample and feature transport plans between
42 :math:`(\mathbf{X}, \mathbf{w}_{xs}, \mathbf{w}_{xf})` and
43 :math:`(\mathbf{Y}, \mathbf{w}_{ys}, \mathbf{w}_{yf})`.
44
45 The function solves the following CO-Optimal Transport (COOT) problem:
46
47 .. math::
48 \mathbf{COOT}_{\alpha, \varepsilon} = \mathop{\arg \min}_{\mathbf{P}, \mathbf{Q}}
49 &\quad \sum_{i,j,k,l}
50 (\mathbf{X}_{i,k} - \mathbf{Y}_{j,l})^2 \mathbf{P}_{i,j} \mathbf{Q}_{k,l}
51 + \alpha_s \sum_{i,j} \mathbf{P}_{i,j} \mathbf{M^{(s)}}_{i, j} \\
52 &+ \alpha_f \sum_{k, l} \mathbf{Q}_{k,l} \mathbf{M^{(f)}}_{k, l}
53 + \varepsilon_s \mathbf{KL}(\mathbf{P} | \mathbf{w}_{xs} \mathbf{w}_{ys}^T)
54 + \varepsilon_f \mathbf{KL}(\mathbf{Q} | \mathbf{w}_{xf} \mathbf{w}_{yf}^T)
55
56 Where :
57
58 - :math:`\mathbf{X}`: Data matrix in the source space
59 - :math:`\mathbf{Y}`: Data matrix in the target space
60 - :math:`\mathbf{M^{(s)}}`: Additional sample matrix
61 - :math:`\mathbf{M^{(f)}}`: Additional feature matrix
62 - :math:`\mathbf{w}_{xs}`: Distribution of the samples in the source space
63 - :math:`\mathbf{w}_{xf}`: Distribution of the features in the source space
64 - :math:`\mathbf{w}_{ys}`: Distribution of the samples in the target space
65 - :math:`\mathbf{w}_{yf}`: Distribution of the features in the target space
66
67 .. note:: This function allows epsilon to be zero.
68 In that case, the :any:`ot.lp.emd` solver of POT will be used.
69
70 Parameters
71 ----------
72 X : (n_sample_x, n_feature_x) array-like, float
73 First input matrix.
74 Y : (n_sample_y, n_feature_y) array-like, float
75 Second input matrix.
76 wx_samp : (n_sample_x, ) array-like, float, optional (default = None)
77 Histogram assigned on rows (samples) of matrix X.
78 Uniform distribution by default.
79 wx_feat : (n_feature_x, ) array-like, float, optional (default = None)
80 Histogram assigned on columns (features) of matrix X.
81 Uniform distribution by default.
82 wy_samp : (n_sample_y, ) array-like, float, optional (default = None)
83 Histogram assigned on rows (samples) of matrix Y.
84 Uniform distribution by default.
85 wy_feat : (n_feature_y, ) array-like, float, optional (default = None)
86 Histogram assigned on columns (features) of matrix Y.
87 Uniform distribution by default.
88 epsilon : scalar or indexable object of length 2, float or int, optional (default = 0)
89 Regularization parameters for entropic approximation of sample and feature couplings.
90 Allow the case where epsilon contains 0. In that case, the EMD solver is used instead of
91 Sinkhorn solver. If epsilon is scalar, then the same epsilon is applied to
92 both regularization of sample and feature couplings.
93 alpha : scalar or indexable object of length 2, float or int, optional (default = 0)
94 Coefficient parameter of linear terms with respect to the sample and feature couplings.
95 If alpha is scalar, then the same alpha is applied to both linear terms.
96 M_samp : (n_sample_x, n_sample_y), float, optional (default = None)
97 Sample matrix with respect to the linear term on sample coupling.
98 M_feat : (n_feature_x, n_feature_y), float, optional (default = None)
99 Feature matrix with respect to the linear term on feature coupling.
100 warmstart : dictionary, optional (default = None)
101 Contains 4 keys:
102 - "duals_sample" and "duals_feature" whose values are
103 tuples of 2 vectors of size (n_sample_x, n_sample_y) and (n_feature_x, n_feature_y).
104 Initialization of sample and feature dual vectors
105 if using Sinkhorn algorithm. Zero vectors by default.
106
107 - "pi_sample" and "pi_feature" whose values are matrices
108 of size (n_sample_x, n_sample_y) and (n_feature_x, n_feature_y).
109 Initialization of sample and feature couplings.
110 Uniform distributions by default.
111 nits_bcd : int, optional (default = 100)
112 Number of Block Coordinate Descent (BCD) iterations to solve COOT.
113 tol_bcd : float, optional (default = 1e-7)
114 Tolerance of BCD scheme. If the L1-norm between the current and previous
115 sample couplings is under this threshold, then stop BCD scheme.
116 eval_bcd : int, optional (default = 1)
117 Multiplier of iteration at which the COOT cost is evaluated. For example,
118 if `eval_bcd = 8`, then the cost is calculated at iterations 8, 16, 24, etc...
119 nits_ot : int, optional (default = 100)
120 Number of iterations to solve each of the
121 two optimal transport problems in each BCD iteration.
122 tol_sinkhorn : float, optional (default = 1e-7)
123 Tolerance of Sinkhorn algorithm to stop the Sinkhorn scheme for
124 entropic optimal transport problem (if any) in each BCD iteration.
125 Only triggered when Sinkhorn solver is used.
126 method_sinkhorn : string, optional (default = "sinkhorn")
127 Method used in POT's `ot.sinkhorn` solver.
128 Only support "sinkhorn" and "sinkhorn_log".
129 early_stopping_tol : float, optional (default = 1e-6)
130 Tolerance for the early stopping. If the absolute difference between
131 the last 2 recorded COOT distances is under this tolerance, then stop BCD scheme.
132 log : bool, optional (default = False)
133 If True then the cost and 4 dual vectors, including
134 2 from sample and 2 from feature couplings, are recorded.
135 verbose : bool, optional (default = False)
136 If True then print the COOT cost at every multiplier of `eval_bcd`-th iteration.
137
138 Returns
139 -------
140 pi_samp : (n_sample_x, n_sample_y) array-like, float
141 Sample coupling matrix.
142 pi_feat : (n_feature_x, n_feature_y) array-like, float
143 Feature coupling matrix.
144 log : dictionary, optional
145 Returned if `log` is True. The keys are:
146 duals_sample : (n_sample_x, n_sample_y) tuple, float
147 Pair of dual vectors when solving OT problem w.r.t the sample coupling.
148 duals_feature : (n_feature_x, n_feature_y) tuple, float
149 Pair of dual vectors when solving OT problem w.r.t the feature coupling.
150 distances : list, float
151 List of COOT distances.
152
153 References
154 ----------
155 .. [49] I. Redko, T. Vayer, R. Flamary, and N. Courty, CO-Optimal Transport,
156 Advances in Neural Information Processing ny_sampstems, 33 (2020).
157 """
158
159 # Main function
160
161 if method_sinkhorn not in ["sinkhorn", "sinkhorn_log"]:
162 raise ValueError(
163 "Method {} is not supported in CO-Optimal Transport.".format(
164 method_sinkhorn
165 )
166 )
167
168 X, Y = list_to_array(X, Y)
169 nx = get_backend(X, Y)
170
171 if isinstance(epsilon, float) or isinstance(epsilon, int):
172 eps_samp, eps_feat = epsilon, epsilon
173 else:
174 if len(epsilon) != 2:
175 raise ValueError(
176 "Epsilon must be either a scalar or an indexable object of length 2."
177 )
178 else:
179 eps_samp, eps_feat = epsilon[0], epsilon[1]
180
181 if isinstance(alpha, float) or isinstance(alpha, int):
182 alpha_samp, alpha_feat = alpha, alpha
183 else:
184 if len(alpha) != 2:
185 raise ValueError(
186 "Alpha must be either a scalar or an indexable object of length 2."
187 )
188 else:
189 alpha_samp, alpha_feat = alpha[0], alpha[1]
190
191 # constant input variables
192 if M_samp is None or alpha_samp == 0:
193 M_samp, alpha_samp = 0, 0
194 if M_feat is None or alpha_feat == 0:
195 M_feat, alpha_feat = 0, 0
196
197 nx_samp, nx_feat = X.shape
198 ny_samp, ny_feat = Y.shape
199
200 # measures on rows and columns
201 if wx_samp is None:
202 wx_samp = nx.ones(nx_samp, type_as=X) / nx_samp
203 if wx_feat is None:
204 wx_feat = nx.ones(nx_feat, type_as=X) / nx_feat
205 if wy_samp is None:
206 wy_samp = nx.ones(ny_samp, type_as=Y) / ny_samp
207 if wy_feat is None:
208 wy_feat = nx.ones(ny_feat, type_as=Y) / ny_feat
209
210 wxy_samp = wx_samp[:, None] * wy_samp[None, :]
211 wxy_feat = wx_feat[:, None] * wy_feat[None, :]
212
213 # pre-calculate cost constants
214 XY_sqr = (X**2 @ wx_feat)[:, None] + (Y**2 @ wy_feat)[None, :] + alpha_samp * M_samp
215 XY_sqr_T = (
216 ((X.T) ** 2 @ wx_samp)[:, None]
217 + ((Y.T) ** 2 @ wy_samp)[None, :]
218 + alpha_feat * M_feat
219 )
220
221 # initialize coupling and dual vectors
222 if warmstart is None:
223 pi_samp, pi_feat = (
224 wxy_samp,
225 wxy_feat,
226 ) # shape nx_samp x ny_samp and nx_feat x ny_feat
227 duals_samp = (
228 nx.zeros(nx_samp, type_as=X),
229 nx.zeros(ny_samp, type_as=Y),
230 ) # shape nx_samp, ny_samp
231 duals_feat = (
232 nx.zeros(nx_feat, type_as=X),
233 nx.zeros(ny_feat, type_as=Y),
234 ) # shape nx_feat, ny_feat
235 else:
236 pi_samp, pi_feat = warmstart["pi_sample"], warmstart["pi_feature"]
237 duals_samp, duals_feat = warmstart["duals_sample"], warmstart["duals_feature"]
238
239 # initialize log
240 list_coot = [float("inf")]
241 err = tol_bcd + 1e-3
242
243 for idx in range(nits_bcd):
244 pi_samp_prev = nx.copy(pi_samp)
245
246 # update sample coupling
247 ot_cost = XY_sqr - 2 * X @ pi_feat @ Y.T # size nx_samp x ny_samp
248 if eps_samp > 0:
249 pi_samp, dict_log = sinkhorn(
250 a=wx_samp,
251 b=wy_samp,
252 M=ot_cost,
253 reg=eps_samp,
254 method=method_sinkhorn,
255 numItermax=nits_ot,
256 stopThr=tol_sinkhorn,
257 log=True,
258 warmstart=duals_samp,
259 )
260 duals_samp = (nx.log(dict_log["u"]), nx.log(dict_log["v"]))
261 elif eps_samp == 0:
262 pi_samp, dict_log = emd(
263 a=wx_samp, b=wy_samp, M=ot_cost, numItermax=nits_ot, log=True
264 )
265 duals_samp = (dict_log["u"], dict_log["v"])
266 # update feature coupling
267 ot_cost = XY_sqr_T - 2 * X.T @ pi_samp @ Y # size nx_feat x ny_feat
268 if eps_feat > 0:
269 pi_feat, dict_log = sinkhorn(
270 a=wx_feat,
271 b=wy_feat,
272 M=ot_cost,
273 reg=eps_feat,
274 method=method_sinkhorn,
275 numItermax=nits_ot,
276 stopThr=tol_sinkhorn,
277 log=True,
278 warmstart=duals_feat,
279 )
280 duals_feat = (nx.log(dict_log["u"]), nx.log(dict_log["v"]))
281 elif eps_feat == 0:
282 pi_feat, dict_log = emd(
283 a=wx_feat, b=wy_feat, M=ot_cost, numItermax=nits_ot, log=True
284 )
285 duals_feat = (dict_log["u"], dict_log["v"])
286
287 if idx % eval_bcd == 0:
288 # update error
289 err = nx.sum(nx.abs(pi_samp - pi_samp_prev))
290
291 # COOT part
292 coot = nx.sum(ot_cost * pi_feat)
293 if alpha_samp != 0:
294 coot = coot + alpha_samp * nx.sum(M_samp * pi_samp)
295 # Entropic part
296 if eps_samp != 0:
297 coot = coot + eps_samp * nx.kl_div(pi_samp, wxy_samp)
298 if eps_feat != 0:
299 coot = coot + eps_feat * nx.kl_div(pi_feat, wxy_feat)
300 list_coot.append(coot)
301
302 if err < tol_bcd or abs(list_coot[-2] - list_coot[-1]) < early_stopping_tol:
303 break
304
305 if verbose:
306 print(
307 "CO-Optimal Transport cost at iteration {}: {}".format(
308 idx + 1, coot
309 )
310 )
311
312 # sanity check
313 if nx.sum(nx.isnan(pi_samp)) > 0 or nx.sum(nx.isnan(pi_feat)) > 0:
314 warnings.warn("There is NaN in coupling.")
315
316 if log:
317 dict_log = {
318 "duals_sample": duals_samp,
319 "duals_feature": duals_feat,
320 "distances": list_coot[1:],
321 }
322
323 return pi_samp, pi_feat, dict_log
324
325 else:
326 return pi_samp, pi_feat
327
328
329 def co_optimal_transport2(
330 X,
331 Y,
332 wx_samp=None,
333 wx_feat=None,
334 wy_samp=None,
335 wy_feat=None,
336 epsilon=0,
337 alpha=0,
338 M_samp=None,
339 M_feat=None,
340 warmstart=None,
341 log=False,
342 verbose=False,
343 early_stopping_tol=1e-6,
344 nits_bcd=100,
345 tol_bcd=1e-7,
346 eval_bcd=1,
347 nits_ot=500,
348 tol_sinkhorn=1e-7,
349 method_sinkhorn="sinkhorn",
350 ):
351 r"""Compute the CO-Optimal Transport distance between two measures.
352
353 Returns the CO-Optimal Transport distance between
354 :math:`(\mathbf{X}, \mathbf{w}_{xs}, \mathbf{w}_{xf})` and
355 :math:`(\mathbf{Y}, \mathbf{w}_{ys}, \mathbf{w}_{yf})`.
356
357 The function solves the following CO-Optimal Transport (COOT) problem:
358
359 .. math::
360 \mathbf{COOT}_{\alpha, \varepsilon} = \mathop{\arg \min}_{\mathbf{P}, \mathbf{Q}}
361 &\quad \sum_{i,j,k,l}
362 (\mathbf{X}_{i,k} - \mathbf{Y}_{j,l})^2 \mathbf{P}_{i,j} \mathbf{Q}_{k,l}
363 + \alpha_1 \sum_{i,j} \mathbf{P}_{i,j} \mathbf{M^{(s)}}_{i, j} \\
364 &+ \alpha_2 \sum_{k, l} \mathbf{Q}_{k,l} \mathbf{M^{(f)}}_{k, l}
365 + \varepsilon_1 \mathbf{KL}(\mathbf{P} | \mathbf{w}_{xs} \mathbf{w}_{ys}^T)
366 + \varepsilon_2 \mathbf{KL}(\mathbf{Q} | \mathbf{w}_{xf} \mathbf{w}_{yf}^T)
367
368 where :
369
370 - :math:`\mathbf{X}`: Data matrix in the source space
371 - :math:`\mathbf{Y}`: Data matrix in the target space
372 - :math:`\mathbf{M^{(s)}}`: Additional sample matrix
373 - :math:`\mathbf{M^{(f)}}`: Additional feature matrix
374 - :math:`\mathbf{w}_{xs}`: Distribution of the samples in the source space
375 - :math:`\mathbf{w}_{xf}`: Distribution of the features in the source space
376 - :math:`\mathbf{w}_{ys}`: Distribution of the samples in the target space
377 - :math:`\mathbf{w}_{yf}`: Distribution of the features in the target space
378
379 .. note:: This function allows epsilon to be zero.
380 In that case, the :any:`ot.lp.emd` solver of POT will be used.
381
382 Parameters
383 ----------
384 X : (n_sample_x, n_feature_x) array-like, float
385 First input matrix.
386 Y : (n_sample_y, n_feature_y) array-like, float
387 Second input matrix.
388 wx_samp : (n_sample_x, ) array-like, float, optional (default = None)
389 Histogram assigned on rows (samples) of matrix X.
390 Uniform distribution by default.
391 wx_feat : (n_feature_x, ) array-like, float, optional (default = None)
392 Histogram assigned on columns (features) of matrix X.
393 Uniform distribution by default.
394 wy_samp : (n_sample_y, ) array-like, float, optional (default = None)
395 Histogram assigned on rows (samples) of matrix Y.
396 Uniform distribution by default.
397 wy_feat : (n_feature_y, ) array-like, float, optional (default = None)
398 Histogram assigned on columns (features) of matrix Y.
399 Uniform distribution by default.
400 epsilon : scalar or indexable object of length 2, float or int, optional (default = 0)
401 Regularization parameters for entropic approximation of sample and feature couplings.
402 Allow the case where epsilon contains 0. In that case, the EMD solver is used instead of
403 Sinkhorn solver. If epsilon is scalar, then the same epsilon is applied to
404 both regularization of sample and feature couplings.
405 alpha : scalar or indexable object of length 2, float or int, optional (default = 0)
406 Coefficient parameter of linear terms with respect to the sample and feature couplings.
407 If alpha is scalar, then the same alpha is applied to both linear terms.
408 M_samp : (n_sample_x, n_sample_y), float, optional (default = None)
409 Sample matrix with respect to the linear term on sample coupling.
410 M_feat : (n_feature_x, n_feature_y), float, optional (default = None)
411 Feature matrix with respect to the linear term on feature coupling.
412 warmstart : dictionary, optional (default = None)
413 Contains 4 keys:
414 - "duals_sample" and "duals_feature" whose values are
415 tuples of 2 vectors of size (n_sample_x, n_sample_y) and (n_feature_x, n_feature_y).
416 Initialization of sample and feature dual vectors
417 if using Sinkhorn algorithm. Zero vectors by default.
418 - "pi_sample" and "pi_feature" whose values are matrices
419 of size (n_sample_x, n_sample_y) and (n_feature_x, n_feature_y).
420 Initialization of sample and feature couplings.
421 Uniform distributions by default.
422 nits_bcd : int, optional (default = 100)
423 Number of Block Coordinate Descent (BCD) iterations to solve COOT.
424 tol_bcd : float, optional (default = 1e-7)
425 Tolerance of BCD scheme. If the L1-norm between the current and previous
426 sample couplings is under this threshold, then stop BCD scheme.
427 eval_bcd : int, optional (default = 1)
428 Multiplier of iteration at which the COOT cost is evaluated. For example,
429 if `eval_bcd = 8`, then the cost is calculated at iterations 8, 16, 24, etc...
430 nits_ot : int, optional (default = 100)
431 Number of iterations to solve each of the
432 two optimal transport problems in each BCD iteration.
433 tol_sinkhorn : float, optional (default = 1e-7)
434 Tolerance of Sinkhorn algorithm to stop the Sinkhorn scheme for
435 entropic optimal transport problem (if any) in each BCD iteration.
436 Only triggered when Sinkhorn solver is used.
437 method_sinkhorn : string, optional (default = "sinkhorn")
438 Method used in POT's `ot.sinkhorn` solver.
439 Only support "sinkhorn" and "sinkhorn_log".
440 early_stopping_tol : float, optional (default = 1e-6)
441 Tolerance for the early stopping. If the absolute difference between
442 the last 2 recorded COOT distances is under this tolerance, then stop BCD scheme.
443 log : bool, optional (default = False)
444 If True then the cost and 4 dual vectors, including
445 2 from sample and 2 from feature couplings, are recorded.
446 verbose : bool, optional (default = False)
447 If True then print the COOT cost at every multiplier of `eval_bcd`-th iteration.
448
449 Returns
450 -------
451 float
452 CO-Optimal Transport distance.
453 dict
454 Contains logged information from :any:`co_optimal_transport` solver.
455 Only returned if `log` parameter is True
456
457 References
458 ----------
459 .. [47] I. Redko, T. Vayer, R. Flamary, and N. Courty, CO-Optimal Transport,
460 Advances in Neural Information Processing ny_sampstems, 33 (2020).
461 """
462
463 pi_samp, pi_feat, dict_log = co_optimal_transport(
464 X=X,
465 Y=Y,
466 wx_samp=wx_samp,
467 wx_feat=wx_feat,
468 wy_samp=wy_samp,
469 wy_feat=wy_feat,
470 epsilon=epsilon,
471 alpha=alpha,
472 M_samp=M_samp,
473 M_feat=M_feat,
474 warmstart=warmstart,
475 nits_bcd=nits_bcd,
476 tol_bcd=tol_bcd,
477 eval_bcd=eval_bcd,
478 nits_ot=nits_ot,
479 tol_sinkhorn=tol_sinkhorn,
480 method_sinkhorn=method_sinkhorn,
481 early_stopping_tol=early_stopping_tol,
482 log=True,
483 verbose=verbose,
484 )
485
486 X, Y = list_to_array(X, Y)
487 nx = get_backend(X, Y)
488
489 nx_samp, nx_feat = X.shape
490 ny_samp, ny_feat = Y.shape
491
492 # measures on rows and columns
493 if wx_samp is None:
494 wx_samp = nx.ones(nx_samp, type_as=X) / nx_samp
495 if wx_feat is None:
496 wx_feat = nx.ones(nx_feat, type_as=X) / nx_feat
497 if wy_samp is None:
498 wy_samp = nx.ones(ny_samp, type_as=Y) / ny_samp
499 if wy_feat is None:
500 wy_feat = nx.ones(ny_feat, type_as=Y) / ny_feat
501
502 vx_samp, vy_samp = dict_log["duals_sample"]
503 vx_feat, vy_feat = dict_log["duals_feature"]
504
505 gradX = (
506 2 * X * (wx_samp[:, None] * wx_feat[None, :]) - 2 * pi_samp @ Y @ pi_feat.T
507 ) # shape (nx_samp, nx_feat)
508 gradY = (
509 2 * Y * (wy_samp[:, None] * wy_feat[None, :]) - 2 * pi_samp.T @ X @ pi_feat
510 ) # shape (ny_samp, ny_feat)
511
512 coot = dict_log["distances"][-1]
513 coot = nx.set_gradients(
514 coot,
515 (wx_samp, wx_feat, wy_samp, wy_feat, X, Y),
516 (vx_samp, vx_feat, vy_samp, vy_feat, gradX, gradY),
517 )
518
519 if log:
520 return coot, dict_log
521
522 else:
523 return coot