| 1 |
""" |
| 2 |
Sliced OT Distances |
| 3 |
|
| 4 |
""" |
| 5 |
|
| 6 |
|
| 7 |
|
| 8 |
> |
| 9 |
|
| 10 |
|
| 11 |
|
| 12 |
import numpy as np |
| 13 |
from .backend import get_backend, NumpyBackend |
| 14 |
from .utils import list_to_array, get_coordinate_circle |
| 15 |
from .lp import wasserstein_circle, semidiscrete_wasserstein2_unif_circle |
| 16 |
|
| 17 |
|
| 18 |
def get_random_projections(d, n_projections, seed=None, backend=None, type_as=None): |
| 19 |
r""" |
| 20 |
Generates n_projections samples from the uniform on the unit sphere of dimension :math:`d-1`: :math:`\mathcal{U}(\mathcal{S}^{d-1})` |
| 21 |
|
| 22 |
Parameters |
| 23 |
---------- |
| 24 |
d : int |
| 25 |
dimension of the space |
| 26 |
n_projections : int |
| 27 |
number of samples requested |
| 28 |
seed: int or RandomState, optional |
| 29 |
Seed used for numpy random number generator |
| 30 |
backend: |
| 31 |
Backend to use for random generation |
| 32 |
|
| 33 |
Returns |
| 34 |
------- |
| 35 |
out: ndarray, shape (d, n_projections) |
| 36 |
The uniform unit vectors on the sphere |
| 37 |
|
| 38 |
Examples |
| 39 |
-------- |
| 40 |
>>> n_projections = 100 |
| 41 |
>>> d = 5 |
| 42 |
>>> projs = get_random_projections(d, n_projections) |
| 43 |
>>> np.allclose(np.sum(np.square(projs), 0), 1.) # doctest: +NORMALIZE_WHITESPACE |
| 44 |
True |
| 45 |
|
| 46 |
""" |
| 47 |
|
| 48 |
if backend is None: |
| 49 |
nx = NumpyBackend() |
| 50 |
else: |
| 51 |
nx = backend |
| 52 |
|
| 53 |
if isinstance(seed, np.random.RandomState) and str(nx) == "numpy": |
| 54 |
projections = seed.randn(d, n_projections) |
| 55 |
else: |
| 56 |
if seed is not None: |
| 57 |
nx.seed(seed) |
| 58 |
projections = nx.randn(d, n_projections, type_as=type_as) |
| 59 |
|
| 60 |
projections = projections / nx.sqrt(nx.sum(projections**2, 0, keepdims=True)) |
| 61 |
return projections |
| 62 |
|
| 63 |
|
| 64 |
def sliced_wasserstein_distance( |
| 65 |
X_s, |
| 66 |
X_t, |
| 67 |
a=None, |
| 68 |
b=None, |
| 69 |
n_projections=50, |
| 70 |
p=2, |
| 71 |
projections=None, |
| 72 |
seed=None, |
| 73 |
log=False, |
| 74 |
): |
| 75 |
r""" |
| 76 |
Computes a Monte-Carlo approximation of the p-Sliced Wasserstein distance |
| 77 |
|
| 78 |
.. math:: |
| 79 |
\mathcal{SWD}_p(\mu, \nu) = \underset{\theta \sim \mathcal{U}(\mathbb{S}^{d-1})}{\mathbb{E}}\left(\mathcal{W}_p^p(\theta_\# \mu, \theta_\# \nu)\right)^{\frac{1}{p}} |
| 80 |
|
| 81 |
|
| 82 |
where : |
| 83 |
|
| 84 |
- :math:`\theta_\# \mu` stands for the pushforwards of the projection :math:`X \in \mathbb{R}^d \mapsto \langle \theta, X \rangle` |
| 85 |
|
| 86 |
|
| 87 |
Parameters |
| 88 |
---------- |
| 89 |
X_s : ndarray, shape (n_samples_a, dim) |
| 90 |
samples in the source domain |
| 91 |
X_t : ndarray, shape (n_samples_b, dim) |
| 92 |
samples in the target domain |
| 93 |
a : ndarray, shape (n_samples_a,), optional |
| 94 |
samples weights in the source domain |
| 95 |
b : ndarray, shape (n_samples_b,), optional |
| 96 |
samples weights in the target domain |
| 97 |
n_projections : int, optional |
| 98 |
Number of projections used for the Monte-Carlo approximation |
| 99 |
p: float, optional = |
| 100 |
Power p used for computing the sliced Wasserstein |
| 101 |
projections: shape (dim, n_projections), optional |
| 102 |
Projection matrix (n_projections and seed are not used in this case) |
| 103 |
seed: int or RandomState or None, optional |
| 104 |
Seed used for random number generator |
| 105 |
log: bool, optional |
| 106 |
if True, sliced_wasserstein_distance returns the projections used and their associated EMD. |
| 107 |
|
| 108 |
Returns |
| 109 |
------- |
| 110 |
cost: float |
| 111 |
Sliced Wasserstein Cost |
| 112 |
log : dict, optional |
| 113 |
log dictionary return only if log==True in parameters |
| 114 |
|
| 115 |
Examples |
| 116 |
-------- |
| 117 |
|
| 118 |
>>> n_samples_a = 20 |
| 119 |
>>> X = np.random.normal(0., 1., (n_samples_a, 5)) |
| 120 |
>>> sliced_wasserstein_distance(X, X, seed=0) # doctest: +NORMALIZE_WHITESPACE |
| 121 |
0.0 |
| 122 |
|
| 123 |
References |
| 124 |
---------- |
| 125 |
|
| 126 |
.. [31] Bonneel, Nicolas, et al. "Sliced and radon wasserstein barycenters of measures." Journal of Mathematical Imaging and Vision 51.1 (2015): 22-45 |
| 127 |
""" |
| 128 |
from .lp import wasserstein_1d |
| 129 |
|
| 130 |
X_s, X_t = list_to_array(X_s, X_t) |
| 131 |
|
| 132 |
if a is not None and b is not None and projections is None: |
| 133 |
nx = get_backend(X_s, X_t, a, b) |
| 134 |
elif a is not None and b is not None and projections is not None: |
| 135 |
nx = get_backend(X_s, X_t, a, b, projections) |
| 136 |
elif a is None and b is None and projections is not None: |
| 137 |
nx = get_backend(X_s, X_t, projections) |
| 138 |
else: |
| 139 |
nx = get_backend(X_s, X_t) |
| 140 |
|
| 141 |
n = X_s.shape[0] |
| 142 |
m = X_t.shape[0] |
| 143 |
|
| 144 |
if X_s.shape[1] != X_t.shape[1]: |
| 145 |
raise ValueError( |
| 146 |
"X_s and X_t must have the same number of dimensions {} and {} respectively given".format( |
| 147 |
X_s.shape[1], X_t.shape[1] |
| 148 |
) |
| 149 |
) |
| 150 |
|
| 151 |
if a is None: |
| 152 |
a = nx.full(n, 1 / n, type_as=X_s) |
| 153 |
if b is None: |
| 154 |
b = nx.full(m, 1 / m, type_as=X_s) |
| 155 |
|
| 156 |
d = X_s.shape[1] |
| 157 |
|
| 158 |
if projections is None: |
| 159 |
projections = get_random_projections( |
| 160 |
d, n_projections, seed, backend=nx, type_as=X_s |
| 161 |
) |
| 162 |
else: |
| 163 |
n_projections = projections.shape[1] |
| 164 |
|
| 165 |
X_s_projections = nx.dot(X_s, projections) |
| 166 |
X_t_projections = nx.dot(X_t, projections) |
| 167 |
|
| 168 |
projected_emd = wasserstein_1d(X_s_projections, X_t_projections, a, b, p=p) |
| 169 |
|
| 170 |
res = (nx.sum(projected_emd) / n_projections) ** (1.0 / p) |
| 171 |
if log: |
| 172 |
return res, {"projections": projections, "projected_emds": projected_emd} |
| 173 |
return res |
| 174 |
|
| 175 |
|
| 176 |
def max_sliced_wasserstein_distance( |
| 177 |
X_s, |
| 178 |
X_t, |
| 179 |
a=None, |
| 180 |
b=None, |
| 181 |
n_projections=50, |
| 182 |
p=2, |
| 183 |
projections=None, |
| 184 |
seed=None, |
| 185 |
log=False, |
| 186 |
): |
| 187 |
r""" |
| 188 |
Computes a Monte-Carlo approximation of the max p-Sliced Wasserstein distance |
| 189 |
|
| 190 |
.. math:: |
| 191 |
\mathcal{Max-SWD}_p(\mu, \nu) = \underset{\theta _in |
| 192 |
\mathcal{U}(\mathbb{S}^{d-1})}{\max} [\mathcal{W}_p^p(\theta_\# |
| 193 |
\mu, \theta_\# \nu)]^{\frac{1}{p}} |
| 194 |
|
| 195 |
where : |
| 196 |
|
| 197 |
- :math:`\theta_\# \mu` stands for the pushforwards of the projection :math:`\mathbb{R}^d \ni X \mapsto \langle \theta, X \rangle` |
| 198 |
|
| 199 |
|
| 200 |
Parameters |
| 201 |
---------- |
| 202 |
X_s : ndarray, shape (n_samples_a, dim) |
| 203 |
samples in the source domain |
| 204 |
X_t : ndarray, shape (n_samples_b, dim) |
| 205 |
samples in the target domain |
| 206 |
a : ndarray, shape (n_samples_a,), optional |
| 207 |
samples weights in the source domain |
| 208 |
b : ndarray, shape (n_samples_b,), optional |
| 209 |
samples weights in the target domain |
| 210 |
n_projections : int, optional |
| 211 |
Number of projections used for the Monte-Carlo approximation |
| 212 |
p: float, optional = |
| 213 |
Power p used for computing the sliced Wasserstein |
| 214 |
projections: shape (dim, n_projections), optional |
| 215 |
Projection matrix (n_projections and seed are not used in this case) |
| 216 |
seed: int or RandomState or None, optional |
| 217 |
Seed used for random number generator |
| 218 |
log: bool, optional |
| 219 |
if True, sliced_wasserstein_distance returns the projections used and their associated EMD. |
| 220 |
|
| 221 |
Returns |
| 222 |
------- |
| 223 |
cost: float |
| 224 |
Sliced Wasserstein Cost |
| 225 |
log : dict, optional |
| 226 |
log dictionary return only if log==True in parameters |
| 227 |
|
| 228 |
Examples |
| 229 |
-------- |
| 230 |
|
| 231 |
>>> n_samples_a = 20 |
| 232 |
>>> X = np.random.normal(0., 1., (n_samples_a, 5)) |
| 233 |
>>> sliced_wasserstein_distance(X, X, seed=0) # doctest: +NORMALIZE_WHITESPACE |
| 234 |
0.0 |
| 235 |
|
| 236 |
References |
| 237 |
---------- |
| 238 |
|
| 239 |
.. [35] Deshpande, I., Hu, Y. T., Sun, R., Pyrros, A., Siddiqui, N., Koyejo, S., ... & Schwing, A. G. (2019). Max-sliced wasserstein distance and its use for gans. In Proceedings of the IEEE/CVF Conference on Computer Vision and Pattern Recognition (pp. 10648-10656). |
| 240 |
""" |
| 241 |
from .lp import wasserstein_1d |
| 242 |
|
| 243 |
X_s, X_t = list_to_array(X_s, X_t) |
| 244 |
|
| 245 |
if a is not None and b is not None and projections is None: |
| 246 |
nx = get_backend(X_s, X_t, a, b) |
| 247 |
elif a is not None and b is not None and projections is not None: |
| 248 |
nx = get_backend(X_s, X_t, a, b, projections) |
| 249 |
elif a is None and b is None and projections is not None: |
| 250 |
nx = get_backend(X_s, X_t, projections) |
| 251 |
else: |
| 252 |
nx = get_backend(X_s, X_t) |
| 253 |
|
| 254 |
n = X_s.shape[0] |
| 255 |
m = X_t.shape[0] |
| 256 |
|
| 257 |
if X_s.shape[1] != X_t.shape[1]: |
| 258 |
raise ValueError( |
| 259 |
"X_s and X_t must have the same number of dimensions {} and {} respectively given".format( |
| 260 |
X_s.shape[1], X_t.shape[1] |
| 261 |
) |
| 262 |
) |
| 263 |
|
| 264 |
if a is None: |
| 265 |
a = nx.full(n, 1 / n, type_as=X_s) |
| 266 |
if b is None: |
| 267 |
b = nx.full(m, 1 / m, type_as=X_s) |
| 268 |
|
| 269 |
d = X_s.shape[1] |
| 270 |
|
| 271 |
if projections is None: |
| 272 |
projections = get_random_projections( |
| 273 |
d, n_projections, seed, backend=nx, type_as=X_s |
| 274 |
) |
| 275 |
|
| 276 |
X_s_projections = nx.dot(X_s, projections) |
| 277 |
X_t_projections = nx.dot(X_t, projections) |
| 278 |
|
| 279 |
projected_emd = wasserstein_1d(X_s_projections, X_t_projections, a, b, p=p) |
| 280 |
|
| 281 |
res = nx.max(projected_emd) ** (1.0 / p) |
| 282 |
if log: |
| 283 |
return res, {"projections": projections, "projected_emds": projected_emd} |
| 284 |
return res |
| 285 |
|
| 286 |
|
| 287 |
def sliced_wasserstein_sphere( |
| 288 |
X_s, |
| 289 |
X_t, |
| 290 |
a=None, |
| 291 |
b=None, |
| 292 |
n_projections=50, |
| 293 |
p=2, |
| 294 |
projections=None, |
| 295 |
seed=None, |
| 296 |
log=False, |
| 297 |
): |
| 298 |
r""" |
| 299 |
Compute the spherical sliced-Wasserstein discrepancy. |
| 300 |
|
| 301 |
.. math:: |
| 302 |
SSW_p(\mu,\nu) = \left(\int_{\mathbb{V}_{d,2}} W_p^p(P^U_\#\mu, P^U_\#\nu)\ \mathrm{d}\sigma(U)\right)^{\frac{1}{p}} |
| 303 |
|
| 304 |
where: |
| 305 |
|
| 306 |
- :math:`P^U_\# \mu` stands for the pushforwards of the projection :math:`\forall x\in S^{d-1},\ P^U(x) = \frac{U^Tx}{\|U^Tx\|_2}` |
| 307 |
|
| 308 |
The function runs on backend but tensorflow and jax are not supported. |
| 309 |
|
| 310 |
Parameters |
| 311 |
---------- |
| 312 |
X_s: ndarray, shape (n_samples_a, dim) |
| 313 |
Samples in the source domain |
| 314 |
X_t: ndarray, shape (n_samples_b, dim) |
| 315 |
Samples in the target domain |
| 316 |
a : ndarray, shape (n_samples_a,), optional |
| 317 |
samples weights in the source domain |
| 318 |
b : ndarray, shape (n_samples_b,), optional |
| 319 |
samples weights in the target domain |
| 320 |
n_projections : int, optional |
| 321 |
Number of projections used for the Monte-Carlo approximation |
| 322 |
p: float, optional (default=2) |
| 323 |
Power p used for computing the spherical sliced Wasserstein |
| 324 |
projections: shape (n_projections, dim, 2), optional |
| 325 |
Projection matrix (n_projections and seed are not used in this case) |
| 326 |
seed: int or RandomState or None, optional |
| 327 |
Seed used for random number generator |
| 328 |
log: bool, optional |
| 329 |
if True, sliced_wasserstein_sphere returns the projections used and their associated EMD. |
| 330 |
|
| 331 |
Returns |
| 332 |
------- |
| 333 |
cost: float |
| 334 |
Spherical Sliced Wasserstein Cost |
| 335 |
log: dict, optional |
| 336 |
log dictionary return only if log==True in parameters |
| 337 |
|
| 338 |
Examples |
| 339 |
-------- |
| 340 |
>>> n_samples_a = 20 |
| 341 |
>>> X = np.random.normal(0., 1., (n_samples_a, 5)) |
| 342 |
>>> X = X / np.sqrt(np.sum(X**2, -1, keepdims=True)) |
| 343 |
>>> sliced_wasserstein_sphere(X, X, seed=0) # doctest: +NORMALIZE_WHITESPACE |
| 344 |
0.0 |
| 345 |
|
| 346 |
References |
| 347 |
---------- |
| 348 |
.. [46] Bonet, C., Berg, P., Courty, N., Septier, F., Drumetz, L., & Pham, M. T. (2023). Spherical sliced-wasserstein. International Conference on Learning Representations. |
| 349 |
""" |
| 350 |
if a is not None and b is not None: |
| 351 |
nx = get_backend(X_s, X_t, a, b) |
| 352 |
else: |
| 353 |
nx = get_backend(X_s, X_t) |
| 354 |
|
| 355 |
n, d = X_s.shape |
| 356 |
m, _ = X_t.shape |
| 357 |
|
| 358 |
if X_s.shape[1] != X_t.shape[1]: |
| 359 |
raise ValueError( |
| 360 |
"X_s and X_t must have the same number of dimensions {} and {} respectively given".format( |
| 361 |
X_s.shape[1], X_t.shape[1] |
| 362 |
) |
| 363 |
) |
| 364 |
if nx.any(nx.abs(nx.sum(X_s**2, axis=-1) - 1) > 10 ** (-4)): |
| 365 |
raise ValueError("X_s is not on the sphere.") |
| 366 |
if nx.any(nx.abs(nx.sum(X_t**2, axis=-1) - 1) > 10 ** (-4)): |
| 367 |
raise ValueError("X_t is not on the sphere.") |
| 368 |
|
| 369 |
if projections is None: |
| 370 |
|
| 371 |
if isinstance(seed, np.random.RandomState) and str(nx) == "numpy": |
| 372 |
Z = seed.randn(n_projections, d, 2) |
| 373 |
else: |
| 374 |
if seed is not None: |
| 375 |
nx.seed(seed) |
| 376 |
Z = nx.randn(n_projections, d, 2, type_as=X_s) |
| 377 |
|
| 378 |
projections, _ = nx.qr(Z) |
| 379 |
else: |
| 380 |
n_projections = projections.shape[0] |
| 381 |
|
| 382 |
|
| 383 |
|
| 384 |
Xps = nx.einsum("ikj, lk -> ilj", projections, X_s) |
| 385 |
Xpt = nx.einsum("ikj, lk -> ilj", projections, X_t) |
| 386 |
|
| 387 |
|
| 388 |
Xps = Xps / nx.sqrt(nx.sum(Xps**2, -1, keepdims=True)) |
| 389 |
Xpt = Xpt / nx.sqrt(nx.sum(Xpt**2, -1, keepdims=True)) |
| 390 |
|
| 391 |
|
| 392 |
Xps_coords = nx.reshape( |
| 393 |
get_coordinate_circle(nx.reshape(Xps, (-1, 2))), (n_projections, n) |
| 394 |
) |
| 395 |
Xpt_coords = nx.reshape( |
| 396 |
get_coordinate_circle(nx.reshape(Xpt, (-1, 2))), (n_projections, m) |
| 397 |
) |
| 398 |
|
| 399 |
projected_emd = wasserstein_circle( |
| 400 |
Xps_coords.T, Xpt_coords.T, u_weights=a, v_weights=b, p=p |
| 401 |
) |
| 402 |
res = nx.mean(projected_emd) ** (1 / p) |
| 403 |
|
| 404 |
if log: |
| 405 |
return res, {"projections": projections, "projected_emds": projected_emd} |
| 406 |
return res |
| 407 |
|
| 408 |
|
| 409 |
def sliced_wasserstein_sphere_unif(X_s, a=None, n_projections=50, seed=None, log=False): |
| 410 |
r"""Compute the 2-spherical sliced wasserstein w.r.t. a uniform distribution. |
| 411 |
|
| 412 |
.. math:: |
| 413 |
SSW_2(\mu_n, \nu) |
| 414 |
|
| 415 |
where |
| 416 |
|
| 417 |
- :math:`\mu_n=\sum_{i=1}^n \alpha_i \delta_{x_i}` |
| 418 |
- :math:`\nu=\mathrm{Unif}(S^1)` |
| 419 |
|
| 420 |
Parameters |
| 421 |
---------- |
| 422 |
X_s: ndarray, shape (n_samples_a, dim) |
| 423 |
Samples in the source domain |
| 424 |
a : ndarray, shape (n_samples_a,), optional |
| 425 |
samples weights in the source domain |
| 426 |
n_projections : int, optional |
| 427 |
Number of projections used for the Monte-Carlo approximation |
| 428 |
seed: int or RandomState or None, optional |
| 429 |
Seed used for random number generator |
| 430 |
log: bool, optional |
| 431 |
if True, sliced_wasserstein_distance returns the projections used and their associated EMD. |
| 432 |
|
| 433 |
Returns |
| 434 |
------- |
| 435 |
cost: float |
| 436 |
Spherical Sliced Wasserstein Cost |
| 437 |
log: dict, optional |
| 438 |
log dictionary return only if log==True in parameters |
| 439 |
|
| 440 |
Examples |
| 441 |
--------- |
| 442 |
>>> np.random.seed(42) |
| 443 |
>>> x0 = np.random.randn(500,3) |
| 444 |
>>> x0 = x0 / np.sqrt(np.sum(x0**2, -1, keepdims=True)) |
| 445 |
>>> ssw = sliced_wasserstein_sphere_unif(x0, seed=42) |
| 446 |
>>> np.allclose(sliced_wasserstein_sphere_unif(x0, seed=42), 0.01734, atol=1e-3) |
| 447 |
True |
| 448 |
|
| 449 |
References: |
| 450 |
----------- |
| 451 |
.. [46] Bonet, C., Berg, P., Courty, N., Septier, F., Drumetz, L., & Pham, M. T. (2023). Spherical sliced-wasserstein. International Conference on Learning Representations. |
| 452 |
""" |
| 453 |
if a is not None: |
| 454 |
nx = get_backend(X_s, a) |
| 455 |
else: |
| 456 |
nx = get_backend(X_s) |
| 457 |
|
| 458 |
n, d = X_s.shape |
| 459 |
|
| 460 |
if nx.any(nx.abs(nx.sum(X_s**2, axis=-1) - 1) > 10 ** (-4)): |
| 461 |
raise ValueError("X_s is not on the sphere.") |
| 462 |
|
| 463 |
|
| 464 |
if isinstance(seed, np.random.RandomState) and str(nx) == "numpy": |
| 465 |
Z = seed.randn(n_projections, d, 2) |
| 466 |
else: |
| 467 |
if seed is not None: |
| 468 |
nx.seed(seed) |
| 469 |
Z = nx.randn(n_projections, d, 2, type_as=X_s) |
| 470 |
|
| 471 |
projections, _ = nx.qr(Z) |
| 472 |
|
| 473 |
|
| 474 |
|
| 475 |
Xps = nx.einsum("ikj, lk -> ilj", projections, X_s) |
| 476 |
|
| 477 |
|
| 478 |
Xps = Xps / nx.sqrt(nx.sum(Xps**2, -1, keepdims=True)) |
| 479 |
|
| 480 |
|
| 481 |
Xps_coords = nx.reshape( |
| 482 |
get_coordinate_circle(nx.reshape(Xps, (-1, 2))), (n_projections, n) |
| 483 |
) |
| 484 |
|
| 485 |
projected_emd = semidiscrete_wasserstein2_unif_circle(Xps_coords.T, u_weights=a) |
| 486 |
res = nx.mean(projected_emd) ** (1 / 2) |
| 487 |
|
| 488 |
if log: |
| 489 |
return res, {"projections": projections, "projected_emds": projected_emd} |
| 490 |
return res |