|
| 1 | +r""" |
| 2 | +================================= |
| 3 | +Sliced Wasserstein barycenter and gradient flow with PyTorch |
| 4 | +================================= |
| 5 | +
|
| 6 | +In this exemple we use the pytorch backend to optimize the sliced Wasserstein |
| 7 | +loss between two empirical distributions [31]. |
| 8 | +
|
| 9 | +In the first example one we perform a |
| 10 | +gradient flow on the support of a distribution that minimize the sliced |
| 11 | +Wassersein distance as poposed in [36]. |
| 12 | +
|
| 13 | +In the second exemple we optimize with a gradient descent the sliced |
| 14 | +Wasserstein barycenter between two distributions as in [31]. |
| 15 | +
|
| 16 | +[31] Bonneel, Nicolas, et al. "Sliced and radon wasserstein barycenters of |
| 17 | +measures." Journal of Mathematical Imaging and Vision 51.1 (2015): 22-45 |
| 18 | +
|
| 19 | +[36] Liutkus, A., Simsekli, U., Majewski, S., Durmus, A., & Stöter, F. R. |
| 20 | +(2019, May). Sliced-Wasserstein flows: Nonparametric generative modeling |
| 21 | +via optimal transport and diffusions. In International Conference on |
| 22 | +Machine Learning (pp. 4104-4113). PMLR. |
| 23 | +
|
| 24 | +
|
| 25 | +""" |
| 26 | +# Author: Rémi Flamary <[email protected]> |
| 27 | +# |
| 28 | +# License: MIT License |
| 29 | + |
| 30 | + |
| 31 | +# %% |
| 32 | +# Loading the data |
| 33 | + |
| 34 | + |
| 35 | +import numpy as np |
| 36 | +import matplotlib.pylab as pl |
| 37 | +import torch |
| 38 | +import ot |
| 39 | +import matplotlib.animation as animation |
| 40 | + |
| 41 | +I1 = pl.imread('../../data/redcross.png').astype(np.float64)[::4, ::4, 2] |
| 42 | +I2 = pl.imread('../../data/tooth.png').astype(np.float64)[::4, ::4, 2] |
| 43 | + |
| 44 | +sz = I2.shape[0] |
| 45 | +XX, YY = np.meshgrid(np.arange(sz), np.arange(sz)) |
| 46 | + |
| 47 | +x1 = np.stack((XX[I1 == 0], YY[I1 == 0]), 1) * 1.0 |
| 48 | +x2 = np.stack((XX[I2 == 0] + 60, -YY[I2 == 0] + 32), 1) * 1.0 |
| 49 | +x3 = np.stack((XX[I2 == 0], -YY[I2 == 0] + 32), 1) * 1.0 |
| 50 | + |
| 51 | +pl.figure(1, (8, 4)) |
| 52 | +pl.scatter(x1[:, 0], x1[:, 1], alpha=0.5) |
| 53 | +pl.scatter(x2[:, 0], x2[:, 1], alpha=0.5) |
| 54 | + |
| 55 | +# %% |
| 56 | +# Sliced Wasserstein gradient flow with Pytorch |
| 57 | +# --------------------------------------------- |
| 58 | + |
| 59 | + |
| 60 | +device = "cuda" if torch.cuda.is_available() else "cpu" |
| 61 | + |
| 62 | +# use pyTorch for our data |
| 63 | +x1_torch = torch.tensor(x1).to(device=device).requires_grad_(True) |
| 64 | +x2_torch = torch.tensor(x2).to(device=device) |
| 65 | + |
| 66 | + |
| 67 | +lr = 1e3 |
| 68 | +nb_iter_max = 100 |
| 69 | + |
| 70 | +x_all = np.zeros((nb_iter_max, x1.shape[0], 2)) |
| 71 | + |
| 72 | +loss_iter = [] |
| 73 | + |
| 74 | +# generator for random permutations |
| 75 | +gen = torch.Generator() |
| 76 | +gen.manual_seed(42) |
| 77 | + |
| 78 | +for i in range(nb_iter_max): |
| 79 | + |
| 80 | + loss = ot.sliced_wasserstein_distance(x1_torch, x2_torch, n_projections=20, seed=gen) |
| 81 | + |
| 82 | + loss_iter.append(loss.clone().detach().cpu().numpy()) |
| 83 | + loss.backward() |
| 84 | + |
| 85 | + # performs a step of projected gradient descent |
| 86 | + with torch.no_grad(): |
| 87 | + grad = x1_torch.grad |
| 88 | + x1_torch -= grad * lr / (1 + i / 5e1) # step |
| 89 | + x1_torch.grad.zero_() |
| 90 | + x_all[i, :, :] = x1_torch.clone().detach().cpu().numpy() |
| 91 | + |
| 92 | +xb = x1_torch.clone().detach().cpu().numpy() |
| 93 | + |
| 94 | +pl.figure(2, (8, 4)) |
| 95 | +pl.scatter(x1[:, 0], x1[:, 1], alpha=0.5, label='$\mu^{(0)}$') |
| 96 | +pl.scatter(x2[:, 0], x2[:, 1], alpha=0.5, label=r'$\nu$') |
| 97 | +pl.scatter(xb[:, 0], xb[:, 1], alpha=0.5, label='$\mu^{(100)}$') |
| 98 | +pl.title('Sliced Wasserstein gradient flow') |
| 99 | +pl.legend() |
| 100 | +ax = pl.axis() |
| 101 | + |
| 102 | +# %% |
| 103 | +# Animate trajectories of the gradient flow along iteration |
| 104 | +# ------------------------------------------------------- |
| 105 | + |
| 106 | +pl.figure(3, (8, 4)) |
| 107 | + |
| 108 | + |
| 109 | +def _update_plot(i): |
| 110 | + pl.clf() |
| 111 | + pl.scatter(x1[:, 0], x1[:, 1], alpha=0.5, label='$\mu^{(0)}$') |
| 112 | + pl.scatter(x2[:, 0], x2[:, 1], alpha=0.5, label=r'$\nu$') |
| 113 | + pl.scatter(x_all[i, :, 0], x_all[i, :, 1], alpha=0.5, label='$\mu^{(100)}$') |
| 114 | + pl.title('Sliced Wasserstein gradient flow Iter. {}'.format(i)) |
| 115 | + pl.axis(ax) |
| 116 | + return 1 |
| 117 | + |
| 118 | + |
| 119 | +ani = animation.FuncAnimation(pl.gcf(), _update_plot, nb_iter_max, interval=100, repeat_delay=2000) |
| 120 | + |
| 121 | +# %% |
| 122 | +# Compute the Sliced Wasserstein Barycenter |
| 123 | +# |
| 124 | +x1_torch = torch.tensor(x1).to(device=device) |
| 125 | +x3_torch = torch.tensor(x3).to(device=device) |
| 126 | +xbinit = np.random.randn(500, 2) * 10 + 16 |
| 127 | +xbary_torch = torch.tensor(xbinit).to(device=device).requires_grad_(True) |
| 128 | + |
| 129 | +lr = 1e3 |
| 130 | +nb_iter_max = 100 |
| 131 | + |
| 132 | +x_all = np.zeros((nb_iter_max, xbary_torch.shape[0], 2)) |
| 133 | + |
| 134 | +loss_iter = [] |
| 135 | + |
| 136 | +# generator for random permutations |
| 137 | +gen = torch.Generator() |
| 138 | +gen.manual_seed(42) |
| 139 | + |
| 140 | +alpha = 0.5 |
| 141 | + |
| 142 | +for i in range(nb_iter_max): |
| 143 | + |
| 144 | + loss = alpha * ot.sliced_wasserstein_distance(xbary_torch, x3_torch, n_projections=50, seed=gen) \ |
| 145 | + + (1 - alpha) * ot.sliced_wasserstein_distance(xbary_torch, x1_torch, n_projections=50, seed=gen) |
| 146 | + |
| 147 | + loss_iter.append(loss.clone().detach().cpu().numpy()) |
| 148 | + loss.backward() |
| 149 | + |
| 150 | + # performs a step of projected gradient descent |
| 151 | + with torch.no_grad(): |
| 152 | + grad = xbary_torch.grad |
| 153 | + xbary_torch -= grad * lr # / (1 + i / 5e1) # step |
| 154 | + xbary_torch.grad.zero_() |
| 155 | + x_all[i, :, :] = xbary_torch.clone().detach().cpu().numpy() |
| 156 | + |
| 157 | +xb = xbary_torch.clone().detach().cpu().numpy() |
| 158 | + |
| 159 | +pl.figure(4, (8, 4)) |
| 160 | +pl.scatter(x1[:, 0], x1[:, 1], alpha=0.5, label='$\mu$') |
| 161 | +pl.scatter(x2[:, 0], x2[:, 1], alpha=0.5, label=r'$\nu$') |
| 162 | +pl.scatter(xb[:, 0] + 30, xb[:, 1], alpha=0.5, label='Barycenter') |
| 163 | +pl.title('Sliced Wasserstein barycenter') |
| 164 | +pl.legend() |
| 165 | +ax = pl.axis() |
| 166 | + |
| 167 | + |
| 168 | +# %% |
| 169 | +# Animate trajectories of the barycenter along gradient descent |
| 170 | +# ------------------------------------------------------- |
| 171 | + |
| 172 | +pl.figure(5, (8, 4)) |
| 173 | + |
| 174 | + |
| 175 | +def _update_plot(i): |
| 176 | + pl.clf() |
| 177 | + pl.scatter(x1[:, 0], x1[:, 1], alpha=0.5, label='$\mu^{(0)}$') |
| 178 | + pl.scatter(x2[:, 0], x2[:, 1], alpha=0.5, label=r'$\nu$') |
| 179 | + pl.scatter(x_all[i, :, 0] + 30, x_all[i, :, 1], alpha=0.5, label='$\mu^{(100)}$') |
| 180 | + pl.title('Sliced Wasserstein barycenter Iter. {}'.format(i)) |
| 181 | + pl.axis(ax) |
| 182 | + return 1 |
| 183 | + |
| 184 | + |
| 185 | +ani = animation.FuncAnimation(pl.gcf(), _update_plot, nb_iter_max, interval=100, repeat_delay=2000) |
0 commit comments