Debian Codegraph @

ot/regpath.py

raw symbols SCIP
1 # -*- coding: utf-8 -*-
2 """
3 Regularization path OT solvers
4 """
5
6 # Author: Haoran Wu <[email protected]>
7 # License: MIT License
8
9 import numpy as np
10 import scipy.sparse as sp
11
12
13 def recast_ot_as_lasso(a, b, C):
14 r"""This function recasts the l2-penalized UOT problem as a Lasso problem.
15
16 Recall the l2-penalized UOT problem defined in
17 :ref:`[41] <references-regpath>`
18
19 .. math::
20 \text{UOT}_{\lambda} = \min_T <C, T> + \lambda \|T 1_m -
21 \mathbf{a}\|_2^2 +
22 \lambda \|T^T 1_n - \mathbf{b}\|_2^2
23
24 s.t.
25 T \geq 0
26
27 where :
28
29 - :math:`C` is the cost matrix
30 - :math:`\lambda` is the l2-regularization parameter
31 - :math:`\mathbf{a}` and :math:`\mathbf{b}` are the source and target \
32 distributions
33 - :math:`T` is the transport plan to optimize
34
35 The problem above can be reformulated as a non-negative penalized
36 linear regression problem, particularly Lasso
37
38 .. math::
39 \text{UOT2}_{\lambda} = \min_{\mathbf{t}} \gamma \mathbf{c}^T
40 \mathbf{t} + 0.5 * \|H \mathbf{t} - \mathbf{y}\|_2^2
41
42 s.t.
43 \mathbf{t} \geq 0
44
45 where :
46
47 - :math:`\mathbf{c}` is the flattened version of the cost matrix :math:`C`
48 - :math:`\mathbf{y}` is the concatenation of vectors :math:`\mathbf{a}` \
49 and :math:`\mathbf{b}`
50 - :math:`H` is a metric matrix, see :ref:`[41] <references-regpath>` for \
51 the design of :math:`H`. The matrix product :math:`H\mathbf{t}` \
52 computes both the source marginal and the target marginals.
53 - :math:`\mathbf{t}` is the flattened version of the transport plan \
54 :math:`T`
55
56 Parameters
57 ----------
58 a : np.ndarray (dim_a,)
59 Histogram of dimension dim_a
60 b : np.ndarray (dim_b,)
61 Histogram of dimension dim_b
62 C : np.ndarray, shape (dim_a, dim_b)
63 Cost matrix
64
65 Returns
66 -------
67 H : np.ndarray (dim_a+dim_b, dim_a*dim_b)
68 Design matrix that contains only 0 and 1
69 y : np.ndarray (ns + nt, )
70 Concatenation of histograms :math:`\mathbf{a}` and :math:`\mathbf{b}`
71 c : np.ndarray (ns * nt, )
72 Flattened array of the cost matrix
73
74 Examples
75 --------
76 >>> import ot
77 >>> a = np.array([0.2, 0.3, 0.5])
78 >>> b = np.array([0.1, 0.9])
79 >>> C = np.array([[16., 25.], [28., 16.], [40., 36.]])
80 >>> H, y, c = ot.regpath.recast_ot_as_lasso(a, b, C)
81 >>> H.toarray()
82 array([[1., 1., 0., 0., 0., 0.],
83 [0., 0., 1., 1., 0., 0.],
84 [0., 0., 0., 0., 1., 1.],
85 [1., 0., 1., 0., 1., 0.],
86 [0., 1., 0., 1., 0., 1.]])
87 >>> y
88 array([0.2, 0.3, 0.5, 0.1, 0.9])
89 >>> c
90 array([16., 25., 28., 16., 40., 36.])
91
92
93 References
94 ----------
95 .. [41] Chapel, L., Flamary, R., Wu, H., Févotte, C., and Gasso, G. (2021).
96 Unbalanced optimal transport through non-negative penalized
97 linear regression. NeurIPS.
98 """
99
100 dim_a = np.shape(a)[0]
101 dim_b = np.shape(b)[0]
102 y = np.concatenate((a, b))
103 c = C.flatten()
104 jHa = np.arange(dim_a * dim_b)
105 iHa = np.repeat(np.arange(dim_a), dim_b)
106 jHb = np.arange(dim_a * dim_b)
107 iHb = np.tile(np.arange(dim_b), dim_a) + dim_a
108 j = np.concatenate((jHa, jHb))
109 i = np.concatenate((iHa, iHb))
110 H = sp.csc_matrix(
111 (np.ones(dim_a * dim_b * 2), (i, j)), shape=(dim_a + dim_b, dim_a * dim_b)
112 )
113 return H, y, c
114
115
116 def recast_semi_relaxed_as_lasso(a, b, C):
117 r"""This function recasts the semi-relaxed l2-UOT problem as Lasso problem.
118
119 .. math::
120
121 \text{semi-relaxed UOT} = \min_T <C, T>
122 + \lambda \|T 1_m - \mathbf{a}\|_2^2
123
124 s.t.
125 T^T 1_n = \mathbf{b}
126
127 \mathbf{t} \geq 0
128
129 where :
130
131 - :math:`C` is the metric cost matrix
132 - :math:`\lambda` is the l2-regularization parameter
133 - :math:`\mathbf{a}` and :math:`\mathbf{b}` are the source and target \
134 distributions
135 - :math:`T` is the transport plan to optimize
136
137 The problem above can be reformulated as follows
138
139 .. math::
140 \text{semi-relaxed UOT2} = \min_t \gamma \mathbf{c}^T t
141 + 0.5 * \|H_r \mathbf{t} - \mathbf{a}\|_2^2
142
143 s.t.
144 H_c \mathbf{t} = \mathbf{b}
145
146 \mathbf{t} \geq 0
147
148 where :
149
150 - :math:`\mathbf{c}` is flattened version of the cost matrix :math:`C`
151 - :math:`\gamma = 1/\lambda` is the l2-regularization parameter
152 - :math:`H_r` is a metric matrix which computes the sum along the \
153 rows of the transport plan :math:`T`
154 - :math:`H_c` is a metric matrix which computes the sum along the \
155 columns of the transport plan :math:`T`
156 - :math:`\mathbf{t}` is the flattened version of :math:`T`
157
158 Parameters
159 ----------
160 a : np.ndarray (dim_a,)
161 Histogram of dimension dim_a
162 b : np.ndarray (dim_b,)
163 Histogram of dimension dim_b
164 C : np.ndarray, shape (dim_a, dim_b)
165 Cost matrix
166
167 Returns
168 -------
169 Hr : np.ndarray (dim_a, dim_a * dim_b)
170 Auxiliary matrix constituted by 0 and 1, which computes
171 the sum along the rows of transport plan :math:`T`
172 Hc : np.ndarray (dim_b, dim_a * dim_b)
173 Auxiliary matrix constituted by 0 and 1, which computes
174 the sum along the columns of transport plan :math:`T`
175 c : np.ndarray (ns * nt, )
176 Flattened array of the cost matrix
177
178 Examples
179 --------
180 >>> import ot
181 >>> a = np.array([0.2, 0.3, 0.5])
182 >>> b = np.array([0.1, 0.9])
183 >>> C = np.array([[16., 25.], [28., 16.], [40., 36.]])
184 >>> Hr,Hc,c = ot.regpath.recast_semi_relaxed_as_lasso(a, b, C)
185 >>> Hr.toarray()
186 array([[1., 1., 0., 0., 0., 0.],
187 [0., 0., 1., 1., 0., 0.],
188 [0., 0., 0., 0., 1., 1.]])
189 >>> Hc.toarray()
190 array([[1., 0., 1., 0., 1., 0.],
191 [0., 1., 0., 1., 0., 1.]])
192 >>> c
193 array([16., 25., 28., 16., 40., 36.])
194 """
195
196 dim_a = np.shape(a)[0]
197 dim_b = np.shape(b)[0]
198
199 c = C.flatten()
200 jHr = np.arange(dim_a * dim_b)
201 iHr = np.repeat(np.arange(dim_a), dim_b)
202 jHc = np.arange(dim_a * dim_b)
203 iHc = np.tile(np.arange(dim_b), dim_a)
204
205 Hr = sp.csc_matrix(
206 (np.ones(dim_a * dim_b), (iHr, jHr)), shape=(dim_a, dim_a * dim_b)
207 )
208 Hc = sp.csc_matrix(
209 (np.ones(dim_a * dim_b), (iHc, jHc)), shape=(dim_b, dim_a * dim_b)
210 )
211
212 return Hr, Hc, c
213
214
215 def ot_next_gamma(phi, delta, HtH, Hty, c, active_index, current_gamma):
216 r""" This function computes the next value of gamma if a variable
217 is added in the next iteration of the regularization path.
218
219 We look for the largest value of gamma such that
220 the gradient of an inactive variable vanishes
221
222 .. math::
223 \max_{i \in \bar{A}} \frac{\mathbf{h}_i^T(H_A \phi - \mathbf{y})}
224 {\mathbf{h}_i^T H_A \delta - \mathbf{c}_i}
225
226 where :
227
228 - A is the current active set
229 - :math:`\mathbf{h}_i` is the :math:`i` th column of the design \
230 matrix :math:`{H}`
231 - :math:`{H}_A` is the sub-matrix constructed by the columns of \
232 :math:`{H}` whose indices belong to the active set A
233 - :math:`\mathbf{c}_i` is the :math:`i` th element of the cost vector \
234 :math:`\mathbf{c}`
235 - :math:`\mathbf{y}` is the concatenation of the source and target \
236 distributions
237 - :math:`\phi` is the intercept of the solutions at the current iteration
238 - :math:`\delta` is the slope of the solutions at the current iteration
239
240 Parameters
241 ----------
242 phi : np.ndarray (size(A), )
243 Intercept of the solutions at the current iteration
244 delta : np.ndarray (size(A), )
245 Slope of the solutions at the current iteration
246 HtH : np.ndarray (dim_a * dim_b, dim_a * dim_b)
247 Matrix product of :math:`{H}^T {H}`
248 Hty : np.ndarray (dim_a + dim_b, )
249 Matrix product of :math:`{H}^T \mathbf{y}`
250 c: np.ndarray (dim_a * dim_b, )
251 Flattened array of the cost matrix :math:`{C}`
252 active_index : list
253 Indices of active variables
254 current_gamma : float
255 Value of the regularization parameter at the beginning of the current \
256 iteration
257
258 Returns
259 -------
260 next_gamma : float
261 Value of gamma if a variable is added to active set in next iteration
262 next_active_index : int
263 Index of variable to be activated
264
265
266 References
267 ----------
268 .. [41] Chapel, L., Flamary, R., Wu, H., Févotte, C., and Gasso, G. (2021).
269 Unbalanced optimal transport through non-negative penalized
270 linear regression. NeurIPS.
271 """
272 M = (HtH[:, active_index].dot(phi) - Hty) / (
273 HtH[:, active_index].dot(delta) - c + 1e-16
274 )
275 M[active_index] = 0
276 M[M > (current_gamma - 1e-10 * current_gamma)] = 0
277 return np.max(M), np.argmax(M)
278
279
280 def semi_relaxed_next_gamma(
281 phi, delta, phi_u, delta_u, HrHr, Hc, Hra, c, active_index, current_gamma
282 ):
283 r""" This function computes the next value of gamma when a variable is
284 active in the regularization path of semi-relaxed UOT.
285
286 By taking the Lagrangian form of the problem, we obtain a similar update
287 as the two-sided relaxed UOT
288
289 .. math::
290
291 \max_{i \in \bar{A}} \frac{\mathbf{h}_{ri}^T(H_{rA} \phi - \mathbf{a})
292 + \mathbf{h}_{c i}^T\phi_u}{\mathbf{h}_{r i}^T H_{r A} \delta + \
293 \mathbf{h}_{c i} \delta_u - \mathbf{c}_i}
294
295 where :
296
297 - A is the current active set
298 - :math:`\mathbf{h}_{r i}` is the ith column of the matrix :math:`H_r`
299 - :math:`\mathbf{h}_{c i}` is the ith column of the matrix :math:`H_c`
300 - :math:`H_{r A}` is the sub-matrix constructed by the columns of \
301 :math:`H_r` whose indices belong to the active set A
302 - :math:`\mathbf{c}_i` is the :math:`i` th element of cost vector \
303 :math:`\mathbf{c}`
304 - :math:`\phi` is the intercept of the solutions in current iteration
305 - :math:`\delta` is the slope of the solutions in current iteration
306 - :math:`\phi_u` is the intercept of Lagrange parameter at the \
307 current iteration
308 - :math:`\delta_u` is the slope of Lagrange parameter at the \
309 current iteration
310
311 Parameters
312 ----------
313 phi : np.ndarray (size(A), )
314 Intercept of the solutions at the current iteration
315 delta : np.ndarray (size(A), )
316 Slope of the solutions at the current iteration
317 phi_u : np.ndarray (dim_b, )
318 Intercept of the Lagrange parameter at the current iteration
319 delta_u : np.ndarray (dim_b, )
320 Slope of the Lagrange parameter at the current iteration
321 HrHr : np.ndarray (dim_a * dim_b, dim_a * dim_b)
322 Matrix product of :math:`H_r^T H_r`
323 Hc : np.ndarray (dim_b, dim_a * dim_b)
324 Matrix that computes the sum along the columns of the transport plan \
325 :math:`T`
326 Hra : np.ndarray (dim_a * dim_b, )
327 Matrix product of :math:`H_r^T \mathbf{a}`
328 c: np.ndarray (dim_a * dim_b, )
329 Flattened array of cost matrix :math:`C`
330 active_index : list
331 Indices of active variables
332 current_gamma : float
333 Value of regularization coefficient at the start of current iteration
334
335 Returns
336 -------
337 next_gamma : float
338 Value of gamma if a variable is added to active set in next iteration
339 next_active_index : int
340 Index of variable to be activated
341
342 References
343 ----------
344 .. [41] Chapel, L., Flamary, R., Wu, H., Févotte, C., and Gasso, G. (2021).
345 Unbalanced optimal transport through non-negative penalized
346 linear regression. NeurIPS.
347 """
348
349 M = (HrHr[:, active_index].dot(phi) - Hra + Hc.T.dot(phi_u)) / (
350 HrHr[:, active_index].dot(delta) - c + Hc.T.dot(delta_u) + 1e-16
351 )
352 M[active_index] = 0
353 M[M > (current_gamma - 1e-10 * current_gamma)] = 0
354 return np.max(M), np.argmax(M)
355
356
357 def compute_next_removal(phi, delta, current_gamma):
358 r""" This function computes the next gamma value if a variable
359 is removed at the next iteration of the regularization path.
360
361 We look for the largest value of the regularization parameter such that
362 an element of the current solution vanishes
363
364 .. math::
365 \max_{j \in A} \frac{\phi_j}{\delta_j}
366
367 where :
368
369 - A is the current active set
370 - :math:`\phi_j` is the :math:`j` th element of the intercept of the \
371 current solution
372 - :math:`\delta_j` is the :math:`j` th element of the slope of the \
373 current solution
374
375
376 Parameters
377 ----------
378 phi : ndarray, shape (size(A), )
379 Intercept of the solution at the current iteration
380 delta : ndarray, shape (size(A), )
381 Slope of the solution at the current iteration
382 current_gamma : float
383 Value of the regularization parameter at the beginning of the \
384 current iteration
385
386 Returns
387 -------
388 next_removal_gamma : float
389 Gamma value if a variable is removed at the next iteration
390 next_removal_index : int
391 Index of the variable to be removed at the next iteration
392
393
394 .. _references-regpath:
395 References
396 ----------
397 .. [41] Chapel, L., Flamary, R., Wu, H., Févotte, C., and Gasso, G. (2021).
398 Unbalanced optimal transport through non-negative penalized
399 linear regression. NeurIPS.
400 """
401 r_candidate = phi / (delta - 1e-16)
402 r_candidate[r_candidate >= (1 - 1e-8) * current_gamma] = 0
403 return np.max(r_candidate), np.argmax(r_candidate)
404
405
406 def complement_schur(M_current, b, d, id_pop):
407 r""" This function computes the inverse of the design matrix in the \
408 regularization path using the Schur complement. Two cases may arise:
409
410 Case 1: one variable is added to the active set
411
412
413 .. math::
414 M_{k+1}^{-1} =
415 \begin{bmatrix}
416 M_{k}^{-1} + s^{-1} M_{k}^{-1} \mathbf{b} \mathbf{b}^T M_{k}^{-1} \
417 & - M_{k}^{-1} \mathbf{b} s^{-1} \\
418 - s^{-1} \mathbf{b}^T M_{k}^{-1} & s^{-1}
419 \end{bmatrix}
420
421
422 where :
423
424 - :math:`M_k^{-1}` is the inverse of the design matrix :math:`H_A^tH_A` \
425 of the previous iteration
426 - :math:`\mathbf{b}` is the last column of :math:`M_{k}`
427 - :math:`s` is the Schur complement, given by \
428 :math:`s = \mathbf{d} - \mathbf{b}^T M_{k}^{-1} \mathbf{b}`
429
430 Case 2: one variable is removed from the active set.
431
432 .. math::
433 M_{k+1}^{-1} = M^{-1}_{k \backslash q} -
434 \frac{r_{-q,q} r^{T}_{-q,q}}{r_{q,q}}
435
436 where :
437
438 - :math:`q` is the index of column and row to delete
439 - :math:`M^{-1}_{k \backslash q}` is the previous inverse matrix deprived \
440 of the :math:`q` th column and :math:`q` th row
441 - :math:`r_{-q,q}` is the :math:`q` th column of :math:`M^{-1}_{k}` \
442 without the :math:`q` th element
443 - :math:`r_{q, q}` is the element of :math:`q` th column and :math:`q` th \
444 row in :math:`M^{-1}_{k}`
445
446
447 Parameters
448 ----------
449 M_current : ndarray, shape (size(A)-1, size(A)-1)
450 Inverse matrix of :math:`H_A^tH_A` at the previous iteration, with \
451 size(A) the size of the active set
452 b : ndarray, shape (size(A)-1, )
453 None for case 2 (removal), last column of :math:`M_{k}` for case 1 \
454 (addition)
455 d : float
456 should be equal to 2 when UOT and 1 for the semi-relaxed OT
457 id_pop : int
458 Index of the variable to be removed, equal to -1
459 if no variable is deleted at the current iteration
460
461
462 Returns
463 -------
464 M : ndarray, shape (size(A), size(A))
465 Inverse matrix of :math:`H_A^tH_A` of the current iteration
466
467
468 References
469 ----------
470 .. [41] Chapel, L., Flamary, R., Wu, H., Févotte, C., and Gasso, G. (2021).
471 Unbalanced optimal transport through non-negative penalized
472 linear regression. NeurIPS.
473 """
474
475 if b is None:
476 b = M_current[id_pop, :]
477 b = np.delete(b, id_pop)
478 M_del = np.delete(M_current, id_pop, 0)
479 a = M_del[:, id_pop]
480 M_del = np.delete(M_del, id_pop, 1)
481 M = M_del - np.outer(a, b) / M_current[id_pop, id_pop]
482 else:
483 n = b.shape[0] + 1
484 if np.shape(b)[0] == 0:
485 M = np.array([[0.5]])
486 else:
487 X = M_current.dot(b)
488 s = d - b.T.dot(X)
489 M = np.zeros((n, n))
490 M[:-1, :-1] = M_current + X.dot(X.T) / s
491 X_ravel = X.ravel()
492 M[-1, :-1] = -X_ravel / s
493 M[:-1, -1] = -X_ravel / s
494 M[-1, -1] = 1 / s
495 return M
496
497
498 def construct_augmented_H(active_index, m, Hc, HrHr):
499 r""" This function constructs an augmented matrix for the first iteration
500 of the semi-relaxed regularization path
501
502 .. math::
503 \text{Augmented}_H =
504 \begin{bmatrix}
505 0 & H_{c A} \\
506 H_{c A}^T & H_{r A}^T H_{r A}
507 \end{bmatrix}
508
509 where :
510
511 - :math:`H_{r A}` is the sub-matrix constructed by the columns of \
512 :math:`H_r` whose indices belong to the active set A
513 - :math:`H_{c A}` is the sub-matrix constructed by the columns of \
514 :math:`H_c` whose indices belong to the active set A
515
516
517 Parameters
518 ----------
519 active_index : list
520 Indices of the active variables
521 m : int
522 Length of the target distribution
523 Hc : np.ndarray (dim_b, dim_a * dim_b)
524 Matrix that computes the sum along the columns of the transport plan \
525 :math:`T`
526 HrHr : np.ndarray (dim_a * dim_b, dim_a * dim_b)
527 Matrix product of :math:`H_r^T H_r`
528
529 Returns
530 -------
531 H_augmented : np.ndarray (dim_b + size(A), dim_b + size(A))
532 Augmented matrix for the first iteration of the semi-relaxed
533 regularization path
534 """
535 Hc_sub = Hc[:, active_index].toarray()
536 HrHr_sub = HrHr[:, active_index]
537 HrHr_sub = HrHr_sub[active_index, :].toarray()
538 H_augmented = np.block([[np.zeros((m, m)), Hc_sub], [Hc_sub.T, HrHr_sub]])
539 return H_augmented
540
541
542 def fully_relaxed_path(a: np.array, b: np.array, C: np.array, reg=1e-4, itmax=50000):
543 r"""This function gives the regularization path of l2-penalized UOT problem
544
545 The problem to optimize is the Lasso reformulation of the l2-penalized UOT:
546
547 .. math::
548 \min_t \gamma \mathbf{c}^T \mathbf{t}
549 + 0.5 * \|{H} \mathbf{t} - \mathbf{y}\|_2^2
550
551 s.t.
552 \mathbf{t} \geq 0
553
554 where :
555
556 - :math:`\mathbf{c}` is the flattened version of the cost matrix \
557 :math:`{C}`
558 - :math:`\gamma = 1/\lambda` is the l2-regularization coefficient
559 - :math:`\mathbf{y}` is the concatenation of vectors :math:`\mathbf{a}` \
560 and :math:`\mathbf{b}`, defined as \
561 :math:`\mathbf{y}^T = [\mathbf{a}^T \mathbf{b}^T]`
562 - :math:`{H}` is a design matrix, see :ref:`[41] <references-regpath>` \
563 for the design of :math:`{H}`. The matrix product :math:`H\mathbf{t}` \
564 computes both the source marginal and the target marginals.
565 - :math:`\mathbf{t}` is the flattened version of the transport matrix
566
567 Parameters
568 ----------
569 a : np.ndarray (dim_a,)
570 Histogram of dimension dim_a
571 b : np.ndarray (dim_b,)
572 Histogram of dimension dim_b
573 C : np.ndarray, shape (dim_a, dim_b)
574 Cost matrix
575 reg: float
576 l2-regularization coefficient
577 itmax: int
578 Maximum number of iteration
579 Returns
580 -------
581 t : np.ndarray (dim_a*dim_b, )
582 Flattened vector of the optimal transport matrix
583 t_list : list
584 List of solutions in the regularization path
585 gamma_list : list
586 List of regularization coefficients in the regularization path
587
588 Examples
589 --------
590 >>> import ot
591 >>> import numpy as np
592 >>> n = 3
593 >>> xs = np.array([1., 2., 3.]).reshape((n, 1))
594 >>> xt = np.array([5., 6., 7.]).reshape((n, 1))
595 >>> C = ot.dist(xs, xt)
596 >>> C /= C.max()
597 >>> a = np.array([0.2, 0.5, 0.3])
598 >>> b = np.array([0.2, 0.5, 0.3])
599 >>> t, _, _ = ot.regpath.fully_relaxed_path(a, b, C, 1e-4)
600 >>> t
601 array([1.99958333e-01, 0.00000000e+00, 0.00000000e+00, 3.88888889e-05,
602 4.99938889e-01, 0.00000000e+00, 0.00000000e+00, 3.88888889e-05,
603 2.99958333e-01])
604
605 References
606 ----------
607 .. [41] Chapel, L., Flamary, R., Wu, H., Févotte, C., and Gasso, G. (2021).
608 Unbalanced optimal transport through non-negative penalized
609 linear regression. NeurIPS.
610 """
611
612 n = np.shape(a)[0]
613 m = np.shape(b)[0]
614 H, y, c = recast_ot_as_lasso(a, b, C)
615 HtH = H.T.dot(H)
616 Hty = H.T.dot(y)
617 n_iter = 1
618
619 # initialization
620 M0 = Hty / c
621 gamma_list = [np.max(M0)]
622 active_index = [np.argmax(M0)]
623 t_list = [np.zeros((n * m,))]
624 H_inv = np.array([[]])
625 add_col = np.array([])
626 id_pop = -1
627
628 while n_iter < itmax and gamma_list[-1] > reg:
629 H_inv = complement_schur(H_inv, add_col, 2.0, id_pop)
630 current_gamma = gamma_list[-1]
631
632 # compute the intercept and slope of solutions in current iteration
633 # t = phi - gamma * delta
634 phi = H_inv.dot(Hty[active_index])
635 delta = H_inv.dot(c[active_index])
636 gamma, ik = ot_next_gamma(phi, delta, HtH, Hty, c, active_index, current_gamma)
637
638 # compute the next lambda when removing a point from the active set
639 alt_gamma, id_pop = compute_next_removal(phi, delta, current_gamma)
640
641 # if the positivity constraint is violated, we remove id_pop
642 # from active set, otherwise we add ik to active set
643 if alt_gamma > gamma:
644 gamma = alt_gamma
645 else:
646 id_pop = -1
647
648 # compute the solution of current segment
649 tA = phi - gamma * delta
650 sol = np.zeros((n * m,))
651 sol[active_index] = tA
652
653 if id_pop != -1:
654 active_index.pop(id_pop)
655 add_col = None
656 else:
657 active_index.append(ik)
658 add_col = HtH[active_index[:-1], ik].toarray()
659
660 gamma_list.append(gamma)
661 t_list.append(sol)
662 n_iter += 1
663
664 if itmax <= n_iter:
665 print("maximum iteration has been reached !")
666
667 # correct the last solution and gamma
668 if len(t_list) > 1:
669 t_final = t_list[-2] + (t_list[-1] - t_list[-2]) * (reg - gamma_list[-2]) / (
670 gamma_list[-1] - gamma_list[-2]
671 )
672 t_list[-1] = t_final
673 gamma_list[-1] = reg
674 else:
675 gamma_list[-1] = reg
676 print("Regularization path does not exist !")
677
678 return t_list[-1], t_list, gamma_list
679
680
681 def semi_relaxed_path(a: np.array, b: np.array, C: np.array, reg=1e-4, itmax=50000):
682 r"""This function gives the regularization path of semi-relaxed
683 l2-UOT problem.
684
685 The problem to optimize is the Lasso reformulation of the l2-penalized UOT:
686
687 .. math::
688
689 \min_t \gamma \mathbf{c}^T t
690 + 0.5 * \|H_r \mathbf{t} - \mathbf{a}\|_2^2
691
692 s.t.
693 H_c \mathbf{t} = \mathbf{b}
694
695 \mathbf{t} \geq 0
696
697 where :
698
699 - :math:`\mathbf{c}` is the flattened version of the cost matrix \
700 :math:`C`
701 - :math:`\gamma = 1/\lambda` is the l2-regularization parameter
702 - :math:`H_r` is a matrix that computes the sum along the rows of \
703 the transport plan :math:`T`
704 - :math:`H_c` is a matrix that computes the sum along the columns of \
705 the transport plan :math:`T`
706 - :math:`\mathbf{t}` is the flattened version of the transport plan \
707 :math:`T`
708
709 Parameters
710 ----------
711 a : np.ndarray (dim_a,)
712 Histogram of dimension dim_a
713 b : np.ndarray (dim_b,)
714 Histogram of dimension dim_b
715 C : np.ndarray, shape (dim_a, dim_b)
716 Cost matrix
717 reg: float (optional)
718 l2-regularization coefficient
719 itmax: int (optional)
720 Maximum number of iteration
721
722 Returns
723 -------
724 t : np.ndarray (dim_a*dim_b, )
725 Flattened vector of the (unregularized) optimal transport matrix
726 t_list : list
727 List of all the optimal transport vectors of the regularization path
728 gamma_list : list
729 List of the regularization parameters in the path
730
731 Examples
732 --------
733 >>> import ot
734 >>> import numpy as np
735 >>> n = 3
736 >>> xs = np.array([1., 2., 3.]).reshape((n, 1))
737 >>> xt = np.array([5., 6., 7.]).reshape((n, 1))
738 >>> C = ot.dist(xs, xt)
739 >>> C /= C.max()
740 >>> a = np.array([0.2, 0.5, 0.3])
741 >>> b = np.array([0.2, 0.5, 0.3])
742 >>> t, _, _ = ot.regpath.semi_relaxed_path(a, b, C, 1e-4)
743 >>> t
744 array([1.99980556e-01, 0.00000000e+00, 0.00000000e+00, 1.94444444e-05,
745 4.99980556e-01, 0.00000000e+00, 0.00000000e+00, 1.94444444e-05,
746 3.00000000e-01])
747
748 References
749 ----------
750 .. [41] Chapel, L., Flamary, R., Wu, H., Févotte, C., and Gasso, G. (2021).
751 Unbalanced optimal transport through non-negative penalized
752 linear regression. NeurIPS.
753 """
754
755 n = np.shape(a)[0]
756 m = np.shape(b)[0]
757 Hr, Hc, c = recast_semi_relaxed_as_lasso(a, b, C)
758 Hra = Hr.T.dot(a)
759 HrHr = Hr.T.dot(Hr)
760 n_iter = 1
761 active_index = []
762
763 # initialization
764 for j in range(np.shape(C)[1]):
765 i = np.argmin(C[:, j])
766 active_index.append(i * m + j)
767 gamma_list = []
768 t_list = []
769 current_gamma = np.inf
770 augmented_H0 = construct_augmented_H(active_index, m, Hc, HrHr)
771 add_col = np.array([])
772 id_pop = -1
773
774 while n_iter < itmax and current_gamma > reg:
775 if n_iter == 1:
776 H_inv = np.linalg.inv(augmented_H0)
777 else:
778 H_inv = complement_schur(H_inv, add_col, 1.0, id_pop + m)
779 # compute the intercept and slope of solutions in current iteration
780 augmented_phi = H_inv.dot(np.concatenate((b, Hra[active_index])))
781 augmented_delta = H_inv[:, m:].dot(c[active_index])
782 phi = augmented_phi[m:]
783 delta = augmented_delta[m:]
784 phi_u = augmented_phi[0:m]
785 delta_u = augmented_delta[0:m]
786 gamma, ik = semi_relaxed_next_gamma(
787 phi, delta, phi_u, delta_u, HrHr, Hc, Hra, c, active_index, current_gamma
788 )
789
790 # compute the next lambda when removing a point from the active set
791 alt_gamma, id_pop = compute_next_removal(phi, delta, current_gamma)
792
793 # if the positivity constraint is violated, we remove id_pop
794 # from active set, otherwise we add ik to active set
795 if alt_gamma > gamma:
796 gamma = alt_gamma
797 else:
798 id_pop = -1
799
800 # compute the solution of current segment
801 tA = phi - gamma * delta
802 sol = np.zeros((n * m,))
803 sol[active_index] = tA
804 if id_pop != -1:
805 active_index.pop(id_pop)
806 add_col = None
807 else:
808 active_index.append(ik)
809 add_col = np.concatenate(
810 (Hc.toarray()[:, ik], HrHr.toarray()[active_index[:-1], ik])
811 )
812 add_col = add_col[:, np.newaxis]
813
814 gamma_list.append(gamma)
815 t_list.append(sol)
816 current_gamma = gamma
817 n_iter += 1
818
819 if itmax <= n_iter:
820 print("maximum iteration has been reached !")
821
822 # correct the last solution and gamma
823 if len(t_list) > 1:
824 t_final = t_list[-2] + (t_list[-1] - t_list[-2]) * (reg - gamma_list[-2]) / (
825 gamma_list[-1] - gamma_list[-2]
826 )
827 t_list[-1] = t_final
828 gamma_list[-1] = reg
829 else:
830 gamma_list[-1] = reg
831 print("Regularization path does not exist !")
832
833 return t_list[-1], t_list, gamma_list
834
835
836 def regularization_path(
837 a: np.array, b: np.array, C: np.array, reg=1e-4, semi_relaxed=False, itmax=50000
838 ):
839 r"""This function provides all the solutions of the regularization path \
840 of the l2-UOT problem :ref:`[41] <references-regpath>`.
841
842 The problem to optimize is the Lasso reformulation of the l2-penalized UOT:
843
844 .. math::
845 \min_t \gamma \mathbf{c}^T \mathbf{t}
846 + 0.5 * \|{H} \mathbf{t} - \mathbf{y}\|_2^2
847
848 s.t.
849 \mathbf{t} \geq 0
850
851 where :
852
853 - :math:`\mathbf{c}` is the flattened version of the cost matrix \
854 :math:`{C}`
855 - :math:`\gamma = 1/\lambda` is the l2-regularization coefficient
856 - :math:`\mathbf{y}` is the concatenation of vectors :math:`\mathbf{a}` \
857 and :math:`\mathbf{b}`, defined as \
858 :math:`\mathbf{y}^T = [\mathbf{a}^T \mathbf{b}^T]`
859 - :math:`{H}` is a design matrix, see :ref:`[41] <references-regpath>` \
860 for the design of :math:`{H}`. The matrix product :math:`H\mathbf{t}` \
861 computes both the source marginal and the target marginals.
862 - :math:`\mathbf{t}` is the flattened version of the transport matrix
863
864 For the semi-relaxed problem, it optimizes the Lasso reformulation of the
865 l2-penalized UOT:
866
867 .. math::
868
869 \min_t \gamma \mathbf{c}^T \mathbf{t}
870 + 0.5 * \|H_r \mathbf{t} - \mathbf{a}\|_2^2
871
872 s.t.
873 H_c \mathbf{t} = \mathbf{b}
874
875 \mathbf{t} \geq 0
876
877
878 Parameters
879 ----------
880 a : np.ndarray (dim_a,)
881 Histogram of dimension dim_a
882 b : np.ndarray (dim_b,)
883 Histogram of dimension dim_b
884 C : np.ndarray, shape (dim_a, dim_b)
885 Cost matrix
886 reg: float (optional)
887 l2-regularization coefficient
888 semi_relaxed : bool (optional)
889 Give the semi-relaxed path if True
890 itmax: int (optional)
891 Maximum number of iteration
892
893 Returns
894 -------
895 t : np.ndarray (dim_a*dim_b, )
896 Flattened vector of the (unregularized) optimal transport matrix
897 t_list : list
898 List of all the optimal transport vectors of the regularization path
899 gamma_list : list
900 List of the regularization parameters in the path
901
902 References
903 ----------
904 .. [41] Chapel, L., Flamary, R., Wu, H., Févotte, C., and Gasso, G. (2021).
905 Unbalanced optimal transport through non-negative penalized
906 linear regression. NeurIPS.
907 """
908 if semi_relaxed:
909 t, t_list, gamma_list = semi_relaxed_path(a, b, C, reg=reg, itmax=itmax)
910 else:
911 t, t_list, gamma_list = fully_relaxed_path(a, b, C, reg=reg, itmax=itmax)
912 return t, t_list, gamma_list
913
914
915 def compute_transport_plan(gamma, gamma_list, Pi_list):
916 r"""Given the regularization path, this function computes the transport
917 plan for any value of gamma thanks to the piecewise linearity of the path.
918
919 .. math::
920 t(\gamma) = \phi(\gamma) - \gamma \delta(\gamma)
921
922 where:
923
924 - :math:`\gamma` is the regularization parameter
925 - :math:`\phi(\gamma)` is the corresponding intercept
926 - :math:`\delta(\gamma)` is the corresponding slope
927 - :math:`\mathbf{t}` is the flattened version of the transport matrix
928
929 Parameters
930 ----------
931 gamma : float
932 Regularization coefficient
933 gamma_list : list
934 List of regularization parameters of the regularization path
935 Pi_list : list
936 List of all the solutions of the regularization path
937
938 Returns
939 -------
940 t : np.ndarray (dim_a*dim_b, )
941 Vectorization of the transport plan corresponding to the given value
942 of gamma
943
944 Examples
945 --------
946 >>> import ot
947 >>> import numpy as np
948 >>> n = 3
949 >>> xs = np.array([1., 2., 3.]).reshape((n, 1))
950 >>> xt = np.array([5., 6., 7.]).reshape((n, 1))
951 >>> C = ot.dist(xs, xt)
952 >>> C /= C.max()
953 >>> a = np.array([0.2, 0.5, 0.3])
954 >>> b = np.array([0.2, 0.5, 0.3])
955 >>> t, pi_list, g_list = ot.regpath.regularization_path(a, b, C, reg=1e-4)
956 >>> gamma = 1
957 >>> t2 = ot.regpath.compute_transport_plan(gamma, g_list, pi_list)
958 >>> t2
959 array([0. , 0. , 0. , 0.19722222, 0.05555556,
960 0. , 0. , 0.24722222, 0. ])
961
962
963 .. _references-regpath:
964 References
965 ----------
966 .. [41] Chapel, L., Flamary, R., Wu, H., Févotte, C., and Gasso, G. (2021).
967 Unbalanced optimal transport through non-negative penalized
968 linear regression. NeurIPS.
969 """
970
971 if gamma >= gamma_list[0]:
972 Pi = Pi_list[0]
973 elif gamma <= gamma_list[-1]:
974 Pi = Pi_list[-1]
975 else:
976 idx = np.where(gamma <= np.array(gamma_list))[0][-1]
977 gamma_k0 = gamma_list[idx]
978 gamma_k1 = gamma_list[idx + 1]
979 pi_k0 = Pi_list[idx]
980 pi_k1 = Pi_list[idx + 1]
981 Pi = pi_k0 + (pi_k1 - pi_k0) * (gamma - gamma_k0) / (gamma_k1 - gamma_k0)
982 return Pi