summaryrefslogtreecommitdiff
path: root/examples/unbalanced-partial/plot_regpath.py
blob: 782e8c25909e71b64f545b36229c4d47da935195 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
# -*- coding: utf-8 -*-
"""
================================================================
Regularization path of l2-penalized unbalanced optimal transport
================================================================
This example illustrate the regularization path for 2D unbalanced
optimal transport. We present here both the fully relaxed case
and the semi-relaxed case.

[Chapel et al., 2021] Chapel, L., Flamary, R., Wu, H., Févotte, C.,
and Gasso, G. (2021). Unbalanced optimal transport through non-negative
penalized linear regression.
"""

# Author: Haoran Wu <haoran.wu@univ-ubs.fr>
# License: MIT License

# sphinx_gallery_thumbnail_number = 2

import numpy as np
import matplotlib.pylab as pl
import ot
import matplotlib.animation as animation
##############################################################################
# Generate data
# -------------

#%% parameters and data generation

n = 50  # nb samples

mu_s = np.array([-1, -1])
cov_s = np.array([[1, 0], [0, 1]])

mu_t = np.array([4, 4])
cov_t = np.array([[1, -.8], [-.8, 1]])

np.random.seed(0)
xs = ot.datasets.make_2D_samples_gauss(n, mu_s, cov_s)
xt = ot.datasets.make_2D_samples_gauss(n, mu_t, cov_t)

a, b = np.ones((n,)) / n, np.ones((n,)) / n  # uniform distribution on samples

# loss matrix
M = ot.dist(xs, xt)
M /= M.max()

##############################################################################
# Plot data
# ---------

#%% plot 2 distribution samples

pl.figure(1)
pl.scatter(xs[:, 0], xs[:, 1], c='C0', label='Source')
pl.scatter(xt[:, 0], xt[:, 1], c='C1', label='Target')
pl.legend(loc=2)
pl.title('Source and target distributions')
pl.show()

##############################################################################
# Compute semi-relaxed and fully relaxed regularization paths
# -----------

#%%
final_gamma = 1e-8
t, t_list, g_list = ot.regpath.regularization_path(a, b, M, reg=final_gamma,
                                                   semi_relaxed=False)
t2, t_list2, g_list2 = ot.regpath.regularization_path(a, b, M, reg=final_gamma,
                                                      semi_relaxed=True)


##############################################################################
# Plot the regularization path
# ----------------
#
# The OT plan is ploted as a function of $\gamma$ that is the inverse of the
# weight on the marginal relaxations.

#%% fully relaxed l2-penalized UOT

pl.figure(2)
selected_gamma = [2e-1, 1e-1, 5e-2, 1e-3]
for p in range(4):
    tp = ot.regpath.compute_transport_plan(selected_gamma[p], g_list,
                                           t_list)
    P = tp.reshape((n, n))
    pl.subplot(2, 2, p + 1)
    if P.sum() > 0:
        P = P / P.max()
    for i in range(n):
        for j in range(n):
            if P[i, j] > 0:
                pl.plot([xs[i, 0], xt[j, 0]], [xs[i, 1], xt[j, 1]], color='C2',
                        alpha=P[i, j] * 0.3)
    pl.scatter(xs[:, 0], xs[:, 1], c='C0', alpha=0.2)
    pl.scatter(xt[:, 0], xt[:, 1], c='C1', alpha=0.2)
    pl.scatter(xs[:, 0], xs[:, 1], c='C0', s=P.sum(1).ravel() * (1 + p) * 2,
               label='Re-weighted source', alpha=1)
    pl.scatter(xt[:, 0], xt[:, 1], c='C1', s=P.sum(0).ravel() * (1 + p) * 2,
               label='Re-weighted target', alpha=1)
    pl.plot([], [], color='C2', alpha=0.8, label='OT plan')
    pl.title(r'$\ell_2$ UOT $\gamma$={}'.format(selected_gamma[p]),
             fontsize=11)
    if p < 2:
        pl.xticks(())
pl.show()


# %%
# Animation of the regpath for UOT l2
# ------------------------

nv = 100
g_list_v = np.logspace(-.5, -2.5, nv)

pl.figure(3)


