Debian Codegraph @

examples/backends/plot_unmix_optim_torch.py

raw symbols SCIP
1 # -*- coding: utf-8 -*-
2 r"""
3 =================================
4 Wasserstein unmixing with PyTorch
5 =================================
6
7 In this example we estimate mixing parameters from distributions that minimize
8 the Wasserstein distance. In other words we suppose that a target
9 distribution :math:`\mu^t` can be expressed as a weighted sum of source
10 distributions :math:`\mu^s_k` with the following model:
11
12 .. math::
13 \mu^t = \sum_{k=1}^K w_k\mu^s_k
14
15 where :math:`\mathbf{w}` is a vector of size :math:`K` and belongs in the
16 distribution simplex :math:`\Delta_K`.
17
18 In order to estimate this weight vector we propose to optimize the Wasserstein
19 distance between the model and the observed :math:`\mu^t` with respect to
20 the vector. This leads to the following optimization problem:
21
22 .. math::
23 \min_{\mathbf{w}\in\Delta_K} \quad W \left(\mu^t,\sum_{k=1}^K w_k\mu^s_k\right)
24
25 This minimization is done in this example with a simple projected gradient
26 descent in PyTorch. We use the automatic backend of POT that allows us to
27 compute the Wasserstein distance with :any:`ot.emd2` with
28 differentiable losses.
29
30 """
31
32 # Author: Remi Flamary <[email protected]>
33 #
34 # License: MIT License
35
36 # sphinx_gallery_thumbnail_number = 2
37
38 import numpy as np
39 import matplotlib.pylab as pl
40 import ot
41 import torch
42
43
44 ##############################################################################
45 # Generate data
46 # -------------
47
48 # %% Data
49
50 nt = 100
51 nt1 = 10 #
52
53 ns1 = 50
54 ns = 2 * ns1
55
56 rng = np.random.RandomState(2)
57
58 xt = rng.randn(nt, 2) * 0.2
59 xt[:nt1, 0] += 1
60 xt[nt1:, 1] += 1
61
62
63 xs1 = rng.randn(ns1, 2) * 0.2
64 xs1[:, 0] += 1
65 xs2 = rng.randn(ns1, 2) * 0.2
66 xs2[:, 1] += 1
67
68 xs = np.concatenate((xs1, xs2))
69
70 # Sample reweighting matrix H
71 H = np.zeros((ns, 2))
72 H[:ns1, 0] = 1 / ns1
73 H[ns1:, 1] = 1 / ns1
74 # each columns sums to 1 and has weights only for samples form the
75 # corresponding source distribution
76
77 M = ot.dist(xs, xt)
78
79 ##############################################################################
80 # Plot data
81 # ---------
82
83 # %% plot the distributions
84
85 pl.figure(1)
86 pl.scatter(xt[:, 0], xt[:, 1], label="Target $\mu^t$", alpha=0.5)
87 pl.scatter(xs1[:, 0], xs1[:, 1], label="Source $\mu^s_1$", alpha=0.5)
88 pl.scatter(xs2[:, 0], xs2[:, 1], label="Source $\mu^s_2$", alpha=0.5)
89 pl.title("Sources and Target distributions")
90 pl.legend()
91
92
93 ##############################################################################
94 # Optimization of the model wrt the Wasserstein distance
95 # ------------------------------------------------------
96
97
98 # %% Weights optimization with gradient descent
99
100 # convert numpy arrays to torch tensors
101 H2 = torch.tensor(H)
102 M2 = torch.tensor(M)
103
104 # weights for the source distributions
105 w = torch.tensor(ot.unif(2), requires_grad=True)
106
107 # uniform weights for target
108 b = torch.tensor(ot.unif(nt))
109
110 lr = 2e-3 # learning rate
111 niter = 500 # number of iterations
112 losses = [] # loss along the iterations
113
114 # loss for the minimal Wasserstein estimator
115
116
117 def get_loss(w):
118 a = torch.mv(H2, w) # distribution reweighting
119 return ot.emd2(a, b, M2) # squared Wasserstein 2
120
121
122 for i in range(niter):
123 loss = get_loss(w)
124 losses.append(float(loss))
125
126 loss.backward()
127
128 with torch.no_grad():
129 w -= lr * w.grad # gradient step
130 w[:] = ot.utils.proj_simplex(w) # projection on the simplex
131
132 w.grad.zero_()
133
134
135 ##############################################################################
136 # Estimated weights and convergence of the objective
137 # --------------------------------------------------
138
139 we = w.detach().numpy()
140 print("Estimated mixture:", we)
141
142 pl.figure(2)
143 pl.semilogy(losses)
144 pl.grid()
145 pl.title("Wasserstein distance")
146 pl.xlabel("Iterations")
147
148 ##############################################################################
149 # Plotting the reweighted source distribution
150 # -------------------------------------------
151
152 pl.figure(3)
153
154 # compute source weights
155 ws = H.dot(we)
156
157 pl.scatter(xt[:, 0], xt[:, 1], label="Target $\mu^t$", alpha=0.5)
158 pl.scatter(
159 xs[:, 0],
160 xs[:, 1],
161 color="C3",
162 s=ws * 20 * ns,
163 label="Weighted sources $\sum_{k} w_k\mu^s_k$",
164 alpha=0.5,
165 )
166 pl.title("Target and reweighted source distributions")
167 pl.legend()