Debian Codegraph @

examples/unbalanced-partial/plot_UOT_1D.py

raw symbols SCIP
1 # -*- coding: utf-8 -*-
2 """
3 ===============================
4 1D Unbalanced optimal transport
5 ===============================
6
7 This example illustrates the computation of Unbalanced Optimal transport
8 using a Kullback-Leibler relaxation.
9 """
10
11 # Author: Hicham Janati <[email protected]>
12 #
13 # License: MIT License
14
15 # sphinx_gallery_thumbnail_number = 4
16
17 import numpy as np
18 import matplotlib.pylab as pl
19 import ot
20 import ot.plot
21 from ot.datasets import make_1D_gauss as gauss
22
23 ##############################################################################
24 # Generate data
25 # -------------
26
27
28 # %% parameters
29
30 n = 100 # nb bins
31
32 # bin positions
33 x = np.arange(n, dtype=np.float64)
34
35 # Gaussian distributions
36 a = gauss(n, m=20, s=5) # m= mean, s= std
37 b = gauss(n, m=60, s=10)
38
39 # make distributions unbalanced
40 b *= 5.0
41
42 # loss matrix
43 M = ot.dist(x.reshape((n, 1)), x.reshape((n, 1)))
44 M /= M.max()
45
46
47 ##############################################################################
48 # Plot distributions and loss matrix
49 # ----------------------------------
50
51 # %% plot the distributions
52
53 pl.figure(1, figsize=(6.4, 3))
54 pl.plot(x, a, "b", label="Source distribution")
55 pl.plot(x, b, "r", label="Target distribution")
56 pl.legend()
57
58 # plot distributions and loss matrix
59
60 pl.figure(2, figsize=(5, 5))
61 ot.plot.plot1D_mat(a, b, M, "Cost matrix M")
62
63
64 ##############################################################################
65 # Solve Unbalanced Sinkhorn
66 # -------------------------
67
68 # Sinkhorn
69
70 epsilon = 0.1 # entropy parameter
71 alpha = 1.0 # Unbalanced KL relaxation parameter
72 Gs = ot.unbalanced.sinkhorn_unbalanced(a, b, M, epsilon, alpha, verbose=True)
73
74 pl.figure(3, figsize=(5, 5))
75 ot.plot.plot1D_mat(a, b, Gs, "UOT matrix Sinkhorn")
76
77 pl.show()
78
79
80 # %%
81 # plot the transported mass
82 # -------------------------
83
84 pl.figure(4, figsize=(6.4, 3))
85 pl.plot(x, a, "b", label="Source distribution")
86 pl.plot(x, b, "r", label="Target distribution")
87 pl.fill(x, Gs.sum(1), "b", alpha=0.5, label="Transported source")
88 pl.fill(x, Gs.sum(0), "r", alpha=0.5, label="Transported target")
89 pl.legend(loc="upper right")
90 pl.title("Distributions and transported mass for UOT")