Debian Codegraph @

ot/unbalanced/_mm.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 from ..backend import get_backend
13 from ..utils import list_to_array, get_parameter_pair
14
15
16 def mm_unbalanced(
17 a,
18 b,
19 M,
20 reg_m,
21 c=None,
22 reg=0,
23 div="kl",
24 G0=None,
25 numItermax=1000,
26 stopThr=1e-15,
27 verbose=False,
28 log=False,
29 ):
30 r"""
31 Solve the unbalanced optimal transport problem and return the OT plan.
32 The function solves the following optimization problem:
33
34 .. math::
35 W = \arg \min_\gamma \quad \langle \gamma, \mathbf{M} \rangle_F +
36 \mathrm{reg_{m1}} \cdot \mathrm{div}(\gamma \mathbf{1}, \mathbf{a}) +
37 \mathrm{reg_{m2}} \cdot \mathrm{div}(\gamma^T \mathbf{1}, \mathbf{b}) +
38 \mathrm{reg} \cdot \mathrm{div}(\gamma, \mathbf{c})
39
40 s.t.
41 \gamma \geq 0
42
43 where:
44
45 - :math:`\mathbf{M}` is the (`dim_a`, `dim_b`) metric cost matrix
46 - :math:`\mathbf{a}` and :math:`\mathbf{b}` are source and target
47 unbalanced distributions
48 - :math:`\mathbf{c}` is a reference distribution for the regularization
49 - div is a divergence, either Kullback-Leibler or half-squared :math:`\ell_2` divergence
50
51 The algorithm used for solving the problem is a maximization-
52 minimization algorithm as proposed in :ref:`[41] <references-regpath>`
53
54 Parameters
55 ----------
56 a : array-like (dim_a,)
57 Unnormalized histogram of dimension `dim_a`
58 If `a` is an empty list or array ([]),
59 then `a` is set to uniform distribution.
60 b : array-like (dim_b,)
61 Unnormalized histogram of dimension `dim_b`
62 If `b` is an empty list or array ([]),
63 then `b` is set to uniform distribution.
64 M : array-like (dim_a, dim_b)
65 loss matrix
66 reg_m: float or indexable object of length 1 or 2
67 Marginal relaxation term: nonnegative but cannot be infinity.
68 If :math:`\mathrm{reg_{m}}` is a scalar or an indexable object of length 1,
69 then the same :math:`\mathrm{reg_{m}}` is applied to both marginal relaxations.
70 If :math:`\mathrm{reg_{m}}` is an array,
71 it must have the same backend as input arrays `(a, b, M)`.
72 reg : float, optional (default = 0)
73 Regularization term >= 0.
74 By default, solve the unregularized problem
75 c : array-like (dim_a, dim_b), optional (default = None)
76 Reference measure for the regularization.
77 If None, then use :math:`\mathbf{c} = \mathbf{a} \mathbf{b}^T`.
78 div: string, optional
79 Divergence to quantify the difference between the marginals.
80 Can take two values: 'kl' (Kullback-Leibler) or 'l2' (half-squared)
81 G0: array-like (dim_a, dim_b)
82 Initialization of the transport matrix
83 numItermax : int, optional
84 Max number of iterations
85 stopThr : float, optional
86 Stop threshold on error (> 0)
87 verbose : bool, optional
88 Print information along iterations
89 log : bool, optional
90 record log if True
91 Returns
92 -------
93 gamma : (dim_a, dim_b) array-like
94 Optimal transportation matrix for the given parameters
95 log : dict
96 log dictionary returned only if `log` is `True`
97
98 Examples
99 --------
100 >>> import ot
101 >>> import numpy as np
102 >>> a=[.5, .5]
103 >>> b=[.5, .5]
104 >>> M=[[1., 36.],[9., 4.]]
105 >>> np.round(ot.unbalanced.mm_unbalanced(a, b, M, 5, div='kl'), 2)
106 array([[0.45, 0. ],
107 [0. , 0.34]])
108 >>> np.round(ot.unbalanced.mm_unbalanced(a, b, M, 5, div='l2'), 2)
109 array([[0.4, 0. ],
110 [0. , 0.1]])
111
112
113 .. _references-regpath:
114 References
115 ----------
116 .. [41] Chapel, L., Flamary, R., Wu, H., Févotte, C., and Gasso, G. (2021).
117 Unbalanced optimal transport through non-negative penalized
118 linear regression. NeurIPS.
119 See Also
120 --------
121 ot.lp.emd : Unregularized OT
122 ot.unbalanced.sinkhorn_unbalanced : Entropic regularized OT
123 """
124
125 M, a, b = list_to_array(M, a, b)
126 nx = get_backend(M, a, b)
127
128 dim_a, dim_b = M.shape
129
130 if len(a) == 0:
131 a = nx.ones(dim_a, type_as=M) / dim_a
132 if len(b) == 0:
133 b = nx.ones(dim_b, type_as=M) / dim_b
134
135 G = a[:, None] * b[None, :] if G0 is None else G0
136 if reg > 0: # regularized case
137 c = a[:, None] * b[None, :] if c is None else c
138 else: # unregularized case
139 c = 0
140
141 reg_m1, reg_m2 = get_parameter_pair(reg_m)
142
143 if log:
144 log = {"err": [], "G": []}
145
146 div = div.lower()
147 if div == "kl":
148 sum_r = reg + reg_m1 + reg_m2
149 r1, r2, r = reg_m1 / sum_r, reg_m2 / sum_r, reg / sum_r
150 K = (a[:, None] ** r1) * (b[None, :] ** r2) * (c**r) * nx.exp(-M / sum_r)
151 elif div == "l2":
152 K = (reg_m1 * a[:, None]) + (reg_m2 * b[None, :]) + reg * c - M
153 K = nx.maximum(K, nx.zeros((dim_a, dim_b), type_as=M))
154 else:
155 raise ValueError("Unknown div = {}. Must be either 'kl' or 'l2'".format(div))
156
157 for i in range(numItermax):
158 Gprev = G
159
160 if div == "kl":
161 Gd = (nx.sum(G, 1, keepdims=True) ** r1) * (
162 nx.sum(G, 0, keepdims=True) ** r2
163 ) + 1e-16
164 G = K * G ** (r1 + r2) / Gd
165 elif div == "l2":
166 Gd = (
167 reg_m1 * nx.sum(G, 1, keepdims=True)
168 + reg_m2 * nx.sum(G, 0, keepdims=True)
169 + reg * G
170 + 1e-16
171 )
172 G = K * G / Gd
173
174 err = nx.sqrt(nx.sum((G - Gprev) ** 2))
175 if log:
176 log["err"].append(err)
177 log["G"].append(G)
178 if verbose:
179 print("{:5d}|{:8e}|".format(i, err))
180 if err < stopThr:
181 break
182
183 if log:
184 linear_cost = nx.sum(G * M)
185 log["cost"] = linear_cost
186
187 m1, m2 = nx.sum(G, 1), nx.sum(G, 0)
188 if div == "kl":
189 cost = (
190 linear_cost
191 + reg_m1 * nx.kl_div(m1, a, mass=True)
192 + reg_m2 * nx.kl_div(m2, b, mass=True)
193 )
194 if reg > 0:
195 cost = cost + reg * nx.kl_div(G, c, mass=True)
196 else:
197 cost = (
198 linear_cost
199 + reg_m1 * 0.5 * nx.sum((m1 - a) ** 2)
200 + reg_m2 * 0.5 * nx.sum((m2 - b) ** 2)
201 )
202 if reg > 0:
203 cost = cost + reg * 0.5 * nx.sum((G - c) ** 2)
204
205 log["total_cost"] = cost
206
207 return G, log
208 else:
209 return G
210
211
212 def mm_unbalanced2(
213 a,
214 b,
215 M,
216 reg_m,
217 c=None,
218 reg=0,
219 div="kl",
220 G0=None,
221 returnCost="linear",
222 numItermax=1000,
223 stopThr=1e-15,
224 verbose=False,
225 log=False,
226 ):
227 r"""
228 Solve the unbalanced optimal transport problem and return the OT cost.
229 The function solves the following optimization problem:
230
231 .. math::
232 \min_\gamma \quad \langle \gamma, \mathbf{M} \rangle_F +
233 \mathrm{reg_{m1}} \cdot \mathrm{div}(\gamma \mathbf{1}, \mathbf{a}) +
234 \mathrm{reg_{m2}} \cdot \mathrm{div}(\gamma^T \mathbf{1}, \mathbf{b}) +
235 \mathrm{reg} \cdot \mathrm{div}(\gamma, \mathbf{c})
236
237 s.t.
238 \gamma \geq 0
239
240 where:
241
242 - :math:`\mathbf{M}` is the (`dim_a`, `dim_b`) metric cost matrix
243 - :math:`\mathbf{a}` and :math:`\mathbf{b}` are source and target
244 unbalanced distributions
245 - :math:`\mathbf{c}` is a reference distribution for the regularization
246 - :math:`\mathrm{div}` is a divergence, either Kullback-Leibler or half-squared :math:`\ell_2` divergence
247
248 The algorithm used for solving the problem is a maximization-
249 minimization algorithm as proposed in :ref:`[41] <references-regpath>`
250
251 Parameters
252 ----------
253 a : array-like (dim_a,)
254 Unnormalized histogram of dimension `dim_a`
255 If `a` is an empty list or array ([]),
256 then `a` is set to uniform distribution.
257 b : array-like (dim_b,)
258 Unnormalized histogram of dimension `dim_b`
259 If `b` is an empty list or array ([]),
260 then `b` is set to uniform distribution.
261 M : array-like (dim_a, dim_b)
262 loss matrix
263 reg_m: float or indexable object of length 1 or 2
264 Marginal relaxation term: nonnegative but cannot be infinity.
265 If :math:`\mathrm{reg_{m}}` is a scalar or an indexable object of length 1,
266 then the same :math:`\mathrm{reg_{m}}` is applied to both marginal relaxations.
267 If :math:`\mathrm{reg_{m}}` is an array,
268 it must have the same backend as input arrays `(a, b, M)`.
269 reg : float, optional (default = 0)
270 Entropy regularization term >= 0.
271 By default, solve the unregularized problem
272 c : array-like (dim_a, dim_b), optional (default = None)
273 Reference measure for the regularization.
274 If None, then use :math:`\mathbf{c} = mathbf{a} mathbf{b}^T`.
275 div: string, optional
276 Divergence to quantify the difference between the marginals.
277 Can take two values: 'kl' (Kullback-Leibler) or 'l2' (half-squared)
278 G0: array-like (dim_a, dim_b)
279 Initialization of the transport matrix
280 returnCost: string, optional (default = "linear")
281 If `returnCost` = "linear", then return the linear part of the unbalanced OT loss.
282 If `returnCost` = "total", then return the total unbalanced OT loss.
283 numItermax : int, optional
284 Max number of iterations
285 stopThr : float, optional
286 Stop threshold on error (> 0)
287 verbose : bool, optional
288 Print information along iterations
289 log : bool, optional
290 record log if True
291
292 Returns
293 -------
294 ot_cost : array-like
295 the OT cost between :math:`\mathbf{a}` and :math:`\mathbf{b}`
296 log : dict
297 log dictionary returned only if `log` is `True`
298
299 Examples
300 --------
301 >>> import ot
302 >>> import numpy as np
303 >>> a=[.5, .5]
304 >>> b=[.5, .5]
305 >>> M=[[1., 36.],[9., 4.]]
306 >>> np.round(ot.unbalanced.mm_unbalanced2(a, b, M, 5, div='l2'), 2)
307 0.8
308 >>> np.round(ot.unbalanced.mm_unbalanced2(a, b, M, 5, div='kl'), 2)
309 1.79
310
311 References
312 ----------
313 .. [41] Chapel, L., Flamary, R., Wu, H., Févotte, C., and Gasso, G. (2021).
314 Unbalanced optimal transport through non-negative penalized
315 linear regression. NeurIPS.
316 See Also
317 --------
318 ot.lp.emd2 : Unregularized OT loss
319 ot.unbalanced.sinkhorn_unbalanced2 : Entropic regularized OT loss
320 """
321
322 _, log_mm = mm_unbalanced(
323 a,
324 b,
325 M,
326 reg_m,
327 c=c,
328 reg=reg,
329 div=div,
330 G0=G0,
331 numItermax=numItermax,
332 stopThr=stopThr,
333 verbose=verbose,
334 log=True,
335 )
336
337 if returnCost == "linear":
338 cost = log_mm["cost"]
339 elif returnCost == "total":
340 cost = log_mm["total_cost"]
341 else:
342 raise ValueError("Unknown returnCost = {}".format(returnCost))
343
344 if log:
345 return cost, log_mm
346 else:
347 return cost