Debian Codegraph @

ot/unbalanced/_lbfgs.py

raw symbols SCIP
1 # -*- coding: utf-8 -*-
2 """
3 Regularized Unbalanced OT solvers
4 """
5
6 # Author: Hicham Janati <[email protected]>
7 # Laetitia Chapel <[email protected]>
8 # Quang Huy Tran <[email protected]>
9 #
10 # License: MIT License
11
12 import warnings
13 import numpy as np
14 from scipy.optimize import minimize, Bounds
15
16 from ..backend import get_backend
17 from ..utils import list_to_array, get_parameter_pair
18
19
20 def _get_loss_unbalanced(a, b, c, M, reg, reg_m1, reg_m2, reg_div="kl", regm_div="kl"):
21 """
22 Return loss function for the L-BFGS-B solver
23
24 .. note:: This function will be fed into scipy.optimize, so all input arrays must be Numpy arrays.
25
26 Parameters
27 ----------
28 a : array-like (dim_a,)
29 Unnormalized histogram of dimension `dim_a`
30 b : array-like (dim_b,)
31 Unnormalized histogram of dimension `dim_b`
32 M : array-like (dim_a, dim_b)
33 loss matrix
34 reg: float
35 regularization term >=0
36 c : array-like (dim_a, dim_b), optional (default = None)
37 Reference measure for the regularization.
38 If None, then use :math:`\mathbf{c} = \mathbf{a} \mathbf{b}^T`.
39 reg_m1: float
40 Marginal relaxation term with respect to the first marginal:
41 nonnegative (including 0) but cannot be infinity.
42 reg_m2: float
43 Marginal relaxation term with respect to the second marginal:
44 nonnegative (including 0) but cannot be infinity.
45 reg_div: string, optional
46 Divergence used for regularization.
47 Can take three values: 'entropy' (negative entropy), or
48 'kl' (Kullback-Leibler) or 'l2' (half-squared) or a tuple
49 of two calable functions returning the reg term and its derivative.
50 Note that the callable functions should be able to handle Numpy arrays
51 and not tesors from the backend
52 regm_div: string, optional
53 Divergence to quantify the difference between the marginals.
54 Can take three values: 'kl' (Kullback-Leibler) or 'l2' (half-squared) or 'tv' (Total Variation)
55
56 Returns
57 -------
58 Loss function (scipy.optimize compatible) for regularized unbalanced OT
59 """
60
61 m, n = M.shape
62 nx_numpy = get_backend(M, a, b)
63
64 def reg_l2(G):
65 return np.sum((G - c) ** 2) / 2
66
67 def grad_l2(G):
68 return G - c
69
70 def reg_kl(G):
71 return nx_numpy.kl_div(G, c, mass=True)
72
73 def grad_kl(G):
74 return np.log(G / c + 1e-16)
75
76 def reg_entropy(G):
77 return np.sum(G * np.log(G + 1e-16)) - np.sum(G)
78
79 def grad_entropy(G):
80 return np.log(G + 1e-16)
81
82 if reg_div == "kl":
83 reg_fun = reg_kl
84 grad_reg_fun = grad_kl
85 elif reg_div == "entropy":
86 reg_fun = reg_entropy
87 grad_reg_fun = grad_entropy
88 elif isinstance(reg_div, tuple):
89 reg_fun = reg_div[0]
90 grad_reg_fun = reg_div[1]
91 else:
92 reg_fun = reg_l2
93 grad_reg_fun = grad_l2
94
95 def marg_l2(G):
96 return reg_m1 * 0.5 * np.sum((G.sum(1) - a) ** 2) + reg_m2 * 0.5 * np.sum(
97 (G.sum(0) - b) ** 2
98 )
99
100 def grad_marg_l2(G):
101 return reg_m1 * np.outer((G.sum(1) - a), np.ones(n)) + reg_m2 * np.outer(
102 np.ones(m), (G.sum(0) - b)
103 )
104
105 def marg_kl(G):
106 return reg_m1 * nx_numpy.kl_div(
107 G.sum(1), a, mass=True
108 ) + reg_m2 * nx_numpy.kl_div(G.sum(0), b, mass=True)
109
110 def grad_marg_kl(G):
111 return reg_m1 * np.outer(
112 np.log(G.sum(1) / a + 1e-16), np.ones(n)
113 ) + reg_m2 * np.outer(np.ones(m), np.log(G.sum(0) / b + 1e-16))
114
115 def marg_tv(G):
116 return reg_m1 * np.sum(np.abs(G.sum(1) - a)) + reg_m2 * np.sum(
117 np.abs(G.sum(0) - b)
118 )
119
120 def grad_marg_tv(G):
121 return reg_m1 * np.outer(np.sign(G.sum(1) - a), np.ones(n)) + reg_m2 * np.outer(
122 np.ones(m), np.sign(G.sum(0) - b)
123 )
124
125 if regm_div == "kl":
126 regm_fun = marg_kl
127 grad_regm_fun = grad_marg_kl
128 elif regm_div == "tv":
129 regm_fun = marg_tv
130 grad_regm_fun = grad_marg_tv
131 else:
132 regm_fun = marg_l2
133 grad_regm_fun = grad_marg_l2
134
135 def _func(G):
136 G = G.reshape((m, n))
137
138 # compute loss
139 val = np.sum(G * M) + regm_fun(G)
140 if reg > 0:
141 val = val + reg * reg_fun(G)
142 # compute gradient
143 grad = M + grad_regm_fun(G)
144 if reg > 0:
145 grad = grad + reg * grad_reg_fun(G)
146
147 return val, grad.ravel()
148
149 return _func
150
151
152 def lbfgsb_unbalanced(
153 a,
154 b,
155 M,
156 reg,
157 reg_m,
158 c=None,
159 reg_div="kl",
160 regm_div="kl",
161 G0=None,
162 numItermax=1000,
163 stopThr=1e-15,
164 method="L-BFGS-B",
165 verbose=False,
166 log=False,
167 ):
168 r"""
169 Solve the unbalanced optimal transport problem and return the OT plan using L-BFGS-B algorithm.
170 The function solves the following optimization problem:
171
172 .. math::
173 W = \arg \min_\gamma \quad \langle \gamma, \mathbf{M} \rangle_F +
174 \mathrm{reg} \mathrm{div}(\gamma, \mathbf{c}) +
175 \mathrm{reg_{m1}} \cdot \mathrm{div_m}(\gamma \mathbf{1}, \mathbf{a}) +
176 \mathrm{reg_{m2}} \cdot \mathrm{div_m}(\gamma^T \mathbf{1}, \mathbf{b})
177
178 s.t.
179 \gamma \geq 0
180
181 where:
182
183 - :math:`\mathbf{M}` is the (`dim_a`, `dim_b`) metric cost matrix
184 - :math:`\mathbf{a}` and :math:`\mathbf{b}` are source and target unbalanced distributions
185 - :math:`\mathbf{c}` is a reference distribution for the regularization
186 - :math:`\mathrm{div_m}` is a divergence, either Kullback-Leibler divergence,
187 or half-squared :math:`\ell_2` divergence, or Total variation
188 - :math:`\mathrm{div}` is a divergence, either Kullback-Leibler divergence,
189 or half-squared :math:`\ell_2` divergence
190
191 .. note:: This function is backend-compatible and will work on arrays
192 from all compatible backends. First, it converts all arrays into Numpy arrays,
193 then uses the L-BFGS-B algorithm from scipy.optimize to solve the optimization problem.
194
195 Parameters
196 ----------
197 a : array-like (dim_a,)
198 Unnormalized histogram of dimension `dim_a`
199 If `a` is an empty list or array ([]),
200 then `a` is set to uniform distribution.
201 b : array-like (dim_b,)
202 Unnormalized histogram of dimension `dim_b`
203 If `b` is an empty list or array ([]),
204 then `b` is set to uniform distribution.
205 M : array-like (dim_a, dim_b)
206 loss matrix
207 reg: float
208 regularization term >=0
209 c : array-like (dim_a, dim_b), optional (default = None)
210 Reference measure for the regularization.
211 If None, then use :math:`\mathbf{c} = \mathbf{a} \mathbf{b}^T`.
212 reg_m: float or indexable object of length 1 or 2
213 Marginal relaxation term: nonnegative (including 0) but cannot be infinity.
214 If :math:`\mathrm{reg_{m}}` is a scalar or an indexable object of length 1,
215 then the same :math:`\mathrm{reg_{m}}` is applied to both marginal relaxations.
216 If :math:`\mathrm{reg_{m}}` is an array, it must be a Numpy array.
217 reg_div: string, optional
218 Divergence used for regularization.
219 Can take three values: 'entropy' (negative entropy), or
220 'kl' (Kullback-Leibler) or 'l2' (half-squared) or a tuple
221 of two calable functions returning the reg term and its derivative.
222 Note that the callable functions should be able to handle Numpy arrays
223 and not tesors from the backend
224 regm_div: string, optional
225 Divergence to quantify the difference between the marginals.
226 Can take three values: 'kl' (Kullback-Leibler) or 'l2' (half-squared) or 'tv' (Total Variation)
227 G0: array-like (dim_a, dim_b)
228 Initialization of the transport matrix
229 numItermax : int, optional
230 Max number of iterations
231 stopThr : float, optional
232 Stop threshold on error (> 0)
233 verbose : bool, optional
234 Print information along iterations
235 log : bool, optional
236 record log if True
237
238 Returns
239 -------
240 gamma : (dim_a, dim_b) array-like
241 Optimal transportation matrix for the given parameters
242 log : dict
243 log dictionary returned only if `log` is `True`
244
245 Examples
246 --------
247 >>> import ot
248 >>> import numpy as np
249 >>> a=[.5, .5]
250 >>> b=[.5, .5]
251 >>> M=[[1., 36.],[9., 4.]]
252 >>> np.round(ot.unbalanced.lbfgsb_unbalanced(a, b, M, reg=0, reg_m=5, reg_div='kl', regm_div='kl'), 2)
253 array([[0.45, 0. ],
254 [0. , 0.34]])
255 >>> np.round(ot.unbalanced.lbfgsb_unbalanced(a, b, M, reg=0, reg_m=5, reg_div='l2', regm_div='l2'), 2)
256 array([[0.4, 0. ],
257 [0. , 0.1]])
258
259 References
260 ----------
261 .. [41] Chapel, L., Flamary, R., Wu, H., Févotte, C., and Gasso, G. (2021).
262 Unbalanced optimal transport through non-negative penalized
263 linear regression. NeurIPS.
264 See Also
265 --------
266 ot.lp.emd2 : Unregularized OT loss
267 ot.unbalanced.sinkhorn_unbalanced2 : Entropic regularized OT loss
268 """
269
270 # wrap the callable function to handle numpy arrays
271 if isinstance(reg_div, tuple):
272 f0, df0 = reg_div
273 try:
274 f0(G0)
275 df0(G0)
276 except BaseException:
277 warnings.warn(
278 "The callable functions should be able to handle numpy arrays, wrapper ar added to handle this which comes with overhead"
279 )
280
281 def f(x):
282 return nx.to_numpy(f0(nx.from_numpy(x, type_as=M0)))
283
284 def df(x):
285 return nx.to_numpy(df0(nx.from_numpy(x, type_as=M0)))
286
287 reg_div = (f, df)
288
289 else:
290 reg_div = reg_div.lower()
291 if reg_div not in ["entropy", "kl", "l2"]:
292 raise ValueError(
293 "Unknown reg_div = {}. Must be either 'entropy', 'kl' or 'l2', or a tuple".format(
294 reg_div
295 )
296 )
297
298 regm_div = regm_div.lower()
299 if regm_div not in ["kl", "l2", "tv"]:
300 raise ValueError(
301 "Unknown regm_div = {}. Must be either 'kl', 'l2' or 'tv'".format(regm_div)
302 )
303
304 reg_m1, reg_m2 = get_parameter_pair(reg_m)
305
306 M, a, b = list_to_array(M, a, b)
307 nx = get_backend(M, a, b)
308 M0 = M
309
310 dim_a, dim_b = M.shape
311
312 if len(a) == 0:
313 a = nx.ones(dim_a, type_as=M) / dim_a
314 if len(b) == 0:
315 b = nx.ones(dim_b, type_as=M) / dim_b
316
317 # convert to numpy
318 a, b, M, reg_m1, reg_m2, reg = nx.to_numpy(a, b, M, reg_m1, reg_m2, reg)
319 G0 = a[:, None] * b[None, :] if G0 is None else nx.to_numpy(G0)
320 c = a[:, None] * b[None, :] if c is None else nx.to_numpy(c)
321
322 _func = _get_loss_unbalanced(a, b, c, M, reg, reg_m1, reg_m2, reg_div, regm_div)
323
324 res = minimize(
325 _func,
326 G0.ravel(),
327 method=method,
328 jac=True,
329 bounds=Bounds(0, np.inf),
330 tol=stopThr,
331 options=dict(maxiter=numItermax, disp=verbose),
332 )
333
334 G = nx.from_numpy(res.x.reshape(M.shape), type_as=M0)
335
336 if log:
337 log = {"cost": nx.sum(G * M), "res": res}
338 log["total_cost"] = nx.from_numpy(res.fun, type_as=M0)
339 return G, log
340 else:
341 return G
342
343
344 def lbfgsb_unbalanced2(
345 a,
346 b,
347 M,
348 reg,
349 reg_m,
350 c=None,
351 reg_div="kl",
352 regm_div="kl",
353 G0=None,
354 returnCost="linear",
355 numItermax=1000,
356 stopThr=1e-15,
357 method="L-BFGS-B",
358 verbose=False,
359 log=False,
360 ):
361 r"""
362 Solve the unbalanced optimal transport problem and return the OT cost using L-BFGS-B.
363 The function solves the following optimization problem:
364
365 .. math::
366 \min_\gamma \quad \langle \gamma, \mathbf{M} \rangle_F +
367 \mathrm{reg} \mathrm{div}(\gamma, \mathbf{c}) +
368 \mathrm{reg_{m1}} \cdot \mathrm{div_m}(\gamma \mathbf{1}, \mathbf{a}) +
369 \mathrm{reg_{m2}} \cdot \mathrm{div_m}(\gamma^T \mathbf{1}, \mathbf{b})
370
371 s.t.
372 \gamma \geq 0
373
374 where:
375
376 - :math:`\mathbf{M}` is the (`dim_a`, `dim_b`) metric cost matrix
377 - :math:`\mathbf{a}` and :math:`\mathbf{b}` are source and target unbalanced distributions
378 - :math:`\mathbf{c}` is a reference distribution for the regularization
379 - :math:`\mathrm{div_m}` is a divergence, either Kullback-Leibler divergence,
380 or half-squared :math:`\ell_2` divergence, or Total variation
381 - :math:`\mathrm{div}` is a divergence, either Kullback-Leibler divergence,
382 or half-squared :math:`\ell_2` divergence
383
384 .. note:: This function is backend-compatible and will work on arrays
385 from all compatible backends. First, it converts all arrays into Numpy arrays,
386 then uses the L-BFGS-B algorithm from scipy.optimize to solve the optimization problem.
387
388 Parameters
389 ----------
390 a : array-like (dim_a,)
391 Unnormalized histogram of dimension `dim_a`
392 If `a` is an empty list or array ([]),
393 then `a` is set to uniform distribution.
394 b : array-like (dim_b,)
395 Unnormalized histogram of dimension `dim_b`
396 If `b` is an empty list or array ([]),
397 then `b` is set to uniform distribution.
398 M : array-like (dim_a, dim_b)
399 loss matrix
400 reg: float
401 regularization term >=0
402 c : array-like (dim_a, dim_b), optional (default = None)
403 Reference measure for the regularization.
404 If None, then use :math:`\mathbf{c} = \mathbf{a} \mathbf{b}^T`.
405 reg_m: float or indexable object of length 1 or 2
406 Marginal relaxation term: nonnegative (including 0) but cannot be infinity.
407 If :math:`\mathrm{reg_{m}}` is a scalar or an indexable object of length 1,
408 then the same :math:`\mathrm{reg_{m}}` is applied to both marginal relaxations.
409 If :math:`\mathrm{reg_{m}}` is an array, it must be a Numpy array.
410 reg_div: string, optional
411 Divergence used for regularization.
412 Can take three values: 'entropy' (negative entropy), or
413 'kl' (Kullback-Leibler) or 'l2' (half-squared) or a tuple
414 of two calable functions returning the reg term and its derivative.
415 Note that the callable functions should be able to handle Numpy arrays
416 and not tesors from the backend
417 regm_div: string, optional
418 Divergence to quantify the difference between the marginals.
419 Can take three values: 'kl' (Kullback-Leibler) or 'l2' (half-squared) or 'tv' (Total Variation)
420 G0: array-like (dim_a, dim_b)
421 Initialization of the transport matrix
422 returnCost: string, optional (default = "linear")
423 If `returnCost` = "linear", then return the linear part of the unbalanced OT loss.
424 If `returnCost` = "total", then return the total unbalanced OT loss.
425 numItermax : int, optional
426 Max number of iterations
427 stopThr : float, optional
428 Stop threshold on error (> 0)
429 verbose : bool, optional
430 Print information along iterations
431 log : bool, optional
432 record log if True
433
434 Returns
435 -------
436 ot_cost : array-like
437 the OT cost between :math:`\mathbf{a}` and :math:`\mathbf{b}`
438 log : dict
439 log dictionary returned only if `log` is `True`
440
441 Examples
442 --------
443 >>> import ot
444 >>> import numpy as np
445 >>> a=[.5, .5]
446 >>> b=[.5, .5]
447 >>> M=[[1., 36.],[9., 4.]]
448 >>> np.round(ot.unbalanced.lbfgsb_unbalanced2(a, b, M, reg=0, reg_m=5, reg_div='kl', regm_div='kl'), 2)
449 1.79
450 >>> np.round(ot.unbalanced.lbfgsb_unbalanced2(a, b, M, reg=0, reg_m=5, reg_div='l2', regm_div='l2'), 2)
451 0.8
452
453 References
454 ----------
455 .. [41] Chapel, L., Flamary, R., Wu, H., Févotte, C., and Gasso, G. (2021).
456 Unbalanced optimal transport through non-negative penalized
457 linear regression. NeurIPS.
458 See Also
459 --------
460 ot.lp.emd2 : Unregularized OT loss
461 ot.unbalanced.sinkhorn_unbalanced2 : Entropic regularized OT loss
462 """
463
464 _, log_lbfgs = lbfgsb_unbalanced(
465 a=a,
466 b=b,
467 M=M,
468 reg=reg,
469 reg_m=reg_m,
470 c=c,
471 reg_div=reg_div,
472 regm_div=regm_div,
473 G0=G0,
474 numItermax=numItermax,
475 stopThr=stopThr,
476 method=method,
477 verbose=verbose,
478 log=True,
479 )
480
481 if returnCost == "linear":
482 cost = log_lbfgs["cost"]
483 elif returnCost == "total":
484 cost = log_lbfgs["total_cost"]
485 else:
486 raise ValueError("Unknown returnCost = {}".format(returnCost))
487
488 if log:
489 return cost, log_lbfgs
490 else:
491 return cost