Debian Codegraph @

ot/lowrank.py

raw symbols SCIP
1 """
2 Low rank OT solvers
3 """
4
5 # Author: Laurène David <[email protected]>
6 #
7 # License: MIT License
8
9 import warnings
10 from .utils import unif, dist, get_lowrank_lazytensor
11 from .backend import get_backend
12 from .bregman import sinkhorn
13
14 # test if sklearn is installed for linux-minimal-deps
15 try:
16 import sklearn.cluster
17
18 sklearn_import = True
19 except ImportError:
20 sklearn_import = False
21
22
23 def _init_lr_sinkhorn(X_s, X_t, a, b, rank, init, reg_init, random_state, nx=None):
24 """
25 Implementation of different initialization strategies for the low rank sinkhorn solver (Q ,R, g).
26 This function is specific to lowrank_sinkhorn.
27
28 Parameters
29 ----------
30 X_s : array-like, shape (n_samples_a, dim)
31 samples in the source domain
32 X_t : array-like, shape (n_samples_b, dim)
33 samples in the target domain
34 a : array-like, shape (n_samples_a,)
35 samples weights in the source domain
36 b : array-like, shape (n_samples_b,)
37 samples weights in the target domain
38 rank : int
39 Nonnegative rank of the OT plan.
40 init : str
41 Initialization strategy for Q, R and g. 'random', 'trivial' or 'kmeans'
42 reg_init : float, optional.
43 Regularization term for a 'kmeans' init.
44 random_state : int, optional.
45 Random state for a "random" or 'kmeans' init strategy
46 nx : optional, Default is None
47 POT backend
48
49
50 Returns
51 ---------
52 Q : array-like, shape (n_samples_a, r)
53 Init for the first low-rank matrix decomposition of the OT plan (Q)
54 R: array-like, shape (n_samples_b, r)
55 Init for the second low-rank matrix decomposition of the OT plan (R)
56 g : array-like, shape (r, )
57 Init for the weight vector of the low-rank decomposition of the OT plan (g)
58
59
60 References
61 -----------
62 .. [65] Scetbon, M., Cuturi, M., & Peyré, G. (2021).
63 "Low-rank Sinkhorn factorization". In International Conference on Machine Learning.
64
65 """
66
67 if nx is None:
68 nx = get_backend(X_s, X_t, a, b)
69
70 ns = X_s.shape[0]
71 nt = X_t.shape[0]
72 r = rank
73
74 if init == "random":
75 nx.seed(seed=random_state)
76
77 # Init g
78 g = nx.abs(nx.randn(r, type_as=X_s)) + 1
79 g = g / nx.sum(g)
80
81 # Init Q
82 Q = nx.abs(nx.randn(ns, r, type_as=X_s)) + 1
83 Q = (Q.T * (a / nx.sum(Q, axis=1))).T
84
85 # Init R
86 R = nx.abs(nx.randn(nt, rank, type_as=X_s)) + 1
87 R = (R.T * (b / nx.sum(R, axis=1))).T
88
89 if init == "deterministic":
90 # Init g
91 g = nx.ones(rank) / rank
92
93 lambda_1 = min(nx.min(a), nx.min(g), nx.min(b)) / 2
94 a1 = nx.arange(start=1, stop=ns + 1, type_as=X_s)
95 a1 = a1 / nx.sum(a1)
96 a2 = (a - lambda_1 * a1) / (1 - lambda_1)
97
98 b1 = nx.arange(start=1, stop=nt + 1, type_as=X_s)
99 b1 = b1 / nx.sum(b1)
100 b2 = (b - lambda_1 * b1) / (1 - lambda_1)
101
102 g1 = nx.arange(start=1, stop=rank + 1, type_as=X_s)
103 g1 = g1 / nx.sum(g1)
104 g2 = (g - lambda_1 * g1) / (1 - lambda_1)
105
106 # Init Q
107 Q1 = lambda_1 * nx.dot(a1[:, None], nx.reshape(g1, (1, -1)))
108 Q2 = (1 - lambda_1) * nx.dot(a2[:, None], nx.reshape(g2, (1, -1)))
109 Q = Q1 + Q2
110
111 # Init R
112 R1 = lambda_1 * nx.dot(b1[:, None], nx.reshape(g1, (1, -1)))
113 R2 = (1 - lambda_1) * nx.dot(b2[:, None], nx.reshape(g2, (1, -1)))
114 R = R1 + R2
115
116 if init == "kmeans":
117 if sklearn_import:
118 # Init g
119 g = nx.ones(rank, type_as=X_s) / rank
120
121 # Init Q
122 kmeans_Xs = sklearn.cluster.KMeans(
123 n_clusters=rank, random_state=random_state, n_init="auto"
124 )
125 kmeans_Xs.fit(X_s)
126 Z_Xs = nx.from_numpy(kmeans_Xs.cluster_centers_)
127 C_Xs = dist(X_s, Z_Xs) # shape (ns, rank)
128 C_Xs = C_Xs / nx.max(C_Xs)
129 Q = sinkhorn(a, g, C_Xs, reg=reg_init, numItermax=10000, stopThr=1e-3)
130
131 # Init R
132 kmeans_Xt = sklearn.cluster.KMeans(
133 n_clusters=rank, random_state=random_state, n_init="auto"
134 )
135 kmeans_Xt.fit(X_t)
136 Z_Xt = nx.from_numpy(kmeans_Xt.cluster_centers_)
137 C_Xt = dist(X_t, Z_Xt) # shape (nt, rank)
138 C_Xt = C_Xt / nx.max(C_Xt)
139 R = sinkhorn(b, g, C_Xt, reg=reg_init, numItermax=10000, stopThr=1e-3)
140
141 else:
142 raise ImportError(
143 "Scikit-learn should be installed to use the 'kmeans' init."
144 )
145
146 return Q, R, g
147
148
149 def compute_lr_sqeuclidean_matrix(X_s, X_t, rescale_cost, nx=None):
150 """
151 Compute the low rank decomposition of a squared euclidean distance matrix.
152 This function won't work for other distance metrics.
153
154 See "Section 3.5, proposition 1"
155
156 Parameters
157 ----------
158 X_s : array-like, shape (n_samples_a, dim)
159 samples in the source domain
160 X_t : array-like, shape (n_samples_b, dim)
161 samples in the target domain
162 rescale_cost : bool
163 Rescale the low rank factorization of the sqeuclidean cost matrix
164 nx : default None
165 POT backend
166
167
168 Returns
169 ----------
170 M1 : array-like, shape (n_samples_a, dim+2)
171 First low rank decomposition of the distance matrix
172 M2 : array-like, shape (n_samples_b, dim+2)
173 Second low rank decomposition of the distance matrix
174
175
176 References
177 -----------
178 .. [65] Scetbon, M., Cuturi, M., & Peyré, G. (2021).
179 "Low-rank Sinkhorn factorization". In International Conference on Machine Learning.
180 """
181
182 if nx is None:
183 nx = get_backend(X_s, X_t)
184
185 ns = X_s.shape[0]
186 nt = X_t.shape[0]
187
188 # First low rank decomposition of the cost matrix (A)
189 array1 = nx.reshape(nx.sum(X_s**2, 1), (-1, 1))
190 array2 = nx.ones((ns, 1), type_as=X_s)
191 M1 = nx.concatenate((array1, array2, -2 * X_s), axis=1)
192
193 # Second low rank decomposition of the cost matrix (B)
194 array1 = nx.ones((nt, 1), type_as=X_s)
195 array2 = nx.reshape(nx.sum(X_t**2, 1), (-1, 1))
196 M2 = nx.concatenate((array1, array2, X_t), axis=1)
197
198 if rescale_cost is True:
199 M1 = M1 / nx.sqrt(nx.max(M1))
200 M2 = M2 / nx.sqrt(nx.max(M2))
201
202 return M1, M2
203
204
205 def _LR_Dysktra(eps1, eps2, eps3, p1, p2, alpha, stopThr, numItermax, warn, nx=None):
206 """
207 Implementation of the Dykstra algorithm for the Low Rank sinkhorn OT solver.
208 This function is specific to lowrank_sinkhorn.
209
210 Parameters
211 ----------
212 eps1 : array-like, shape (n_samples_a, r)
213 First input parameter of the Dykstra algorithm
214 eps2 : array-like, shape (n_samples_b, r)
215 Second input parameter of the Dykstra algorithm
216 eps3 : array-like, shape (r,)
217 Third input parameter of the Dykstra algorithm
218 p1 : array-like, shape (n_samples_a,)
219 Samples weights in the source domain (same as "a" in lowrank_sinkhorn)
220 p2 : array-like, shape (n_samples_b,)
221 Samples weights in the target domain (same as "b" in lowrank_sinkhorn)
222 alpha: int
223 Lower bound for the weight vector g (same as "alpha" in lowrank_sinkhorn)
224 stopThr : float
225 Stop threshold on error
226 numItermax : int
227 Max number of iterations
228 warn : bool, optional
229 if True, raises a warning if the algorithm doesn't convergence.
230 nx : default None
231 POT backend
232
233
234 Returns
235 ----------
236 Q : array-like, shape (n_samples_a, r)
237 Dykstra update of the first low-rank matrix decomposition Q
238 R: array-like, shape (n_samples_b, r)
239 Dykstra update of the Second low-rank matrix decomposition R
240 g : array-like, shape (r, )
241 Dykstra update of the weight vector g
242
243
244 References
245 ----------
246 .. [65] Scetbon, M., Cuturi, M., & Peyré, G. (2021).
247 "Low-rank Sinkhorn Factorization". In International Conference on Machine Learning.
248
249 """
250
251 # POT backend if None
252 if nx is None:
253 nx = get_backend(eps1, eps2, eps3, p1, p2)
254
255 # ----------------- Initialisation of Dykstra algorithm -----------------
256 r = len(eps3) # rank
257 g_ = nx.copy(eps3) # \tilde{g}
258 q3_1, q3_2 = nx.ones(r, type_as=p1), nx.ones(r, type_as=p1) # q^{(3)}_1, q^{(3)}_2
259 v1_, v2_ = (
260 nx.ones(r, type_as=p1),
261 nx.ones(r, type_as=p1),
262 ) # \tilde{v}^{(1)}, \tilde{v}^{(2)}
263 q1, q2 = nx.ones(r, type_as=p1), nx.ones(r, type_as=p1) # q^{(1)}, q^{(2)}
264 err = 1 # initial error
265
266 # --------------------- Dykstra algorithm -------------------------
267
268 # See Section 3.3 - "Algorithm 2 LR-Dykstra" in paper
269
270 for ii in range(numItermax):
271 if err > stopThr:
272 # Compute u^{(1)} and u^{(2)}
273 u1 = p1 / nx.dot(eps1, v1_)
274 u2 = p2 / nx.dot(eps2, v2_)
275
276 # Compute g, g^{(3)}_1 and update \tilde{g}
277 g = nx.maximum(alpha, g_ * q3_1)
278 q3_1 = (g_ * q3_1) / g
279 g_ = nx.copy(g)
280
281 # Compute new value of g with \prod
282 prod1 = (v1_ * q1) * nx.dot(eps1.T, u1)
283 prod2 = (v2_ * q2) * nx.dot(eps2.T, u2)
284 g = (g_ * q3_2 * prod1 * prod2) ** (1 / 3)
285
286 # Compute v^{(1)} and v^{(2)}
287 v1 = g / nx.dot(eps1.T, u1)
288 v2 = g / nx.dot(eps2.T, u2)
289
290 # Compute q^{(1)}, q^{(2)} and q^{(3)}_2
291 q1 = (v1_ * q1) / v1
292 q2 = (v2_ * q2) / v2
293 q3_2 = (g_ * q3_2) / g
294
295 # Update values of \tilde{v}^{(1)}, \tilde{v}^{(2)} and \tilde{g}
296 v1_, v2_ = nx.copy(v1), nx.copy(v2)
297 g_ = nx.copy(g)
298
299 # Compute error
300 err1 = nx.sum(nx.abs(u1 * (eps1 @ v1) - p1))
301 err2 = nx.sum(nx.abs(u2 * (eps2 @ v2) - p2))
302 err = err1 + err2
303
304 else:
305 break
306
307 else:
308 if warn:
309 warnings.warn(
310 "Dykstra did not converge. You might want to "
311 "increase the number of iterations `numItermax` "
312 )
313
314 # Compute low rank matrices Q, R
315 Q = u1[:, None] * eps1 * v1[None, :]
316 R = u2[:, None] * eps2 * v2[None, :]
317
318 return Q, R, g
319
320
321 def lowrank_sinkhorn(
322 X_s,
323 X_t,
324 a=None,
325 b=None,
326 reg=0,
327 rank=None,
328 alpha=1e-10,
329 rescale_cost=True,
330 init="random",
331 reg_init=1e-1,
332 seed_init=49,
333 gamma_init="rescale",
334 numItermax=2000,
335 stopThr=1e-7,
336 warn=True,
337 log=False,
338 ):
339 r"""
340 Solve the entropic regularization optimal transport problem under low-nonnegative rank constraints
341 on the couplings.
342
343 The function solves the following optimization problem:
344
345 .. math::
346 \mathop{\inf_{(\mathbf{Q},\mathbf{R},\mathbf{g}) \in \mathcal{C}(\mathbf{a},\mathbf{b},r)}} \langle \mathbf{C}, \mathbf{Q}\mathrm{diag}(1/\mathbf{g})\mathbf{R}^\top \rangle -
347 \mathrm{reg} \cdot H((\mathbf{Q}, \mathbf{R}, \mathbf{g}))
348
349 where :
350
351 - :math:`\mathbf{C}` is the (`dim_a`, `dim_b`) metric cost matrix
352 - :math:`H((\mathbf{Q}, \mathbf{R}, \mathbf{g}))` is the values of the three respective entropies evaluated for each term.
353 - :math:`\mathbf{Q}` and :math:`\mathbf{R}` are the low-rank matrix decomposition of the OT plan
354 - :math:`\mathbf{g}` is the weight vector for the low-rank decomposition of the OT plan
355 - :math:`\mathbf{a}` and :math:`\mathbf{b}` are source and target weights (histograms, both sum to 1)
356 - :math:`r` is the rank of the OT plan
357 - :math:`\mathcal{C}(\mathbf{a}, \mathbf{b}, r)` are the low-rank couplings of the OT problem
358
359
360 Parameters
361 ----------
362 X_s : array-like, shape (n_samples_a, dim)
363 samples in the source domain
364 X_t : array-like, shape (n_samples_b, dim)
365 samples in the target domain
366 a : array-like, shape (n_samples_a,)
367 samples weights in the source domain
368 b : array-like, shape (n_samples_b,)
369 samples weights in the target domain
370 reg : float, optional
371 Regularization term >0
372 rank : int, optional. Default is None. (>0)
373 Nonnegative rank of the OT plan. If None, min(ns, nt) is considered.
374 alpha : int, optional. Default is 1e-10. (>0 and <1/r)
375 Lower bound for the weight vector g.
376 rescale_cost : bool, optional. Default is False
377 Rescale the low rank factorization of the sqeuclidean cost matrix
378 init : str, optional. Default is 'random'.
379 Initialization strategy for the low rank couplings. 'random', 'deterministic' or 'kmeans'
380 reg_init : float, optional. Default is 1e-1. (>0)
381 Regularization term for a 'kmeans' init. If None, 1 is considered.
382 seed_init : int, optional. Default is 49. (>0)
383 Random state for a 'random' or 'kmeans' init strategy.
384 gamma_init : str, optional. Default is "rescale".
385 Initialization strategy for gamma. 'rescale', or 'theory'
386 Gamma is a constant that scales the convergence criterion of the Mirror Descent
387 optimization scheme used to compute the low-rank couplings (Q, R and g)
388 numItermax : int, optional. Default is 2000.
389 Max number of iterations for the Dykstra algorithm
390 stopThr : float, optional. Default is 1e-7.
391 Stop threshold on error (>0) in Dykstra
392 warn : bool, optional
393 if True, raises a warning if the algorithm doesn't convergence.
394 log : bool, optional
395 record log if True
396
397
398 Returns
399 ---------
400 Q : array-like, shape (n_samples_a, r)
401 First low-rank matrix decomposition of the OT plan
402 R: array-like, shape (n_samples_b, r)
403 Second low-rank matrix decomposition of the OT plan
404 g : array-like, shape (r, )
405 Weight vector for the low-rank decomposition of the OT
406 log : dict (lazy_plan, value and value_linear)
407 log dictionary return only if log==True in parameters
408
409
410 References
411 ----------
412 .. [65] Scetbon, M., Cuturi, M., & Peyré, G. (2021).
413 "Low-rank Sinkhorn Factorization". In International Conference on Machine Learning.
414
415 """
416
417 # POT backend
418 nx = get_backend(X_s, X_t)
419 ns, nt = X_s.shape[0], X_t.shape[0]
420
421 # Initialize weights a, b
422 if a is None:
423 a = unif(ns, type_as=X_s)
424 if b is None:
425 b = unif(nt, type_as=X_t)
426
427 # Compute rank (see Section 3.1, def 1)
428 r = rank
429 if rank is None:
430 r = min(ns, nt)
431 else:
432 r = min(ns, nt, rank)
433
434 if r <= 0:
435 raise ValueError("The rank parameter cannot have a negative value")
436
437 # Dykstra won't converge if 1/rank < alpha (see Section 3.2)
438 if 1 / r < alpha:
439 raise ValueError(
440 "alpha ({a}) should be smaller than 1/rank ({r}) for the Dykstra algorithm to converge.".format(
441 a=alpha, r=1 / rank
442 )
443 )
444
445 # Low rank decomposition of the sqeuclidean cost matrix
446 M1, M2 = compute_lr_sqeuclidean_matrix(X_s, X_t, rescale_cost, nx)
447
448 # Initialize the low rank matrices Q, R, g
449 Q, R, g = _init_lr_sinkhorn(X_s, X_t, a, b, r, init, reg_init, seed_init, nx=nx)
450
451 # Gamma initialization
452 if gamma_init == "theory":
453 L = nx.sqrt(
454 3 * (2 / (alpha**4)) * ((nx.norm(M1) * nx.norm(M2)) ** 2)
455 + (reg + (2 / (alpha**3)) * (nx.norm(M1) * nx.norm(M2))) ** 2
456 )
457 gamma = 1 / (2 * L)
458
459 if gamma_init not in ["rescale", "theory"]:
460 raise (
461 NotImplementedError('Not implemented gamma_init="{}"'.format(gamma_init))
462 )
463
464 # -------------------------- Low rank algorithm ------------------------------
465 # see "Section 3.3, Algorithm 3 LOT"
466
467 for ii in range(100):
468 # Compute C*R dot using the lr decomposition of C
469 CR = nx.dot(M2.T, R)
470 CR_ = nx.dot(M1, CR)
471 diag_g = (1 / g)[None, :]
472 CR_g = CR_ * diag_g
473
474 # Compute C.T * Q using the lr decomposition of C
475 CQ = nx.dot(M1.T, Q)
476 CQ_ = nx.dot(M2, CQ)
477 CQ_g = CQ_ * diag_g
478
479 # Compute omega
480 omega = nx.diag(nx.dot(Q.T, CR_))
481
482 # Rescale gamma at each iteration
483 if gamma_init == "rescale":
484 norm_1 = nx.max(nx.abs(CR_ * diag_g + reg * nx.log(Q))) ** 2
485 norm_2 = nx.max(nx.abs(CQ_ * diag_g + reg * nx.log(R))) ** 2
486 norm_3 = nx.max(nx.abs(-omega * diag_g)) ** 2
487 gamma = 10 / max(norm_1, norm_2, norm_3)
488
489 eps1 = nx.exp(-gamma * CR_g - ((gamma * reg) - 1) * nx.log(Q))
490 eps2 = nx.exp(-gamma * CQ_g - ((gamma * reg) - 1) * nx.log(R))
491 eps3 = nx.exp((gamma * omega / (g**2)) - (gamma * reg - 1) * nx.log(g))
492
493 # LR Dykstra algorithm
494 Q, R, g = _LR_Dysktra(
495 eps1, eps2, eps3, a, b, alpha, stopThr, numItermax, warn, nx
496 )
497 Q = Q + 1e-16
498 R = R + 1e-16
499 g = g + 1e-16
500
501 # ----------------- Compute lazy_plan, value and value_linear ------------------
502 # see "Section 3.2: The Low-rank OT Problem" in the paper
503
504 # Compute lazy plan (using LazyTensor class)
505 lazy_plan = get_lowrank_lazytensor(Q, R, 1 / g)
506
507 # Compute value_linear (using trace formula)
508 v1 = nx.dot(Q.T, M1)
509 v2 = nx.dot(R, (v1.T * diag_g).T)
510 value_linear = nx.sum(nx.diag(nx.dot(M2.T, v2)))
511
512 # Compute value with entropy reg (see "Section 3.2" in the paper)
513 reg_Q = nx.sum(Q * nx.log(Q + 1e-16)) # entropy for Q
514 reg_g = nx.sum(g * nx.log(g + 1e-16)) # entropy for g
515 reg_R = nx.sum(R * nx.log(R + 1e-16)) # entropy for R
516 value = value_linear + reg * (reg_Q + reg_g + reg_R)
517
518 if log:
519 dict_log = dict()
520 dict_log["value"] = value
521 dict_log["value_linear"] = value_linear
522 dict_log["lazy_plan"] = lazy_plan
523
524 return Q, R, g, dict_log
525
526 return Q, R, g