|
| 1 | +# -*- coding: utf-8 -*- |
| 2 | +""" |
| 3 | +==================== |
| 4 | +Gromov-Wasserstein example |
| 5 | +==================== |
| 6 | +
|
| 7 | +This example is designed to show how to use the Gromov-Wassertsein distance |
| 8 | +computation in POT. |
| 9 | +
|
| 10 | +
|
| 11 | +""" |
| 12 | + |
| 13 | +# Author: Erwan Vautier <erwan.vautier@gmail.com> |
| 14 | +# Nicolas Courty <ncourty@irisa.fr> |
| 15 | +# |
| 16 | +# License: MIT License |
| 17 | + |
| 18 | +import scipy as sp |
| 19 | +import numpy as np |
| 20 | + |
| 21 | +import ot |
| 22 | +import matplotlib.pylab as pl |
| 23 | +from mpl_toolkits.mplot3d import Axes3D |
| 24 | + |
| 25 | + |
| 26 | + |
| 27 | +""" |
| 28 | +Sample two Gaussian distributions (2D and 3D) |
| 29 | +==================== |
| 30 | +
|
| 31 | +The Gromov-Wasserstein distance allows to compute distances with samples that do not belong to the same metric space. For |
| 32 | +demonstration purpose, we sample two Gaussian distributions in 2- and 3-dimensional spaces. |
| 33 | +
|
| 34 | +""" |
| 35 | +n=30 # nb samples |
| 36 | + |
| 37 | +mu_s=np.array([0,0]) |
| 38 | +cov_s=np.array([[1,0],[0,1]]) |
| 39 | + |
| 40 | +mu_t=np.array([4,4,4]) |
| 41 | +cov_t=np.array([[1,0,0],[0,1,0],[0,0,1]]) |
| 42 | + |
| 43 | + |
| 44 | + |
| 45 | +xs=ot.datasets.get_2D_samples_gauss(n,mu_s,cov_s) |
| 46 | +P=sp.linalg.sqrtm(cov_t) |
| 47 | +xt= np.random.randn(n,3).dot(P)+mu_t |
| 48 | + |
| 49 | + |
| 50 | + |
| 51 | +""" |
| 52 | +Plotting the distributions |
| 53 | +==================== |
| 54 | +""" |
| 55 | +fig=pl.figure() |
| 56 | +ax1=fig.add_subplot(121) |
| 57 | +ax1.plot(xs[:,0],xs[:,1],'+b',label='Source samples') |
| 58 | +ax2=fig.add_subplot(122,projection='3d') |
| 59 | +ax2.scatter(xt[:,0],xt[:,1],xt[:,2],color='r') |
| 60 | +pl.show() |
| 61 | + |
| 62 | + |
| 63 | +""" |
| 64 | +Compute distance kernels, normalize them and then display |
| 65 | +==================== |
| 66 | +""" |
| 67 | + |
| 68 | +C1=sp.spatial.distance.cdist(xs,xs) |
| 69 | +C2=sp.spatial.distance.cdist(xt,xt) |
| 70 | + |
| 71 | +C1/=C1.max() |
| 72 | +C2/=C2.max() |
| 73 | + |
| 74 | +pl.figure() |
| 75 | +pl.subplot(121) |
| 76 | +pl.imshow(C1) |
| 77 | +pl.subplot(122) |
| 78 | +pl.imshow(C2) |
| 79 | +pl.show() |
| 80 | + |
| 81 | +""" |
| 82 | +Compute Gromov-Wasserstein plans and distance |
| 83 | +==================== |
| 84 | +""" |
| 85 | + |
| 86 | +p=ot.unif(n) |
| 87 | +q=ot.unif(n) |
| 88 | + |
| 89 | +gw=ot.gromov_wasserstein(C1,C2,p,q,'square_loss',epsilon=5e-4) |
| 90 | +gw_dist=ot.gromov_wasserstein2(C1,C2,p,q,'square_loss',epsilon=5e-4) |
| 91 | + |
| 92 | +print('Gromov-Wasserstein distances between the distribution: '+str(gw_dist)) |
| 93 | + |
| 94 | +pl.figure() |
| 95 | +pl.imshow(gw,cmap='jet') |
| 96 | +pl.colorbar() |
| 97 | +pl.show() |
| 98 | + |
0 commit comments