Debian Codegraph @

examples/backends/plot_wass1d_torch.py

raw symbols SCIP
1 r"""
2 =================================================
3 Wasserstein 1D (flow and barycenter) with PyTorch
4 =================================================
5
6 In this small example, we consider the following minimization problem:
7
8 .. math::
9 \mu^* = \min_\mu W(\mu,\nu)
10
11 where :math:`\nu` is a reference 1D measure. The problem is handled
12 by a projected gradient descent method, where the gradient is computed
13 by pyTorch automatic differentiation. The projection on the simplex
14 ensures that the iterate will remain on the probability simplex.
15
16 This example illustrates both `wasserstein_1d` function and backend use within
17 the POT framework.
18 """
19 # Author: Nicolas Courty <[email protected]>
20 # Rémi Flamary <[email protected]>
21 #
22 # License: MIT License
23
24 import numpy as np
25 import matplotlib.pylab as pl
26 import matplotlib as mpl
27 import torch
28
29 from ot.lp import wasserstein_1d
30 from ot.datasets import make_1D_gauss as gauss
31 from ot.utils import proj_simplex
32
33 red = np.array(mpl.colors.to_rgb("red"))
34 blue = np.array(mpl.colors.to_rgb("blue"))
35
36
37 n = 100 # nb bins
38
39 # bin positions
40 x = np.arange(n, dtype=np.float64)
41
42 # Gaussian distributions
43 a = gauss(n, m=20, s=5) # m= mean, s= std
44 b = gauss(n, m=60, s=10)
45
46 # enforce sum to one on the support
47 a = a / a.sum()
48 b = b / b.sum()
49
50
51 device = "cuda" if torch.cuda.is_available() else "cpu"
52
53 # use pyTorch for our data
54 x_torch = torch.tensor(x).to(device=device)
55 a_torch = torch.tensor(a).to(device=device).requires_grad_(True)
56 b_torch = torch.tensor(b).to(device=device)
57
58 lr = 1e-6
59 nb_iter_max = 800
60
61 loss_iter = []
62
63 pl.figure(1, figsize=(8, 4))
64 pl.plot(x, a, "b", label="Source distribution")
65 pl.plot(x, b, "r", label="Target distribution")
66
67 for i in range(nb_iter_max):
68 # Compute the Wasserstein 1D with torch backend
69 loss = wasserstein_1d(x_torch, x_torch, a_torch, b_torch, p=2)
70 # record the corresponding loss value
71 loss_iter.append(loss.clone().detach().cpu().numpy())
72 loss.backward()
73
74 # performs a step of projected gradient descent
75 with torch.no_grad():
76 grad = a_torch.grad
77 a_torch -= a_torch.grad * lr # step
78 a_torch.grad.zero_()
79 a_torch.data = proj_simplex(a_torch) # projection onto the simplex
80
81 # plot one curve every 10 iterations
82 if i % 10 == 0:
83 mix = float(i) / nb_iter_max
84 pl.plot(
85 x, a_torch.clone().detach().cpu().numpy(), c=(1 - mix) * blue + mix * red
86 )
87
88 pl.legend()
89 pl.title("Distribution along the iterations of the projected gradient descent")
90 pl.show()
91
92 pl.figure(2)
93 pl.plot(range(nb_iter_max), loss_iter, lw=3)
94 pl.title("Evolution of the loss along iterations", fontsize=16)
95 pl.show()
96
97 # %%
98 # Wasserstein barycenter
99 # ----------------------
100 # In this example, we consider the following Wasserstein barycenter problem
101 # $$ \\eta^* = \\min_\\eta\;\;\; (1-t)W(\\mu,\\eta) + tW(\\eta,\\nu)$$
102 # where :math:`\\mu` and :math:`\\nu` are reference 1D measures, and :math:`t`
103 # is a parameter :math:`\in [0,1]`. The problem is handled by a project gradient
104 # descent method, where the gradient is computed by pyTorch automatic differentiation.
105 # The projection on the simplex ensures that the iterate will remain on the
106 # probability simplex.
107 #
108 # This example illustrates both `wasserstein_1d` function and backend use within the
109 # POT framework.
110
111
112 device = "cuda" if torch.cuda.is_available() else "cpu"
113
114 # use pyTorch for our data
115 x_torch = torch.tensor(x).to(device=device)
116 a_torch = torch.tensor(a).to(device=device)
117 b_torch = torch.tensor(b).to(device=device)
118 bary_torch = torch.tensor((a + b).copy() / 2).to(device=device).requires_grad_(True)
119
120
121 lr = 1e-6
122 nb_iter_max = 2000
123
124 loss_iter = []
125
126 # instant of the interpolation
127 t = 0.5
128
129 for i in range(nb_iter_max):
130 # Compute the Wasserstein 1D with torch backend
131 loss = (1 - t) * wasserstein_1d(
132 x_torch, x_torch, a_torch.detach(), bary_torch, p=2
133 ) + t * wasserstein_1d(x_torch, x_torch, b_torch, bary_torch, p=2)
134 # record the corresponding loss value
135 loss_iter.append(loss.clone().detach().cpu().numpy())
136 loss.backward()
137
138 # performs a step of projected gradient descent
139 with torch.no_grad():
140 grad = bary_torch.grad
141 bary_torch -= bary_torch.grad * lr # step
142 bary_torch.grad.zero_()
143 bary_torch.data = proj_simplex(bary_torch) # projection onto the simplex
144
145 pl.figure(3, figsize=(8, 4))
146 pl.plot(x, a, "b", label="Source distribution")
147 pl.plot(x, b, "r", label="Target distribution")
148 pl.plot(x, bary_torch.clone().detach().cpu().numpy(), c="green", label="W barycenter")
149 pl.legend()
150 pl.title("Wasserstein barycenter computed by gradient descent")
151 pl.show()
152
153 pl.figure(4)
154 pl.plot(range(nb_iter_max), loss_iter, lw=3)
155 pl.title("Evolution of the loss along iterations", fontsize=16)
156 pl.show()