def _update_plot(iv):
    pl.clf()
    tp = ot.regpath.compute_transport_plan(g_list_v[iv], g_list,
                                           t_list)
    P = tp.reshape((n, n))
    if P.sum() > 0:
        P = P / P.max()
    for i in range(n):
        for j in range(n):
            if P[i, j] > 0:
                pl.plot([xs[i, 0], xt[j, 0]], [xs[i, 1], xt[j, 1]], color='C2',
                        alpha=P[i, j] * 0.5)
    pl.scatter(xs[:, 0], xs[:, 1], c='C0', alpha=0.2)
    pl.scatter(xt[:, 0], xt[:, 1], c='C1', alpha=0.2)
    pl.scatter(xs[:, 0], xs[:, 1], c='C0', s=P.sum(1).ravel() * (1 + p) * 4,
               label='Re-weighted source', alpha=1)
    pl.scatter(xt[:, 0], xt[:, 1], c='C1', s=P.sum(0).ravel() * (1 + p) * 4,
               label='Re-weighted target', alpha=1)
    pl.plot([], [], color='C2', alpha=0.8, label='OT plan')
    pl.title(r'$\ell_2$ UOT $\gamma$={:1.3f}'.format(g_list_v[iv]),
             fontsize=11)
    return 1


i = 0
_update_plot(i)

ani = animation.FuncAnimation(pl.gcf(), _update_plot, nv, interval=50, repeat_delay=2000)


##############################################################################
# Plot the semi-relaxed regularization path
# -------------------

#%% semi-relaxed l2-penalized UOT

pl.figure(4)
selected_gamma = [10, 1, 1e-1, 1e-2]
for p in range(4):
    tp = ot.regpath.compute_transport_plan(selected_gamma[p], g_list2,
                                           t_list2)
    P = tp.reshape((n, n))
    pl.subplot(2, 2, p + 1)
    if P.sum() > 0:
        P = P / P.max()
    for i in range(n):
        for j in range(n):
            if P[i, j] > 0:
                pl.plot([xs[i, 0], xt[j, 0]], [xs[i, 1], xt[j, 1]], color='C2',
                        alpha=P[i, j] * 0.3)
    pl.scatter(xs[:, 0], xs[:, 1], c='C0', alpha=0.2)
    pl.scatter(xt[:, 0], xt[:, 1], c='C1', alpha=1, label='Target marginal')
    pl.scatter(xs[:, 0], xs[:, 1], c='C0', s=P.sum(1).ravel() * 2 * (1 + p),
               label='Source marginal', alpha=1)
    pl.plot([], [], color='C2', alpha=0.8, label='OT plan')
    pl.title(r'Semi-relaxed $l_2$ UOT $\gamma$={}'.format(selected_gamma[p]),
             fontsize=11)
    if p < 2:
        pl.xticks(())
pl.show()


# %%
# Animation of the regpath for semi-relaxed UOT l2
# ------------------------

nv = 100
g_list_v = np.logspace(2.5, -2, nv)

pl.figure(5)


def _update_plot(iv):
    pl.clf()
    tp = ot.regpath.compute_transport_plan(g_list_v[iv], g_list2,
                                           t_list2)
    P = tp.reshape((n, n))
    if P.sum() > 0:
        P = P / P.max()
    for i in range(n):
        for j in range(n):
            if P[i, j] > 0:
                pl.plot([xs[i, 0], xt[j, 0]], [xs[i, 1], xt[j, 1]], color='C2',
                        alpha=P[i, j] * 0.5)
    pl.scatter(xs[:, 0], xs[:, 1], c='C0', alpha=0.2)
    pl.scatter(xt[:, 0], xt[:, 1], c='C1', alpha=0.2)
    pl.scatter(xs[:, 0], xs[:, 1], c='C0', s=P.sum(1).ravel() * (1 + p) * 4,
               label='Re-weighted source', alpha=1)
    pl.scatter(xt[:, 0], xt[:, 1], c='C1', s=P.sum(0).ravel() * (1 + p) * 4,
               label='Re-weighted target', alpha=1)
    pl.plot([], [], color='C2', alpha=0.8, label='OT plan')
    pl.title(r'Semi-relaxed $\ell_2$ UOT $\gamma$={:1.3f}'.format(g_list_v[iv]),
             fontsize=11)
    return 1


i = 0
_update_plot(i)

ani = animation.FuncAnimation(pl.gcf(), _update_plot, nv, interval=50, repeat_delay=2000)