Debian Codegraph @

ot/bregman/_geomloss.py

raw symbols SCIP
1 # -*- coding: utf-8 -*-
2 """
3 Wrapper functions for geomloss
4 """
5
6 # Author: Remi Flamary <[email protected]>
7 #
8 # License: MIT License
9
10 import numpy as np
11
12 try:
13 import geomloss
14 from geomloss import SamplesLoss
15 import torch
16 from torch.autograd import grad
17 from ..utils import get_backend, LazyTensor, dist
18 except ImportError:
19 geomloss = False
20
21
22 def get_sinkhorn_geomloss_lazytensor(
23 X_a, X_b, f, g, a, b, metric="sqeuclidean", blur=0.1, nx=None
24 ):
25 """Get a LazyTensor of sinkhorn solution T = exp((f+g^T-C)/reg)*(ab^T)
26
27 Parameters
28 ----------
29 X_a : array-like, shape (n_samples_a, dim)
30 samples in the source domain
31 X_torch: array-like, shape (n_samples_b, dim)
32 samples in the target domain
33 f : array-like, shape (n_samples_a,)
34 First dual potentials (log space)
35 g : array-like, shape (n_samples_b,)
36 Second dual potentials (log space)
37 metric : str, default='sqeuclidean'
38 Metric used for the cost matrix computation
39 blur : float, default=1e-1
40 blur term (blur=sqrt(reg)) >0
41 nx : Backend(), default=None
42 Numerical backend used
43
44
45 Returns
46 -------
47 T : LazyTensor
48 Lowrank tensor T = exp((f+g^T-C)/reg)*(ab^T)
49 """
50
51 if nx is None:
52 nx = get_backend(X_a, X_b, f, g)
53
54 shape = (X_a.shape[0], X_b.shape[0])
55
56 def func(i, j, X_a, X_b, f, g, a, b, metric, blur):
57 if metric == "sqeuclidean":
58 C = dist(X_a[i], X_b[j], metric=metric) / 2
59 else:
60 C = dist(X_a[i], X_b[j], metric=metric)
61 return nx.exp((f[i, None] + g[None, j] - C) / (blur**2)) * (
62 a[i, None] * b[None, j]
63 )
64
65 T = LazyTensor(
66 shape, func, X_a=X_a, X_b=X_b, f=f, g=g, a=a, b=b, metric=metric, blur=blur
67 )
68
69 return T
70
71
72 def empirical_sinkhorn2_geomloss(
73 X_s,
74 X_t,
75 reg,
76 a=None,
77 b=None,
78 metric="sqeuclidean",
79 scaling=0.95,
80 verbose=False,
81 debias=False,
82 log=False,
83 backend="auto",
84 ):
85 r"""Solve the entropic regularization optimal transport problem with geomloss
86
87 The function solves the following optimization problem:
88
89 .. math::
90 \gamma = arg\min_\gamma <\gamma,C>_F + reg\cdot\Omega(\gamma)
91
92 s.t. \gamma 1 = a
93
94 \gamma^T 1= b
95
96 \gamma\geq 0
97
98 where :
99
100 - :math:`C` is the cost matrix such that :math:`C_{i,j}=d(x_i^s,x_j^t)` and
101 :math:`d` is a metric.
102 - :math:`\Omega` is the entropic regularization term
103 :math:`\Omega(\gamma)=\sum_{i,j}\gamma_{i,j}\log(\gamma_{i,j})-\gamma_{i,j}+1`
104 - :math:`a` and :math:`b` are source and target weights (sum to 1)
105
106 The algorithm used for solving the problem is the Sinkhorn-Knopp matrix
107 scaling algorithm as proposed in and computed in log space for
108 better stability and epsilon-scaling. The solution is computed in a lazy way
109 using the Geomloss [60] and the KeOps library [61].
110
111 Parameters
112 ----------
113 X_s : array-like, shape (n_samples_a, dim)
114 samples in the source domain
115 X_t : array-like, shape (n_samples_b, dim)
116 samples in the target domain
117 reg : float
118 Regularization term >0
119 a : array-like, shape (n_samples_a,), default=None
120 samples weights in the source domain
121 b : array-like, shape (n_samples_b,), default=None
122 samples weights in the target domain
123 metric : str, default='sqeuclidean'
124 Metric used for the cost matrix computation Only accepted values are
125 'sqeuclidean' and 'euclidean'.
126 scaling : float, default=0.95
127 Scaling parameter used for epsilon scaling. Value close to one promote
128 precision while value close to zero promote speed.
129 verbose : bool, default=False
130 Print information
131 debias : bool, default=False
132 Use the debiased version of Sinkhorn algorithm [12]_.
133 log : bool, default=False
134 Return log dictionary containing all computed objects
135 backend : str, default='auto'
136 Numerical backend for geomloss. Only 'auto' and 'tensorized' 'online'
137 and 'multiscale' are accepted values.
138
139 Returns
140 -------
141 value : float
142 OT value
143 log : dict
144 Log dictionary return only if log==True in parameters
145
146 References
147 ----------
148
149 .. [60] Feydy, J., Roussillon, P., Trouvé, A., & Gori, P. (2019). [Fast
150 and scalable optimal transport for brain tractograms. In Medical Image
151 Computing and Computer Assisted Intervention–MICCAI 2019: 22nd
152 International Conference, Shenzhen, China, October 13–17, 2019,
153 Proceedings, Part III 22 (pp. 636-644). Springer International
154 Publishing.
155
156 .. [61] Charlier, B., Feydy, J., Glaunes, J. A., Collin, F. D., & Durif, G.
157 (2021). Kernel operations on the gpu, with autodiff, without memory
158 overflows. The Journal of Machine Learning Research, 22(1), 3457-3462.
159
160 """
161
162 if geomloss:
163 nx = get_backend(X_s, X_t, a, b)
164
165 if nx.__name__ not in ["torch", "numpy"]:
166 raise ValueError("geomloss only support torch or numpy backend")
167
168 if a is None:
169 a = nx.ones(X_s.shape[0], type_as=X_s) / X_s.shape[0]
170 if b is None:
171 b = nx.ones(X_t.shape[0], type_as=X_t) / X_t.shape[0]
172
173 if nx.__name__ == "numpy":
174 X_s_torch = torch.tensor(X_s)
175 X_t_torch = torch.tensor(X_t)
176
177 a_torch = torch.tensor(a)
178 b_torch = torch.tensor(b)
179
180 else:
181 X_s_torch = X_s
182 X_t_torch = X_t
183
184 a_torch = a
185 b_torch = b
186
187 # after that we are all in torch
188
189 # set blur value and p
190 if metric == "sqeuclidean":
191 p = 2
192 blur = np.sqrt(reg / 2) # because geomloss divides cost by two
193 elif metric == "euclidean":
194 p = 1
195 blur = np.sqrt(reg)
196 else:
197 raise ValueError("geomloss only supports sqeuclidean and euclidean metrics")
198
199 # force gradients for computing dual
200 a_torch.requires_grad = True
201 b_torch.requires_grad = True
202
203 loss = SamplesLoss(
204 loss="sinkhorn",
205 p=p,
206 blur=blur,
207 backend=backend,
208 debias=debias,
209 scaling=scaling,
210 verbose=verbose,
211 )
212
213 # compute value
214 value = loss(
215 a_torch, X_s_torch, b_torch, X_t_torch
216 ) # linear + entropic/KL reg?
217
218 # get dual potentials
219 f, g = grad(value, [a_torch, b_torch])
220
221 if metric == "sqeuclidean":
222 value *= 2 # because geomloss divides cost by two
223
224 if nx.__name__ == "numpy":
225 f = f.cpu().detach().numpy()
226 g = g.cpu().detach().numpy()
227 value = value.cpu().detach().numpy()
228
229 if log:
230 log = {}
231 log["f"] = f
232 log["g"] = g
233 log["value"] = value
234
235 log["lazy_plan"] = get_sinkhorn_geomloss_lazytensor(
236 X_s, X_t, f, g, a, b, metric=metric, blur=blur, nx=nx
237 )
238
239 return value, log
240
241 else:
242 return value
243
244 else:
245 raise ImportError("geomloss not installed")