Debian Codegraph @

examples/backends/plot_ssw_unif_torch.py

raw symbols SCIP
1 # -*- coding: utf-8 -*-
2 r"""
3 ================================================
4 Spherical Sliced-Wasserstein Embedding on Sphere
5 ================================================
6
7 Here, we aim at transforming samples into a uniform
8 distribution on the sphere by minimizing SSW:
9
10 .. math::
11 \min_{x} SSW_2(\nu, \frac{1}{n}\sum_{i=1}^n \delta_{x_i})
12
13 where :math:`\nu=\mathrm{Unif}(S^1)`.
14
15 """
16
17 # Author: Clément Bonet <[email protected]>
18 #
19 # License: MIT License
20
21 # sphinx_gallery_thumbnail_number = 3
22
23 import numpy as np
24 import matplotlib.pyplot as pl
25 import matplotlib.animation as animation
26 import torch
27 import torch.nn.functional as F
28
29 import ot
30
31
32 # %%
33 # Data generation
34 # ---------------
35
36 torch.manual_seed(1)
37
38 N = 500
39 x0 = torch.rand(N, 3)
40 x0 = F.normalize(x0, dim=-1)
41
42
43 # %%
44 # Plot data
45 # ---------
46
47
48 def plot_sphere(ax):
49 xlist = np.linspace(-1.0, 1.0, 50)
50 ylist = np.linspace(-1.0, 1.0, 50)
51 r = np.linspace(1.0, 1.0, 50)
52 X, Y = np.meshgrid(xlist, ylist)
53
54 Z = np.sqrt(np.maximum(r**2 - X**2 - Y**2, 0))
55
56 ax.plot_wireframe(X, Y, Z, color="gray", alpha=0.3)
57 ax.plot_wireframe(X, Y, -Z, color="gray", alpha=0.3) # Now plot the bottom half
58
59
60 # plot the distributions
61 pl.figure(1)
62 ax = pl.axes(projection="3d")
63 plot_sphere(ax)
64 ax.scatter(x0[:, 0], x0[:, 1], x0[:, 2], label="Data samples", alpha=0.5)
65 ax.set_title("Data distribution")
66 ax.legend()
67
68
69 # %%
70 # Gradient descent
71 # ----------------
72
73 x = x0.clone()
74 x.requires_grad_(True)
75
76 n_iter = 100
77 lr = 150
78
79 losses = []
80 xvisu = torch.zeros(n_iter, N, 3)
81
82 for i in range(n_iter):
83 sw = ot.sliced_wasserstein_sphere_unif(x, n_projections=500)
84 grad_x = torch.autograd.grad(sw, x)[0]
85
86 x = x - lr * grad_x / np.sqrt(i / 10 + 1)
87 x = F.normalize(x, p=2, dim=1)
88
89 losses.append(sw.item())
90 xvisu[i, :, :] = x.detach().clone()
91
92 if i % 100 == 0:
93 print("Iter: {:3d}, loss={}".format(i, losses[-1]))
94
95 pl.figure(1)
96 pl.semilogy(losses)
97 pl.grid()
98 pl.title("SSW")
99 pl.xlabel("Iterations")
100
101
102 # %%
103 # Plot trajectories of generated samples along iterations
104 # -------------------------------------------------------
105
106 ivisu = [0, 10, 20, 30, 40, 50, 60, 70, 80]
107
108 fig = pl.figure(3, (10, 10))
109 for i in range(9):
110 # pl.subplot(3, 3, i + 1)
111 # ax = pl.axes(projection='3d')
112 ax = fig.add_subplot(3, 3, i + 1, projection="3d")
113 plot_sphere(ax)
114 ax.scatter(
115 xvisu[ivisu[i], :, 0],
116 xvisu[ivisu[i], :, 1],
117 xvisu[ivisu[i], :, 2],
118 label="Data samples",
119 alpha=0.5,
120 )
121 ax.set_title("Iter. {}".format(ivisu[i]))
122 # ax.axis("off")
123 if i == 0:
124 ax.legend()
125
126
127 # %%
128 # Animate trajectories of generated samples along iteration
129 # ---------------------------------------------------------
130
131 pl.figure(4, (8, 8))
132
133
134 def _update_plot(i):
135 i = 3 * i
136 pl.clf()
137 ax = pl.axes(projection="3d")
138 plot_sphere(ax)
139 ax.scatter(
140 xvisu[i, :, 0], xvisu[i, :, 1], xvisu[i, :, 2], label="Data samples$", alpha=0.5
141 )
142 ax.axis("off")
143 ax.set_xlim((-1.5, 1.5))
144 ax.set_ylim((-1.5, 1.5))
145 ax.set_title("Iter. {}".format(i))
146 return 1
147
148
149 print(xvisu.shape)
150
151 i = 0
152 ax = pl.axes(projection="3d")
153 plot_sphere(ax)
154 ax.scatter(
155 xvisu[i, :, 0],
156 xvisu[i, :, 1],
157 xvisu[i, :, 2],
158 label="Data samples from $G\#\mu_n$",
159 alpha=0.5,
160 )
161 ax.axis("off")
162 ax.set_xlim((-1.5, 1.5))
163 ax.set_ylim((-1.5, 1.5))
164 ax.set_title("Iter. {}".format(ivisu[i]))
165
166
167 ani = animation.FuncAnimation(
168 pl.gcf(), _update_plot, n_iter // 5, interval=200, repeat_delay=2000
169 )
170 # %%