| 1 |
|
| 2 |
""" |
| 3 |
Optimal Transport maps and variants |
| 4 |
|
| 5 |
.. warning:: |
| 6 |
Note that by default the module is not imported in :mod:`ot`. In order to |
| 7 |
use it you need to explicitly import :mod:`ot.mapping` |
| 8 |
""" |
| 9 |
|
| 10 |
|
| 11 |
|
| 12 |
|
| 13 |
|
| 14 |
|
| 15 |
from .backend import get_backend, to_numpy |
| 16 |
from .lp import emd |
| 17 |
import numpy as np |
| 18 |
|
| 19 |
from .optim import cg |
| 20 |
from .utils import dist, unif, list_to_array, kernel, dots |
| 21 |
|
| 22 |
|
| 23 |
def nearest_brenier_potential_fit( |
| 24 |
X, |
| 25 |
V, |
| 26 |
X_classes=None, |
| 27 |
a=None, |
| 28 |
b=None, |
| 29 |
strongly_convex_constant=0.6, |
| 30 |
gradient_lipschitz_constant=1.4, |
| 31 |
its=100, |
| 32 |
log=False, |
| 33 |
init_method="barycentric", |
| 34 |
): |
| 35 |
r""" |
| 36 |
Computes optimal values and gradients at X for a strongly convex potential :math:`\varphi` with Lipschitz gradients |
| 37 |
on the partitions defined by `X_classes`, where :math:`\varphi` is optimal such that |
| 38 |
:math:`\nabla \varphi \#\mu \approx \nu`, given samples :math:`X = x_1, \cdots, x_n \sim \mu` and |
| 39 |
:math:`V = v_1, \cdots, v_n \sim \nu`. Finding such a potential that has the desired regularity on the |
| 40 |
partition :math:`(E_k)_{k \in [K]}` (given by the classes `X_classes`) is equivalent to finding optimal values |
| 41 |
`phi` for the :math:`\varphi(x_i)` and its gradients :math:`\nabla \varphi(x_i)` (variable`G`). |
| 42 |
In practice, these optimal values are found by solving the following problem |
| 43 |
|
| 44 |
.. math:: |
| 45 |
:nowrap: |
| 46 |
|
| 47 |
\begin{gather*} |
| 48 |
\text{min} \sum_{i,j}\pi_{i,j}\|g_i - v_j\|_2^2 \\ |
| 49 |
g_1,\cdots, g_n \in \mathbb{R}^d,\; \varphi_1, \cdots, \varphi_n \in \mathbb{R},\; \pi \in \Pi(a, b) \\ |
| 50 |
\text{s.t.}\ \forall k \in [K],\; \forall i,j \in I_k: \\ |
| 51 |
\varphi_i-\varphi_j-\langle g_j, x_i-x_j\rangle \geq c_1\|g_i - g_j\|_2^2 |
| 52 |
+ c_2\|x_i-x_j\|_2^2 - c_3\langle g_j-g_i, x_j -x_i \rangle. |
| 53 |
\end{gather*} |
| 54 |
|
| 55 |
The constants :math:`c_1, c_2, c_3` only depend on `strongly_convex_constant` and `gradient_lipschitz_constant`. |
| 56 |
The constraint :math:`\pi \in \Pi(a, b)` denotes the fact that the matrix :math:`\pi` belong to the OT polytope |
| 57 |
of marginals a and b. :math:`I_k` is the subset of :math:`[n]` of the i such that :math:`x_i` is in the |
| 58 |
partition (or class) :math:`E_k`, i.e. `X_classes[i] == k`. |
| 59 |
|
| 60 |
This problem is solved by alternating over the variable :math:`\pi` and the variables :math:`\varphi_i, g_i`. |
| 61 |
For :math:`\pi`, the problem is the standard discrete OT problem, and for :math:`\varphi_i, g_i`, the |
| 62 |
problem is a convex QCQP solved using :code:`cvxpy` (ECOS solver). |
| 63 |
|
| 64 |
Accepts any compatible backend, but will perform the QCQP optimisation on Numpy arrays, and convert back at the end. |
| 65 |
|
| 66 |
.. warning:: This function requires the CVXPY library |
| 67 |
.. warning:: Accepts any backend but will convert to Numpy then back to the backend. |
| 68 |
|
| 69 |
Parameters |
| 70 |
---------- |
| 71 |
X : array-like (n, d) |
| 72 |
reference points used to compute the optimal values phi and G |
| 73 |
V : array-like (n, d) |
| 74 |
values of the gradients at the reference points X |
| 75 |
X_classes : array-like (n,), optional |
| 76 |
classes of the reference points, defaults to a single class |
| 77 |
a : array-like (n,), optional |
| 78 |
weights for the reference points X, defaults to uniform |
| 79 |
b : array-like (n,), optional |
| 80 |
weights for the target points V, defaults to uniform |
| 81 |
strongly_convex_constant : float, optional |
| 82 |
constant for the strong convexity of the input potential phi, defaults to 0.6 |
| 83 |
gradient_lipschitz_constant : float, optional |
| 84 |
constant for the Lipschitz property of the input gradient G, defaults to 1.4 |
| 85 |
its: int, optional |
| 86 |
number of iterations, defaults to 100 |
| 87 |
log : bool, optional |
| 88 |
record log if true |
| 89 |
init_method : str, optional |
| 90 |
'target' initialises G=V, 'barycentric' initialises at the image of X by the barycentric projection |
| 91 |
|
| 92 |
Returns |
| 93 |
------- |
| 94 |
phi : array-like (n,) |
| 95 |
optimal values of the potential at the points X |
| 96 |
G : array-like (n, d) |
| 97 |
optimal values of the gradients at the points X |
| 98 |
log : dict, optional |
| 99 |
If input log is true, a dictionary containing the values of the variables at each iteration, as well |
| 100 |
as solver information |
| 101 |
|
| 102 |
References |
| 103 |
---------- |
| 104 |
|
| 105 |
.. [58] François-Pierre Paty, Alexandre d’Aspremont, and Marco Cuturi. Regularity as regularization: |
| 106 |
Smooth and strongly convex brenier potentials in optimal transport. In International Conference |
| 107 |
on Artificial Intelligence and Statistics, pages 1222–1232. PMLR, 2020. |
| 108 |
|
| 109 |
See Also |
| 110 |
-------- |
| 111 |
ot.mapping.nearest_brenier_potential_predict_bounds : Predicting SSNB images on new source data |
| 112 |
ot.da.NearestBrenierPotential : BaseTransport wrapper for SSNB |
| 113 |
|
| 114 |
""" |
| 115 |
try: |
| 116 |
import cvxpy as cvx |
| 117 |
except ImportError: |
| 118 |
print("Please install CVXPY to use this function") |
| 119 |
return |
| 120 |
assert ( |
| 121 |
X.shape == V.shape |
| 122 |
), f"point shape should be the same as value shape, yet {X.shape} != {V.shape}" |
| 123 |
nx = get_backend(X, V, X_classes, a, b) |
| 124 |
X, V = to_numpy(X), to_numpy(V) |
| 125 |
n, d = X.shape |
| 126 |
if X_classes is not None: |
| 127 |
X_classes = to_numpy(X_classes) |
| 128 |
assert X_classes.size == n, "incorrect number of class items" |
| 129 |
else: |
| 130 |
X_classes = np.zeros(n) |
| 131 |
a = unif(n) if a is None else nx.to_numpy(a) |
| 132 |
b = unif(n) if b is None else nx.to_numpy(b) |
| 133 |
assert a.shape[-1] == b.shape[-1] == n, "incorrect measure weight sizes" |
| 134 |
|
| 135 |
assert init_method in [ |
| 136 |
"target", |
| 137 |
"barycentric", |
| 138 |
], f"Unsupported initialization method '{init_method}'" |
| 139 |
if init_method == "target": |
| 140 |
G_val = V |
| 141 |
else: |
| 142 |
G_val = emd(a, b, dist(X, V)) @ V / a.reshape(n, 1) |
| 143 |
phi_val = None |
| 144 |
log_dict = {"G_list": [], "phi_list": [], "its": []} |
| 145 |
|
| 146 |
for _ in range(its): |
| 147 |
cost_matrix = dist(G_val, V) |
| 148 |
|
| 149 |
plan = emd(a, b, cost_matrix) |
| 150 |
|
| 151 |
|
| 152 |
phi = cvx.Variable(n) |
| 153 |
G = cvx.Variable((n, d)) |
| 154 |
constraints = [] |
| 155 |
cost = 0 |
| 156 |
for i in range(n): |
| 157 |
for j in range(n): |
| 158 |
cost += cvx.sum_squares(G[i, :] - V[j, :]) * plan[i, j] |
| 159 |
objective = cvx.Minimize(cost) |
| 160 |
c1, c2, c3 = _ssnb_qcqp_constants( |
| 161 |
strongly_convex_constant, gradient_lipschitz_constant |
| 162 |
) |
| 163 |
|
| 164 |
for k in np.unique(X_classes): |
| 165 |
for i in np.where(X_classes == k)[0]: |
| 166 |
for j in np.where(X_classes == k)[0]: |
| 167 |
constraints += [ |
| 168 |
phi[i] |
| 169 |
>= phi[j] |
| 170 |
+ G[j].T @ (X[i] - X[j]) |
| 171 |
+ c1 * cvx.sum_squares(G[i] - G[j]) |
| 172 |
+ c2 * cvx.sum_squares(X[i] - X[j]) |
| 173 |
- c3 * (G[j] - G[i]).T @ (X[j] - X[i]) |
| 174 |
] |
| 175 |
problem = cvx.Problem(objective, constraints) |
| 176 |
problem.solve(solver=cvx.ECOS) |
| 177 |
phi_val, G_val = phi.value, G.value |
| 178 |
it_log_dict = { |
| 179 |
"solve_time": problem.solver_stats.solve_time, |
| 180 |
"setup_time": problem.solver_stats.setup_time, |
| 181 |
"num_iters": problem.solver_stats.num_iters, |
| 182 |
"status": problem.status, |
| 183 |
"value": problem.value, |
| 184 |
} |
| 185 |
if log: |
| 186 |
log_dict["its"].append(it_log_dict) |
| 187 |
log_dict["G_list"].append(G_val) |
| 188 |
log_dict["phi_list"].append(phi_val) |
| 189 |
|
| 190 |
|
| 191 |
phi_val = nx.from_numpy(phi_val) |
| 192 |
G_val = nx.from_numpy(G_val) |
| 193 |
if not log: |
| 194 |
return phi_val, G_val |
| 195 |
return phi_val, G_val, log_dict |
| 196 |
|
| 197 |
|
| 198 |
def _ssnb_qcqp_constants(strongly_convex_constant, gradient_lipschitz_constant): |
| 199 |
r""" |
| 200 |
Handy function computing the constants for the Nearest Brenier Potential QCQP problems |
| 201 |
|
| 202 |
Parameters |
| 203 |
---------- |
| 204 |
strongly_convex_constant : float |
| 205 |
gradient_lipschitz_constant : float |
| 206 |
|
| 207 |
Returns |
| 208 |
------- |
| 209 |
c1 : float |
| 210 |
c2 : float |
| 211 |
c3 : float |
| 212 |
|
| 213 |
""" |
| 214 |
assert ( |
| 215 |
0 < strongly_convex_constant < gradient_lipschitz_constant |
| 216 |
), "incompatible regularity assumption" |
| 217 |
c = 1 / (2 * (1 - strongly_convex_constant / gradient_lipschitz_constant)) |
| 218 |
c1 = c / gradient_lipschitz_constant |
| 219 |
c2 = strongly_convex_constant * c |
| 220 |
c3 = 2 * strongly_convex_constant * c / gradient_lipschitz_constant |
| 221 |
return c1, c2, c3 |
| 222 |
|
| 223 |
|
| 224 |
def nearest_brenier_potential_predict_bounds( |
| 225 |
X, |
| 226 |
phi, |
| 227 |
G, |
| 228 |
Y, |
| 229 |
X_classes=None, |
| 230 |
Y_classes=None, |
| 231 |
strongly_convex_constant=0.6, |
| 232 |
gradient_lipschitz_constant=1.4, |
| 233 |
log=False, |
| 234 |
): |
| 235 |
r""" |
| 236 |
Compute the values of the lower and upper bounding potentials at the input points Y, using the potential optimal |
| 237 |
values phi at X and their gradients G at X. The 'lower' potential corresponds to the method from :ref:`[58]`, |
| 238 |
Equation 2, while the bounding property and 'upper' potential come from :ref:`[59]`, Theorem 3.14 (taking into |
| 239 |
account the fact that this theorem's statement has a min instead of a max, which is a typo). Both potentials are |
| 240 |
optimal for the SSNB problem. |
| 241 |
|
| 242 |
If :math:`I_k` is the subset of :math:`[n]` of the i such that :math:`x_i` is in the partition (or class) |
| 243 |
:math:`E_k`, for each :math:`y \in E_k`, this function solves the convex QCQP problems, |
| 244 |
respectively for l: 'lower' and u: 'upper': |
| 245 |
|
| 246 |
.. math:: |
| 247 |
:nowrap: |
| 248 |
|
| 249 |
\begin{gather*} |
| 250 |
(\varphi_{l}(x), \nabla \varphi_l(x)) = \text{argmin}\ t, \\ |
| 251 |
t\in \mathbb{R},\; g\in \mathbb{R}^d, \\ |
| 252 |
\text{s.t.} \forall j \in I_k,\; t-\varphi_j - \langle g_j, y-x_j \rangle \geq c_1\|g - g_j\|_2^2 |
| 253 |
+ c_2\|y-x_j\|_2^2 - c_3\langle g_j-g, x_j -y \rangle. |
| 254 |
\end{gather*} |
| 255 |
|
| 256 |
.. math:: |
| 257 |
:nowrap: |
| 258 |
|
| 259 |
\begin{gather*} |
| 260 |
(\varphi_{u}(x), \nabla \varphi_u(x)) = \text{argmax}\ t, \\ |
| 261 |
t\in \mathbb{R},\; g\in \mathbb{R}^d, \\ |
| 262 |
\text{s.t.} \forall i \in I_k,\; \varphi_i^* -t - \langle g, x_i-y \rangle \geq c_1\|g_i - g\|_2^2 |
| 263 |
+ c_2\|x_i-y\|_2^2 - c_3\langle g-g_i, y -x_i \rangle. |
| 264 |
\end{gather*} |
| 265 |
|
| 266 |
The constants :math:`c_1, c_2, c_3` only depend on `strongly_convex_constant` and `gradient_lipschitz_constant`. |
| 267 |
|
| 268 |
.. warning:: This function requires the CVXPY library |
| 269 |
.. warning:: Accepts any backend but will convert to Numpy then back to the backend. |
| 270 |
|
| 271 |
Parameters |
| 272 |
---------- |
| 273 |
X : array-like (n, d) |
| 274 |
reference points used to compute the optimal values phi and G |
| 275 |
X_classes : array-like (n,) |
| 276 |
classes of the reference points |
| 277 |
phi : array-like (n,) |
| 278 |
optimal values of the potential at the points X |
| 279 |
G : array-like (n, d) |
| 280 |
optimal values of the gradients at the points X |
| 281 |
Y : array-like (m, d) |
| 282 |
input points |
| 283 |
X_classes : array-like (n,), optional |
| 284 |
classes of the reference points, defaults to a single class |
| 285 |
Y_classes : array_like (m,), optional |
| 286 |
classes of the input points, defaults to a single class |
| 287 |
strongly_convex_constant : float, optional |
| 288 |
constant for the strong convexity of the input potential phi, defaults to 0.6 |
| 289 |
gradient_lipschitz_constant : float, optional |
| 290 |
constant for the Lipschitz property of the input gradient G, defaults to 1.4 |
| 291 |
log : bool, optional |
| 292 |
record log if true |
| 293 |
|
| 294 |
Returns |
| 295 |
------- |
| 296 |
phi_lu: array-like (2, m) |
| 297 |
values of the lower and upper bounding potentials at Y |
| 298 |
G_lu: array-like (2, m, d) |
| 299 |
gradients of the lower and upper bounding potentials at Y |
| 300 |
log : dict, optional |
| 301 |
If input log is true, a dictionary containing solver information |
| 302 |
|
| 303 |
References |
| 304 |
---------- |
| 305 |
|
| 306 |
.. [58] François-Pierre Paty, Alexandre d’Aspremont, and Marco Cuturi. Regularity as regularization: |
| 307 |
Smooth and strongly convex brenier potentials in optimal transport. In International Conference |
| 308 |
on Artificial Intelligence and Statistics, pages 1222–1232. PMLR, 2020. |
| 309 |
|
| 310 |
.. [59] Adrien B Taylor. Convex interpolation and performance estimation of first-order methods for |
| 311 |
convex optimization. PhD thesis, Catholic University of Louvain, Louvain-la-Neuve, Belgium, |
| 312 |
2017. |
| 313 |
|
| 314 |
See Also |
| 315 |
-------- |
| 316 |
ot.mapping.nearest_brenier_potential_fit : Fitting the SSNB on source and target data |
| 317 |
ot.da.NearestBrenierPotential : BaseTransport wrapper for SSNB |
| 318 |
|
| 319 |
""" |
| 320 |
try: |
| 321 |
import cvxpy as cvx |
| 322 |
except ImportError: |
| 323 |
print("Please install CVXPY to use this function") |
| 324 |
return |
| 325 |
nx = get_backend(X, phi, G, Y) |
| 326 |
X = to_numpy(X) |
| 327 |
phi = to_numpy(phi) |
| 328 |
G = to_numpy(G) |
| 329 |
Y = to_numpy(Y) |
| 330 |
m, d = Y.shape |
| 331 |
if Y_classes is not None: |
| 332 |
Y_classes = to_numpy(Y_classes) |
| 333 |
assert Y_classes.size == m, "wrong number of class items for Y" |
| 334 |
else: |
| 335 |
Y_classes = np.zeros(m) |
| 336 |
assert ( |
| 337 |
X.shape[1] == d |
| 338 |
), f"incompatible dimensions between X: {X.shape} and Y: {Y.shape}" |
| 339 |
n, _ = X.shape |
| 340 |
if X_classes is not None: |
| 341 |
X_classes = to_numpy(X_classes) |
| 342 |
assert X_classes.size == n, "incorrect number of class items" |
| 343 |
else: |
| 344 |
X_classes = np.zeros(n) |
| 345 |
assert X_classes.size == n, "wrong number of class items for X" |
| 346 |
c1, c2, c3 = _ssnb_qcqp_constants( |
| 347 |
strongly_convex_constant, gradient_lipschitz_constant |
| 348 |
) |
| 349 |
phi_lu = np.zeros((2, m)) |
| 350 |
G_lu = np.zeros((2, m, d)) |
| 351 |
log_dict = {} |
| 352 |
|
| 353 |
for y_idx in range(m): |
| 354 |
log_item = {} |
| 355 |
|
| 356 |
phi_l_y = cvx.Variable(1) |
| 357 |
G_l_y = cvx.Variable(d) |
| 358 |
objective = cvx.Minimize(phi_l_y) |
| 359 |
constraints = [] |
| 360 |
k = Y_classes[y_idx] |
| 361 |
for j in np.where(X_classes == k)[0]: |
| 362 |
constraints += [ |
| 363 |
phi_l_y |
| 364 |
>= phi[j] |
| 365 |
+ G[j].T @ (Y[y_idx] - X[j]) |
| 366 |
+ c1 * cvx.sum_squares(G_l_y - G[j]) |
| 367 |
+ c2 * cvx.sum_squares(Y[y_idx] - X[j]) |
| 368 |
- c3 * (G[j] - G_l_y).T @ (X[j] - Y[y_idx]) |
| 369 |
] |
| 370 |
problem = cvx.Problem(objective, constraints) |
| 371 |
problem.solve(solver=cvx.ECOS) |
| 372 |
phi_lu[0, y_idx] = phi_l_y.value |
| 373 |
G_lu[0, y_idx] = G_l_y.value |
| 374 |
if log: |
| 375 |
log_item["l"] = { |
| 376 |
"solve_time": problem.solver_stats.solve_time, |
| 377 |
"setup_time": problem.solver_stats.setup_time, |
| 378 |
"num_iters": problem.solver_stats.num_iters, |
| 379 |
"status": problem.status, |
| 380 |
"value": problem.value, |
| 381 |
} |
| 382 |
|
| 383 |
|
| 384 |
phi_u_y = cvx.Variable(1) |
| 385 |
G_u_y = cvx.Variable(d) |
| 386 |
objective = cvx.Maximize(phi_u_y) |
| 387 |
constraints = [] |
| 388 |
for i in np.where(X_classes == k)[0]: |
| 389 |
constraints += [ |
| 390 |
phi[i] |
| 391 |
>= phi_u_y |
| 392 |
+ G_u_y.T @ (X[i] - Y[y_idx]) |
| 393 |
+ c1 * cvx.sum_squares(G[i] - G_u_y) |
| 394 |
+ c2 * cvx.sum_squares(X[i] - Y[y_idx]) |
| 395 |
- c3 * (G_u_y - G[i]).T @ (Y[y_idx] - X[i]) |
| 396 |
] |
| 397 |
problem = cvx.Problem(objective, constraints) |
| 398 |
problem.solve(solver=cvx.ECOS) |
| 399 |
phi_lu[1, y_idx] = phi_u_y.value |
| 400 |
G_lu[1, y_idx] = G_u_y.value |
| 401 |
if log: |
| 402 |
log_item["u"] = { |
| 403 |
"solve_time": problem.solver_stats.solve_time, |
| 404 |
"setup_time": problem.solver_stats.setup_time, |
| 405 |
"num_iters": problem.solver_stats.num_iters, |
| 406 |
"status": problem.status, |
| 407 |
"value": problem.value, |
| 408 |
} |
| 409 |
log_dict[y_idx] = log_item |
| 410 |
|
| 411 |
phi_lu, G_lu = nx.from_numpy(phi_lu), nx.from_numpy(G_lu) |
| 412 |
if not log: |
| 413 |
return phi_lu, G_lu |
| 414 |
return phi_lu, G_lu, log_dict |
| 415 |
|
| 416 |
|
| 417 |
def joint_OT_mapping_linear( |
| 418 |
xs, |
| 419 |
xt, |
| 420 |
mu=1, |
| 421 |
eta=0.001, |
| 422 |
bias=False, |
| 423 |
verbose=False, |
| 424 |
verbose2=False, |
| 425 |
numItermax=100, |
| 426 |
numInnerItermax=10, |
| 427 |
stopInnerThr=1e-6, |
| 428 |
stopThr=1e-5, |
| 429 |
log=False, |
| 430 |
**kwargs, |
| 431 |
): |
| 432 |
r"""Joint OT and linear mapping estimation as proposed in |
| 433 |
:ref:`[8] <references-joint-OT-mapping-linear>`. |
| 434 |
|
| 435 |
The function solves the following optimization problem: |
| 436 |
|
| 437 |
.. math:: |
| 438 |
\min_{\gamma,L}\quad \|L(\mathbf{X_s}) - n_s\gamma \mathbf{X_t} \|^2_F + |
| 439 |
\mu \langle \gamma, \mathbf{M} \rangle_F + \eta \|L - \mathbf{I}\|^2_F |
| 440 |
|
| 441 |
s.t. \ \gamma \mathbf{1} = \mathbf{a} |
| 442 |
|
| 443 |
\gamma^T \mathbf{1} = \mathbf{b} |
| 444 |
|
| 445 |
\gamma \geq 0 |
| 446 |
|
| 447 |
where : |
| 448 |
|
| 449 |
- :math:`\mathbf{M}` is the (`ns`, `nt`) squared euclidean cost matrix between samples in |
| 450 |
:math:`\mathbf{X_s}` and :math:`\mathbf{X_t}` (scaled by :math:`n_s`) |
| 451 |
- :math:`L` is a :math:`d\times d` linear operator that approximates the barycentric |
| 452 |
mapping |
| 453 |
- :math:`\mathbf{I}` is the identity matrix (neutral linear mapping) |
| 454 |
- :math:`\mathbf{a}` and :math:`\mathbf{b}` are uniform source and target weights |
| 455 |
|
| 456 |
The problem consist in solving jointly an optimal transport matrix |
| 457 |
:math:`\gamma` and a linear mapping that fits the barycentric mapping |
| 458 |
:math:`n_s\gamma \mathbf{X_t}`. |
| 459 |
|
| 460 |
One can also estimate a mapping with constant bias (see supplementary |
| 461 |
material of :ref:`[8] <references-joint-OT-mapping-linear>`) using the bias optional argument. |
| 462 |
|
| 463 |
The algorithm used for solving the problem is the block coordinate |
| 464 |
descent that alternates between updates of :math:`\mathbf{G}` (using conditional gradient) |
| 465 |
and the update of :math:`\mathbf{L}` using a classical least square solver. |
| 466 |
|
| 467 |
|
| 468 |
Parameters |
| 469 |
---------- |
| 470 |
xs : array-like (ns,d) |
| 471 |
samples in the source domain |
| 472 |
xt : array-like (nt,d) |
| 473 |
samples in the target domain |
| 474 |
mu : float,optional |
| 475 |
Weight for the linear OT loss (>0) |
| 476 |
eta : float, optional |
| 477 |
Regularization term for the linear mapping L (>0) |
| 478 |
bias : bool,optional |
| 479 |
Estimate linear mapping with constant bias |
| 480 |
numItermax : int, optional |
| 481 |
Max number of BCD iterations |
| 482 |
stopThr : float, optional |
| 483 |
Stop threshold on relative loss decrease (>0) |
| 484 |
numInnerItermax : int, optional |
| 485 |
Max number of iterations (inner CG solver) |
| 486 |
stopInnerThr : float, optional |
| 487 |
Stop threshold on error (inner CG solver) (>0) |
| 488 |
verbose : bool, optional |
| 489 |
Print information along iterations |
| 490 |
log : bool, optional |
| 491 |
record log if True |
| 492 |
|
| 493 |
|
| 494 |
Returns |
| 495 |
------- |
| 496 |
gamma : (ns, nt) array-like |
| 497 |
Optimal transportation matrix for the given parameters |
| 498 |
L : (d, d) array-like |
| 499 |
Linear mapping matrix ((:math:`d+1`, `d`) if bias) |
| 500 |
log : dict |
| 501 |
log dictionary return only if log==True in parameters |
| 502 |
|
| 503 |
|
| 504 |
.. _references-joint-OT-mapping-linear: |
| 505 |
References |
| 506 |
---------- |
| 507 |
.. [8] M. Perrot, N. Courty, R. Flamary, A. Habrard, |
| 508 |
"Mapping estimation for discrete optimal transport", |
| 509 |
Neural Information Processing Systems (NIPS), 2016. |
| 510 |
|
| 511 |
See Also |
| 512 |
-------- |
| 513 |
ot.lp.emd : Unregularized OT |
| 514 |
ot.optim.cg : General regularized OT |
| 515 |
|
| 516 |
""" |
| 517 |
xs, xt = list_to_array(xs, xt) |
| 518 |
nx = get_backend(xs, xt) |
| 519 |
|
| 520 |
ns, nt, d = xs.shape[0], xt.shape[0], xt.shape[1] |
| 521 |
|
| 522 |
if bias: |
| 523 |
xs1 = nx.concatenate((xs, nx.ones((ns, 1), type_as=xs)), axis=1) |
| 524 |
xstxs = nx.dot(xs1.T, xs1) |
| 525 |
Id = nx.eye(d + 1, type_as=xs) |
| 526 |
Id[-1] = 0 |
| 527 |
I0 = Id[:, :-1] |
| 528 |
|
| 529 |
def sel(x): |
| 530 |
return x[:-1, :] |
| 531 |
else: |
| 532 |
xs1 = xs |
| 533 |
xstxs = nx.dot(xs1.T, xs1) |
| 534 |
Id = nx.eye(d, type_as=xs) |
| 535 |
I0 = Id |
| 536 |
|
| 537 |
def sel(x): |
| 538 |
return x |
| 539 |
|
| 540 |
if log: |
| 541 |
log = {"err": []} |
| 542 |
|
| 543 |
a = unif(ns, type_as=xs) |
| 544 |
b = unif(nt, type_as=xt) |
| 545 |
M = dist(xs, xt) * ns |
| 546 |
G = emd(a, b, M) |
| 547 |
|
| 548 |
vloss = [] |
| 549 |
|
| 550 |
def loss(L, G): |
| 551 |
"""Compute full loss""" |
| 552 |
return ( |
| 553 |
nx.sum((nx.dot(xs1, L) - ns * nx.dot(G, xt)) ** 2) |
| 554 |
+ mu * nx.sum(G * M) |
| 555 |
+ eta * nx.sum(sel(L - I0) ** 2) |
| 556 |
) |
| 557 |
|
| 558 |
def solve_L(G): |
| 559 |
"""solve L problem with fixed G (least square)""" |
| 560 |
xst = ns * nx.dot(G, xt) |
| 561 |
return nx.solve(xstxs + eta * Id, nx.dot(xs1.T, xst) + eta * I0) |
| 562 |
|
| 563 |
def solve_G(L, G0): |
| 564 |
"""Update G with CG algorithm""" |
| 565 |
xsi = nx.dot(xs1, L) |
| 566 |
|
| 567 |
def f(G): |
| 568 |
return nx.sum((xsi - ns * nx.dot(G, xt)) ** 2) |
| 569 |
|
| 570 |
def df(G): |
| 571 |
return -2 * ns * nx.dot(xsi - ns * nx.dot(G, xt), xt.T) |
| 572 |
|
| 573 |
G = cg( |
| 574 |
a, |
| 575 |
b, |
| 576 |
M, |
| 577 |
1.0 / mu, |
| 578 |
f, |
| 579 |
df, |
| 580 |
G0=G0, |
| 581 |
numItermax=numInnerItermax, |
| 582 |
stopThr=stopInnerThr, |
| 583 |
) |
| 584 |
return G |
| 585 |
|
| 586 |
L = solve_L(G) |
| 587 |
|
| 588 |
vloss.append(loss(L, G)) |
| 589 |
|
| 590 |
if verbose: |
| 591 |
print( |
| 592 |
"{:5s}|{:12s}|{:8s}".format("It.", "Loss", "Delta loss") + "\n" + "-" * 32 |
| 593 |
) |
| 594 |
print("{:5d}|{:8e}|{:8e}".format(0, vloss[-1], 0)) |
| 595 |
|
| 596 |
|
| 597 |
if numItermax > 0: |
| 598 |
loop = 1 |
| 599 |
else: |
| 600 |
loop = 0 |
| 601 |
it = 0 |
| 602 |
|
| 603 |
while loop: |
| 604 |
it += 1 |
| 605 |
|
| 606 |
|
| 607 |
G = solve_G(L, G) |
| 608 |
|
| 609 |
|
| 610 |
L = solve_L(G) |
| 611 |
|
| 612 |
vloss.append(loss(L, G)) |
| 613 |
|
| 614 |
if it >= numItermax: |
| 615 |
loop = 0 |
| 616 |
|
| 617 |
if abs(vloss[-1] - vloss[-2]) / abs(vloss[-2]) < stopThr: |
| 618 |
loop = 0 |
| 619 |
|
| 620 |
if verbose: |
| 621 |
if it % 20 == 0: |
| 622 |
print( |
| 623 |
"{:5s}|{:12s}|{:8s}".format("It.", "Loss", "Delta loss") |
| 624 |
+ "\n" |
| 625 |
+ "-" * 32 |
| 626 |
) |
| 627 |
print( |
| 628 |
"{:5d}|{:8e}|{:8e}".format( |
| 629 |
it, vloss[-1], (vloss[-1] - vloss[-2]) / abs(vloss[-2]) |
| 630 |
) |
| 631 |
) |
| 632 |
if log: |
| 633 |
log["loss"] = vloss |
| 634 |
return G, L, log |
| 635 |
else: |
| 636 |
return G, L |
| 637 |
|
| 638 |
|
| 639 |
def joint_OT_mapping_kernel( |
| 640 |
xs, |
| 641 |
xt, |
| 642 |
mu=1, |
| 643 |
eta=0.001, |
| 644 |
kerneltype="gaussian", |
| 645 |
sigma=1, |
| 646 |
bias=False, |
| 647 |
verbose=False, |
| 648 |
verbose2=False, |
| 649 |
numItermax=100, |
| 650 |
numInnerItermax=10, |
| 651 |
stopInnerThr=1e-6, |
| 652 |
stopThr=1e-5, |
| 653 |
log=False, |
| 654 |
**kwargs, |
| 655 |
): |
| 656 |
r"""Joint OT and nonlinear mapping estimation with kernels as proposed in |
| 657 |
:ref:`[8] <references-joint-OT-mapping-kernel>`. |
| 658 |
|
| 659 |
The function solves the following optimization problem: |
| 660 |
|
| 661 |
.. math:: |
| 662 |
\min_{\gamma, L\in\mathcal{H}}\quad \|L(\mathbf{X_s}) - |
| 663 |
n_s\gamma \mathbf{X_t}\|^2_F + \mu \langle \gamma, \mathbf{M} \rangle_F + |
| 664 |
\eta \|L\|^2_\mathcal{H} |
| 665 |
|
| 666 |
s.t. \ \gamma \mathbf{1} = \mathbf{a} |
| 667 |
|
| 668 |
\gamma^T \mathbf{1} = \mathbf{b} |
| 669 |
|
| 670 |
\gamma \geq 0 |
| 671 |
|
| 672 |
|
| 673 |
where : |
| 674 |
|
| 675 |
- :math:`\mathbf{M}` is the (`ns`, `nt`) squared euclidean cost matrix between samples in |
| 676 |
:math:`\mathbf{X_s}` and :math:`\mathbf{X_t}` (scaled by :math:`n_s`) |
| 677 |
- :math:`L` is a :math:`n_s \times d` linear operator on a kernel matrix that |
| 678 |
approximates the barycentric mapping |
| 679 |
- :math:`\mathbf{a}` and :math:`\mathbf{b}` are uniform source and target weights |
| 680 |
|
| 681 |
The problem consist in solving jointly an optimal transport matrix |
| 682 |
:math:`\gamma` and the nonlinear mapping that fits the barycentric mapping |
| 683 |
:math:`n_s\gamma \mathbf{X_t}`. |
| 684 |
|
| 685 |
One can also estimate a mapping with constant bias (see supplementary |
| 686 |
material of :ref:`[8] <references-joint-OT-mapping-kernel>`) using the bias optional argument. |
| 687 |
|
| 688 |
The algorithm used for solving the problem is the block coordinate |
| 689 |
descent that alternates between updates of :math:`\mathbf{G}` (using conditional gradient) |
| 690 |
and the update of :math:`\mathbf{L}` using a classical kernel least square solver. |
| 691 |
|
| 692 |
|
| 693 |
Parameters |
| 694 |
---------- |
| 695 |
xs : array-like (ns,d) |
| 696 |
samples in the source domain |
| 697 |
xt : array-like (nt,d) |
| 698 |
samples in the target domain |
| 699 |
mu : float,optional |
| 700 |
Weight for the linear OT loss (>0) |
| 701 |
eta : float, optional |
| 702 |
Regularization term for the linear mapping L (>0) |
| 703 |
kerneltype : str,optional |
| 704 |
kernel used by calling function :py:func:`ot.utils.kernel` (gaussian by default) |
| 705 |
sigma : float, optional |
| 706 |
Gaussian kernel bandwidth. |
| 707 |
bias : bool,optional |
| 708 |
Estimate linear mapping with constant bias |
| 709 |
verbose : bool, optional |
| 710 |
Print information along iterations |
| 711 |
verbose2 : bool, optional |
| 712 |
Print information along iterations |
| 713 |
numItermax : int, optional |
| 714 |
Max number of BCD iterations |
| 715 |
numInnerItermax : int, optional |
| 716 |
Max number of iterations (inner CG solver) |
| 717 |
stopInnerThr : float, optional |
| 718 |
Stop threshold on error (inner CG solver) (>0) |
| 719 |
stopThr : float, optional |
| 720 |
Stop threshold on relative loss decrease (>0) |
| 721 |
log : bool, optional |
| 722 |
record log if True |
| 723 |
|
| 724 |
|
| 725 |
Returns |
| 726 |
------- |
| 727 |
gamma : (ns, nt) array-like |
| 728 |
Optimal transportation matrix for the given parameters |
| 729 |
L : (ns, d) array-like |
| 730 |
Nonlinear mapping matrix ((:math:`n_s+1`, `d`) if bias) |
| 731 |
log : dict |
| 732 |
log dictionary return only if log==True in parameters |
| 733 |
|
| 734 |
|
| 735 |
.. _references-joint-OT-mapping-kernel: |
| 736 |
References |
| 737 |
---------- |
| 738 |
.. [8] M. Perrot, N. Courty, R. Flamary, A. Habrard, |
| 739 |
"Mapping estimation for discrete optimal transport", |
| 740 |
Neural Information Processing Systems (NIPS), 2016. |
| 741 |
|
| 742 |
See Also |
| 743 |
-------- |
| 744 |
ot.lp.emd : Unregularized OT |
| 745 |
ot.optim.cg : General regularized OT |
| 746 |
|
| 747 |
""" |
| 748 |
xs, xt = list_to_array(xs, xt) |
| 749 |
nx = get_backend(xs, xt) |
| 750 |
|
| 751 |
ns, nt = xs.shape[0], xt.shape[0] |
| 752 |
|
| 753 |
K = kernel(xs, xs, method=kerneltype, sigma=sigma) |
| 754 |
if bias: |
| 755 |
K1 = nx.concatenate((K, nx.ones((ns, 1), type_as=xs)), axis=1) |
| 756 |
Id = nx.eye(ns + 1, type_as=xs) |
| 757 |
Id[-1] = 0 |
| 758 |
Kp = nx.eye(ns + 1, type_as=xs) |
| 759 |
Kp[:ns, :ns] = K |
| 760 |
|
| 761 |
|
| 762 |
|
| 763 |
|
| 764 |
|
| 765 |
|
| 766 |
K0 = nx.dot(K1.T, K1) + eta * Kp |
| 767 |
Kreg = Kp |
| 768 |
|
| 769 |
else: |
| 770 |
K1 = K |
| 771 |
Id = nx.eye(ns, type_as=xs) |
| 772 |
|
| 773 |
|
| 774 |
|
| 775 |
|
| 776 |
|
| 777 |
|
| 778 |
K0 = K + eta * Id |
| 779 |
Kreg = K |
| 780 |
|
| 781 |
if log: |
| 782 |
log = {"err": []} |
| 783 |
|
| 784 |
a = unif(ns, type_as=xs) |
| 785 |
b = unif(nt, type_as=xt) |
| 786 |
M = dist(xs, xt) * ns |
| 787 |
G = emd(a, b, M) |
| 788 |
|
| 789 |
vloss = [] |
| 790 |
|
| 791 |
def loss(L, G): |
| 792 |
"""Compute full loss""" |
| 793 |
return ( |
| 794 |
nx.sum((nx.dot(K1, L) - ns * nx.dot(G, xt)) ** 2) |
| 795 |
+ mu * nx.sum(G * M) |
| 796 |
+ eta * nx.trace(dots(L.T, Kreg, L)) |
| 797 |
) |
| 798 |
|
| 799 |
def solve_L_nobias(G): |
| 800 |
"""solve L problem with fixed G (least square)""" |
| 801 |
xst = ns * nx.dot(G, xt) |
| 802 |
return nx.solve(K0, xst) |
| 803 |
|
| 804 |
def solve_L_bias(G): |
| 805 |
"""solve L problem with fixed G (least square)""" |
| 806 |
xst = ns * nx.dot(G, xt) |
| 807 |
return nx.solve(K0, nx.dot(K1.T, xst)) |
| 808 |
|
| 809 |
def solve_G(L, G0): |
| 810 |
"""Update G with CG algorithm""" |
| 811 |
xsi = nx.dot(K1, L) |
| 812 |
|
| 813 |
def f(G): |
| 814 |
return nx.sum((xsi - ns * nx.dot(G, xt)) ** 2) |
| 815 |
|
| 816 |
def df(G): |
| 817 |
return -2 * ns * nx.dot(xsi - ns * nx.dot(G, xt), xt.T) |
| 818 |
|
| 819 |
G = cg( |
| 820 |
a, |
| 821 |
b, |
| 822 |
M, |
| 823 |
1.0 / mu, |
| 824 |
f, |
| 825 |
df, |
| 826 |
G0=G0, |
| 827 |
numItermax=numInnerItermax, |
| 828 |
stopThr=stopInnerThr, |
| 829 |
) |
| 830 |
return G |
| 831 |
|
| 832 |
if bias: |
| 833 |
solve_L = solve_L_bias |
| 834 |
else: |
| 835 |
solve_L = solve_L_nobias |
| 836 |
|
| 837 |
L = solve_L(G) |
| 838 |
|
| 839 |
vloss.append(loss(L, G)) |
| 840 |
|
| 841 |
if verbose: |
| 842 |
print( |
| 843 |
"{:5s}|{:12s}|{:8s}".format("It.", "Loss", "Delta loss") + "\n" + "-" * 32 |
| 844 |
) |
| 845 |
print("{:5d}|{:8e}|{:8e}".format(0, vloss[-1], 0)) |
| 846 |
|
| 847 |
|
| 848 |
if numItermax > 0: |
| 849 |
loop = 1 |
| 850 |
else: |
| 851 |
loop = 0 |
| 852 |
it = 0 |
| 853 |
|
| 854 |
while loop: |
| 855 |
it += 1 |
| 856 |
|
| 857 |
|
| 858 |
G = solve_G(L, G) |
| 859 |
|
| 860 |
|
| 861 |
L = solve_L(G) |
| 862 |
|
| 863 |
vloss.append(loss(L, G)) |
| 864 |
|
| 865 |
if it >= numItermax: |
| 866 |
loop = 0 |
| 867 |
|
| 868 |
if abs(vloss[-1] - vloss[-2]) / abs(vloss[-2]) < stopThr: |
| 869 |
loop = 0 |
| 870 |
|
| 871 |
if verbose: |
| 872 |
if it % 20 == 0: |
| 873 |
print( |
| 874 |
"{:5s}|{:12s}|{:8s}".format("It.", "Loss", "Delta loss") |
| 875 |
+ "\n" |
| 876 |
+ "-" * 32 |
| 877 |
) |
| 878 |
print( |
| 879 |
"{:5d}|{:8e}|{:8e}".format( |
| 880 |
it, vloss[-1], (vloss[-1] - vloss[-2]) / abs(vloss[-2]) |
| 881 |
) |
| 882 |
) |
| 883 |
if log: |
| 884 |
log["loss"] = vloss |
| 885 |
return G, L, log |
| 886 |
else: |
| 887 |
return G, L |