Debian Codegraph @

examples/backends/plot_dual_ot_pytorch.py

raw symbols SCIP
1 # -*- coding: utf-8 -*-
2 r"""
3 ======================================================================
4 Dual OT solvers for entropic and quadratic regularized OT with Pytorch
5 ======================================================================
6
7
8 """
9
10 # Author: Remi Flamary <[email protected]>
11 #
12 # License: MIT License
13
14 # sphinx_gallery_thumbnail_number = 3
15
16 import numpy as np
17 import matplotlib.pyplot as pl
18 import torch
19 import ot
20 import ot.plot
21
22 # %%
23 # Data generation
24 # ---------------
25
26 torch.manual_seed(1)
27
28 n_source_samples = 100
29 n_target_samples = 100
30 theta = 2 * np.pi / 20
31 noise_level = 0.1
32
33 Xs, ys = ot.datasets.make_data_classif("gaussrot", n_source_samples, nz=noise_level)
34 Xt, yt = ot.datasets.make_data_classif(
35 "gaussrot", n_target_samples, theta=theta, nz=noise_level
36 )
37
38 # one of the target mode changes its variance (no linear mapping)
39 Xt[yt == 2] *= 3
40 Xt = Xt + 4
41
42
43 # %%
44 # Plot data
45 # ---------
46
47 pl.figure(1, (10, 5))
48 pl.clf()
49 pl.scatter(Xs[:, 0], Xs[:, 1], marker="+", label="Source samples")
50 pl.scatter(Xt[:, 0], Xt[:, 1], marker="o", label="Target samples")
51 pl.legend(loc=0)
52 pl.title("Source and target distributions")
53
54 # %%
55 # Convert data to torch tensors
56 # -----------------------------
57
58 xs = torch.tensor(Xs)
59 xt = torch.tensor(Xt)
60
61 # %%
62 # Estimating dual variables for entropic OT
63 # -----------------------------------------
64
65 u = torch.randn(n_source_samples, requires_grad=True)
66 v = torch.randn(n_source_samples, requires_grad=True)
67
68 reg = 0.5
69
70 optimizer = torch.optim.Adam([u, v], lr=1)
71
72 # number of iteration
73 n_iter = 200
74
75
76 losses = []
77
78 for i in range(n_iter):
79 # generate noise samples
80
81 # minus because we maximize the dual loss
82 loss = -ot.stochastic.loss_dual_entropic(u, v, xs, xt, reg=reg)
83 losses.append(float(loss.detach()))
84
85 if i % 10 == 0:
86 print("Iter: {:3d}, loss={}".format(i, losses[-1]))
87
88 loss.backward()
89 optimizer.step()
90 optimizer.zero_grad()
91
92
93 pl.figure(2)
94 pl.plot(losses)
95 pl.grid()
96 pl.title("Dual objective (negative)")
97 pl.xlabel("Iterations")
98
99 Ge = ot.stochastic.plan_dual_entropic(u, v, xs, xt, reg=reg)
100
101 # %%
102 # Plot the estimated entropic OT plan
103 # -----------------------------------
104
105 pl.figure(3, (10, 5))
106 pl.clf()
107 ot.plot.plot2D_samples_mat(Xs, Xt, Ge.detach().numpy(), alpha=0.1)
108 pl.scatter(Xs[:, 0], Xs[:, 1], marker="+", label="Source samples", zorder=2)
109 pl.scatter(Xt[:, 0], Xt[:, 1], marker="o", label="Target samples", zorder=2)
110 pl.legend(loc=0)
111 pl.title("Source and target distributions")
112
113
114 # %%
115 # Estimating dual variables for quadratic OT
116 # ------------------------------------------
117
118 u = torch.randn(n_source_samples, requires_grad=True)
119 v = torch.randn(n_source_samples, requires_grad=True)
120
121 reg = 0.01
122
123 optimizer = torch.optim.Adam([u, v], lr=1)
124
125 # number of iteration
126 n_iter = 200
127
128
129 losses = []
130
131
132 for i in range(n_iter):
133 # generate noise samples
134
135 # minus because we maximize the dual loss
136 loss = -ot.stochastic.loss_dual_quadratic(u, v, xs, xt, reg=reg)
137 losses.append(float(loss.detach()))
138
139 if i % 10 == 0:
140 print("Iter: {:3d}, loss={}".format(i, losses[-1]))
141
142 loss.backward()
143 optimizer.step()
144 optimizer.zero_grad()
145
146
147 pl.figure(4)
148 pl.plot(losses)
149 pl.grid()
150 pl.title("Dual objective (negative)")
151 pl.xlabel("Iterations")
152
153 Gq = ot.stochastic.plan_dual_quadratic(u, v, xs, xt, reg=reg)
154
155
156 # %%
157 # Plot the estimated quadratic OT plan
158 # ------------------------------------
159
160 pl.figure(5, (10, 5))
161 pl.clf()
162 ot.plot.plot2D_samples_mat(Xs, Xt, Gq.detach().numpy(), alpha=0.1)
163 pl.scatter(Xs[:, 0], Xs[:, 1], marker="+", label="Source samples", zorder=2)
164 pl.scatter(Xt[:, 0], Xt[:, 1], marker="o", label="Target samples", zorder=2)
165 pl.legend(loc=0)
166 pl.title("OT plan with quadratic regularization")