Debian Codegraph @

ot/gromov/_lowrank.py

raw symbols SCIP
1 """
2 Low rank Gromov-Wasserstein solver
3 """
4
5 # Author: Laurène David <[email protected]>
6 #
7 # License: MIT License
8
9 import warnings
10 from ..utils import unif, get_lowrank_lazytensor
11 from ..backend import get_backend
12 from ..lowrank import compute_lr_sqeuclidean_matrix, _init_lr_sinkhorn, _LR_Dysktra
13
14
15 def _flat_product_operator(X, nx=None):
16 r"""
17 Implementation of the flattened out-product operator.
18
19 This function is used in low rank gromov wasserstein to compute the low rank decomposition of
20 a cost matrix's squared hadamard product (page 6 in paper).
21
22 Parameters
23 ----------
24 X: array-like, shape (n_samples, n_col)
25 Input matrix for operator
26
27 nx: default None
28 POT backend
29
30 Returns
31 ----------
32 X_flat: array-like, shape (n_samples, n_col**2)
33 Matrix with flattened out-product operator applied on each row
34
35 References
36 ----------
37 .. [67] Scetbon, M., Peyré, G. & Cuturi, M. (2022).
38 "Linear-Time GromovWasserstein Distances using Low Rank Couplings and Costs".
39 In International Conference on Machine Learning (ICML), 2022.
40
41 """
42
43 if nx is None:
44 nx = get_backend(X)
45
46 n = X.shape[0]
47 x1 = X[0, :][:, None]
48 X_flat = nx.dot(x1, x1.T).flatten()[:, None]
49
50 for i in range(1, n):
51 x = X[i, :][:, None]
52 x_out = nx.dot(x, x.T).flatten()[:, None]
53 X_flat = nx.concatenate((X_flat, x_out), axis=1)
54
55 X_flat = X_flat.T
56
57 return X_flat
58
59
60 def lowrank_gromov_wasserstein_samples(
61 X_s,
62 X_t,
63 a=None,
64 b=None,
65 reg=0,
66 rank=None,
67 alpha=1e-10,
68 gamma_init="rescale",
69 rescale_cost=True,
70 cost_factorized_Xs=None,
71 cost_factorized_Xt=None,
72 stopThr=1e-4,
73 numItermax=1000,
74 stopThr_dykstra=1e-3,
75 numItermax_dykstra=10000,
76 seed_init=49,
77 warn=True,
78 warn_dykstra=False,
79 log=False,
80 ):
81 r"""
82 Solve the entropic regularization Gromov-Wasserstein transport problem under low-nonnegative rank constraints
83 on the couplings and cost matrices.
84
85 Squared euclidean distance matrices are considered for the target and source distributions.
86
87 The function solves the following optimization problem:
88
89 .. math::
90 \mathop{\min_{(Q,R,g) \in \mathcal{C(a,b,r)}}} \mathcal{Q}_{A,B}(Q\mathrm{diag}(1/g)R^T) -
91 \epsilon \cdot H((Q,R,g))
92
93 where :
94
95 - :math: `A` is the (`dim_a`, `dim_a`) square pairwise cost matrix of the source domain.
96 - :math: `B` is the (`dim_a`, `dim_a`) square pairwise cost matrix of the target domain.
97 - :math: `\mathcal{Q}_{A,B}` is quadratic objective function of the Gromov Wasserstein plan.
98 - :math: `Q` and `R` are the low-rank matrix decomposition of the Gromov-Wasserstein plan.
99 - :math: `g` is the weight vector for the low-rank decomposition of the Gromov-Wasserstein plan.
100 - :math:`\mathbf{a}` and :math:`\mathbf{b}` are source and target weights (histograms, both sum to 1).
101 - :math: `r` is the rank of the Gromov-Wasserstein plan.
102 - :math: `\mathcal{C(a,b,r)}` are the low-rank couplings of the OT problem.
103 - :math:`H((Q,R,g))` is the values of the three respective entropies evaluated for each term.
104
105
106 Parameters
107 ----------
108 X_s : array-like, shape (n_samples_a, dim_Xs)
109 Samples in the source domain
110 X_t : array-like, shape (n_samples_b, dim_Xt)
111 Samples in the target domain
112 a : array-like, shape (n_samples_a,), optional
113 Samples weights in the source domain
114 If let to its default value None, uniform distribution is taken.
115 b : array-like, shape (n_samples_b,), optional
116 Samples weights in the target domain
117 If let to its default value None, uniform distribution is taken.
118 reg : float, optional
119 Regularization term >=0
120 rank : int, optional. Default is None. (>0)
121 Nonnegative rank of the OT plan. If None, min(ns, nt) is considered.
122 alpha : int, optional. Default is 1e-10. (>0 and <1/r)
123 Lower bound for the weight vector g.
124 rescale_cost : bool, optional. Default is False
125 Rescale the low rank factorization of the sqeuclidean cost matrix
126 seed_init : int, optional. Default is 49. (>0)
127 Random state for the 'random' initialization of low rank couplings
128 gamma_init : str, optional. Default is "rescale".
129 Initialization strategy for gamma. 'rescale', or 'theory'
130 Gamma is a constant that scales the convergence criterion of the Mirror Descent
131 optimization scheme used to compute the low-rank couplings (Q, R and g)
132 numItermax : int, optional. Default is 1000.
133 Max number of iterations for Low Rank GW
134 stopThr : float, optional. Default is 1e-4.
135 Stop threshold on error (>0) for Low Rank GW
136 The error is the sum of Kullback Divergences computed for each low rank
137 coupling (Q, R and g) and scaled using gamma.
138 numItermax_dykstra : int, optional. Default is 2000.
139 Max number of iterations for the Dykstra algorithm
140 stopThr_dykstra : float, optional. Default is 1e-7.
141 Stop threshold on error (>0) in Dykstra
142 cost_factorized_Xs: tuple, optional. Default is None
143 Tuple with two pre-computed low rank decompositions (A1, A2) of the source cost
144 matrix. Both matrices should have a shape of (n_samples_a, dim_Xs + 2).
145 If None, the low rank cost matrices will be computed as sqeuclidean cost matrices.
146 cost_factorized_Xt: tuple, optional. Default is None
147 Tuple with two pre-computed low rank decompositions (B1, B2) of the target cost
148 matrix. Both matrices should have a shape of (n_samples_b, dim_Xt + 2).
149 If None, the low rank cost matrices will be computed as sqeuclidean cost matrices.
150 warn : bool, optional
151 if True, raises a warning if the low rank GW algorithm doesn't convergence.
152 warn_dykstra: bool, optional
153 if True, raises a warning if the Dykstra algorithm doesn't convergence.
154 log : bool, optional
155 record log if True
156
157
158 Returns
159 ---------
160 Q : array-like, shape (n_samples_a, r)
161 First low-rank matrix decomposition of the OT plan
162 R: array-like, shape (n_samples_b, r)
163 Second low-rank matrix decomposition of the OT plan
164 g : array-like, shape (r, )
165 Weight vector for the low-rank decomposition of the OT
166 log : dict (lazy_plan, value and value_linear)
167 log dictionary return only if log==True in parameters
168
169
170 References
171 ----------
172 .. [67] Scetbon, M., Peyré, G. & Cuturi, M. (2022).
173 "Linear-Time GromovWasserstein Distances using Low Rank Couplings and Costs".
174 In International Conference on Machine Learning (ICML), 2022.
175
176 """
177
178 # POT backend
179 nx = get_backend(X_s, X_t)
180 ns, nt = X_s.shape[0], X_t.shape[0]
181
182 # Initialize weights a, b
183 if a is None:
184 a = unif(ns, type_as=X_s)
185 if b is None:
186 b = unif(nt, type_as=X_t)
187
188 # Compute rank (see Section 3.1, def 1)
189 r = rank
190 if rank is None:
191 r = min(ns, nt)
192 else:
193 r = min(ns, nt, rank)
194
195 if r <= 0:
196 raise ValueError("The rank parameter cannot have a negative value")
197
198 # Dykstra won't converge if 1/rank < alpha (see Section 3.2)
199 if 1 / r < alpha:
200 raise ValueError(
201 "alpha ({a}) should be smaller than 1/rank ({r}) for the Dykstra algorithm to converge.".format(
202 a=alpha, r=1 / rank
203 )
204 )
205
206 if cost_factorized_Xs is not None:
207 A1, A2 = cost_factorized_Xs
208 else:
209 A1, A2 = compute_lr_sqeuclidean_matrix(X_s, X_s, rescale_cost, nx=nx)
210
211 if cost_factorized_Xt is not None:
212 B1, B2 = cost_factorized_Xt
213 else:
214 B1, B2 = compute_lr_sqeuclidean_matrix(X_t, X_t, rescale_cost, nx=nx)
215
216 # Initial values for LR couplings (Q, R, g) with LOT
217 Q, R, g = _init_lr_sinkhorn(
218 X_s, X_t, a, b, r, init="random", random_state=seed_init, reg_init=None, nx=nx
219 )
220
221 # Gamma initialization
222 if gamma_init == "theory":
223 L = (27 * nx.norm(A1) * nx.norm(A2)) / alpha**4
224 gamma = 1 / (2 * L)
225
226 if gamma_init not in ["rescale", "theory"]:
227 raise (
228 NotImplementedError('Not implemented gamma_init="{}"'.format(gamma_init))
229 )
230
231 # initial value of error
232 err = 1
233
234 for ii in range(numItermax):
235 Q_prev = Q
236 R_prev = R
237 g_prev = g
238
239 if err > stopThr:
240 # Compute cost matrices
241 C1 = nx.dot(A2.T, Q * (1 / g)[None, :])
242 C1 = -4 * nx.dot(A1, C1)
243 C2 = nx.dot(R.T, B1)
244 C2 = nx.dot(C2, B2.T)
245 diag_g = (1 / g)[None, :]
246
247 # Compute C*R dot using the lr decomposition of C
248 CR = nx.dot(C2, R)
249 CR = nx.dot(C1, CR)
250 CR_g = CR * diag_g
251
252 # Compute C.T * Q using the lr decomposition of C
253 CQ = nx.dot(C1.T, Q)
254 CQ = nx.dot(C2.T, CQ)
255 CQ_g = CQ * diag_g
256
257 # Compute omega
258 omega = nx.diag(nx.dot(Q.T, CR))
259
260 # Rescale gamma at each iteration
261 if gamma_init == "rescale":
262 norm_1 = nx.max(nx.abs(CR_g + reg * nx.log(Q))) ** 2
263 norm_2 = nx.max(nx.abs(CQ_g + reg * nx.log(R))) ** 2
264 norm_3 = nx.max(nx.abs(-omega * (diag_g**2))) ** 2
265 gamma = 10 / max(norm_1, norm_2, norm_3)
266
267 K1 = nx.exp(-gamma * CR_g - ((gamma * reg) - 1) * nx.log(Q))
268 K2 = nx.exp(-gamma * CQ_g - ((gamma * reg) - 1) * nx.log(R))
269 K3 = nx.exp((gamma * omega / (g**2)) - (gamma * reg - 1) * nx.log(g))
270
271 # Update couplings with LR Dykstra algorithm
272 Q, R, g = _LR_Dysktra(
273 K1,
274 K2,
275 K3,
276 a,
277 b,
278 alpha,
279 stopThr_dykstra,
280 numItermax_dykstra,
281 warn_dykstra,
282 nx,
283 )
284
285 # Update error with kullback-divergence
286 err_1 = ((1 / gamma) ** 2) * (nx.kl_div(Q, Q_prev) + nx.kl_div(Q_prev, Q))
287 err_2 = ((1 / gamma) ** 2) * (nx.kl_div(R, R_prev) + nx.kl_div(R_prev, R))
288 err_3 = ((1 / gamma) ** 2) * (nx.kl_div(g, g_prev) + nx.kl_div(g_prev, g))
289 err = err_1 + err_2 + err_3
290
291 # fix divide by zero
292 Q = Q + 1e-16
293 R = R + 1e-16
294 g = g + 1e-16
295
296 else:
297 break
298
299 else:
300 if warn:
301 warnings.warn(
302 "Low Rank GW did not converge. You might want to "
303 "increase the number of iterations `numItermax` "
304 )
305
306 # Update low rank costs
307 C1 = nx.dot(A2.T, Q * (1 / g)[None, :])
308 C1 = -4 * nx.dot(A1, C1)
309 C2 = nx.dot(R.T, B1)
310 C2 = nx.dot(C2, B2.T)
311
312 # Compute lazy plan (using LazyTensor class)
313 lazy_plan = get_lowrank_lazytensor(Q, R, 1 / g)
314
315 # Compute value_quad
316 A1_, A2_ = _flat_product_operator(A1, nx), _flat_product_operator(A2, nx)
317 B1_, B2_ = _flat_product_operator(B1, nx), _flat_product_operator(B2, nx)
318
319 x_ = nx.dot(A1_, nx.dot(A2_.T, a))
320 y_ = nx.dot(B1_, nx.dot(B2_.T, b))
321 c1 = nx.dot(x_, a) + nx.dot(y_, b)
322
323 G = nx.dot(C1, nx.dot(C2, R))
324 G = nx.dot(Q.T, G * diag_g)
325 value_quad = c1 + nx.trace(G) / 2
326
327 if reg != 0:
328 reg_Q = nx.sum(Q * nx.log(Q + 1e-16)) # entropy for Q
329 reg_g = nx.sum(g * nx.log(g + 1e-16)) # entropy for g
330 reg_R = nx.sum(R * nx.log(R + 1e-16)) # entropy for R
331 value = value_quad + reg * (reg_Q + reg_g + reg_R)
332 else:
333 value = value_quad
334
335 if log:
336 dict_log = dict()
337 dict_log["value"] = value
338 dict_log["value_quad"] = value_quad
339 dict_log["lazy_plan"] = lazy_plan
340
341 return Q, R, g, dict_log
342
343 return Q, R, g