From ee19d423adc85a960c9a46e4f81c370196805dbf Mon Sep 17 00:00:00 2001 From: RĂ©mi Flamary Date: Fri, 16 Feb 2018 15:04:04 +0100 Subject: update notebooks --- docs/cache_nbrun | 2 +- .../source/auto_examples/auto_examples_jupyter.zip | Bin 89148 -> 85906 bytes docs/source/auto_examples/auto_examples_python.zip | Bin 59370 -> 58682 bytes .../images/sphx_glr_plot_barycenter_1D_003.png | Bin 41555 -> 108687 bytes .../images/sphx_glr_plot_gromov_001.png | Bin 46633 -> 16548 bytes .../images/sphx_glr_plot_gromov_002.png | Bin 16945 -> 17330 bytes .../images/sphx_glr_plot_gromov_barycenter_001.png | Bin 47537 -> 48271 bytes .../images/sphx_glr_plot_otda_d2_001.png | Bin 131063 -> 130442 bytes .../images/sphx_glr_plot_otda_d2_003.png | Bin 213055 -> 216096 bytes .../images/sphx_glr_plot_otda_d2_006.png | Bin 99762 -> 102285 bytes .../images/thumb/sphx_glr_plot_OT_1D_thumb.png | Bin 18227 -> 14983 bytes .../thumb/sphx_glr_plot_OT_L1_vs_L2_thumb.png | Bin 10935 -> 9383 bytes .../thumb/sphx_glr_plot_barycenter_1D_thumb.png | Bin 16522 -> 13541 bytes .../sphx_glr_plot_gromov_barycenter_thumb.png | Bin 34183 -> 28787 bytes .../images/thumb/sphx_glr_plot_gromov_thumb.png | Bin 30843 -> 17804 bytes .../images/thumb/sphx_glr_plot_otda_d2_thumb.png | Bin 52743 -> 47553 bytes docs/source/auto_examples/index.rst | 67 +-- docs/source/auto_examples/plot_OT_1D.ipynb | 170 +++---- docs/source/auto_examples/plot_OT_1D.py | 1 + docs/source/auto_examples/plot_OT_1D.rst | 14 +- docs/source/auto_examples/plot_OT_L1_vs_L2.ipynb | 170 +++---- docs/source/auto_examples/plot_OT_L1_vs_L2.py | 1 + docs/source/auto_examples/plot_OT_L1_vs_L2.rst | 14 +- docs/source/auto_examples/plot_barycenter_1D.ipynb | 144 ++---- docs/source/auto_examples/plot_barycenter_1D.py | 8 +- docs/source/auto_examples/plot_barycenter_1D.rst | 125 ++--- docs/source/auto_examples/plot_gromov.ipynb | 144 ++---- docs/source/auto_examples/plot_gromov.py | 32 +- docs/source/auto_examples/plot_gromov.rst | 206 +++++---- .../auto_examples/plot_gromov_barycenter.ipynb | 178 ++++---- .../source/auto_examples/plot_gromov_barycenter.py | 8 +- .../auto_examples/plot_gromov_barycenter.rst | 507 +++++++++++---------- docs/source/auto_examples/plot_optim_OTreg.ipynb | 194 ++++---- docs/source/auto_examples/plot_optim_OTreg.py | 2 +- docs/source/auto_examples/plot_optim_OTreg.rst | 15 +- docs/source/auto_examples/plot_otda_d2.ipynb | 194 ++++---- docs/source/auto_examples/plot_otda_d2.py | 2 +- docs/source/auto_examples/plot_otda_d2.rst | 15 +- 38 files changed, 1047 insertions(+), 1166 deletions(-) diff --git a/docs/cache_nbrun b/docs/cache_nbrun index 3f1e6ea..ae0fe23 100644 --- a/docs/cache_nbrun +++ b/docs/cache_nbrun @@ -1 +1 @@ -{"plot_otda_mapping_colors_images.ipynb": "4f0587a00a3c082799a75a0ed36e9ce1", "plot_optim_OTreg.ipynb": "71d3c106b3f395a6b1001078a6ca6f8d", "plot_otda_color_images.ipynb": "d047d635f4987c81072383241590e21f", "plot_WDA.ipynb": "27f8de4c6d7db46497076523673eedfb", "plot_OT_L1_vs_L2.ipynb": "e15219bf651a7e39e7c5c3934069894c", "plot_barycenter_1D.ipynb": "6fd8167f98816dc832fe0c58b1d5527b", "plot_otda_classes.ipynb": "44bb8cd93317b5d342cd62e26d9bbe60", "plot_otda_d2.ipynb": "8ac4fd2ff899df0858ce1e5fead37f33", "plot_otda_mapping.ipynb": "d335a15af828aaa3439a1c67570d79d6", "plot_gromov.ipynb": "9d0893ec68851f200d0ca806bcbe847f", "plot_compute_emd.ipynb": "bd95981189df6adcb113d9b360ead734", "plot_OT_1D.ipynb": "e44c83f6112388ae18657cb0ad76d0e9", "plot_gromov_barycenter.ipynb": "a4d9636685394ceb13f26cdc613b9b5b", "plot_otda_semi_supervised.ipynb": "0261d339a692e339e15d3634488905cc", "plot_OT_2D_samples.ipynb": "3f125714daa35ff3cfe5dae1f71265c4"} \ No newline at end of file +{"plot_otda_mapping_colors_images.ipynb": "4f0587a00a3c082799a75a0ed36e9ce1", "plot_optim_OTreg.ipynb": "2ec33a099bb67120a134332a20f29313", "plot_barycenter_1D.ipynb": "95708b025b6d96d97f579d30d268cbff", "plot_WDA.ipynb": "27f8de4c6d7db46497076523673eedfb", "plot_OT_L1_vs_L2.ipynb": "871d60931f5118c085342e11cb638336", "plot_otda_color_images.ipynb": "d047d635f4987c81072383241590e21f", "plot_otda_classes.ipynb": "44bb8cd93317b5d342cd62e26d9bbe60", "plot_otda_d2.ipynb": "1a9547f07317612e1a161b7d9f07a5a8", "plot_otda_mapping.ipynb": "d335a15af828aaa3439a1c67570d79d6", "plot_gromov.ipynb": "243e64c7d13afa8dfa10fc3ccb4e1e28", "plot_compute_emd.ipynb": "bd95981189df6adcb113d9b360ead734", "plot_OT_1D.ipynb": "54dfea8ccb61f30729519275785c494c", "plot_gromov_barycenter.ipynb": "953e5047b886ec69ec621ec52f5e21d1", "plot_otda_semi_supervised.ipynb": "0261d339a692e339e15d3634488905cc", "plot_OT_2D_samples.ipynb": "3f125714daa35ff3cfe5dae1f71265c4"} \ No newline at end of file diff --git a/docs/source/auto_examples/auto_examples_jupyter.zip b/docs/source/auto_examples/auto_examples_jupyter.zip index 5a3f24c..42f42de 100644 Binary files a/docs/source/auto_examples/auto_examples_jupyter.zip and b/docs/source/auto_examples/auto_examples_jupyter.zip differ diff --git a/docs/source/auto_examples/auto_examples_python.zip b/docs/source/auto_examples/auto_examples_python.zip index aa06bb6..0fb2cda 100644 Binary files a/docs/source/auto_examples/auto_examples_python.zip and b/docs/source/auto_examples/auto_examples_python.zip differ diff --git a/docs/source/auto_examples/images/sphx_glr_plot_barycenter_1D_003.png b/docs/source/auto_examples/images/sphx_glr_plot_barycenter_1D_003.png index 3b23af5..eac9230 100644 Binary files a/docs/source/auto_examples/images/sphx_glr_plot_barycenter_1D_003.png and b/docs/source/auto_examples/images/sphx_glr_plot_barycenter_1D_003.png differ diff --git a/docs/source/auto_examples/images/sphx_glr_plot_gromov_001.png b/docs/source/auto_examples/images/sphx_glr_plot_gromov_001.png index b4571fa..09864f2 100644 Binary files a/docs/source/auto_examples/images/sphx_glr_plot_gromov_001.png and b/docs/source/auto_examples/images/sphx_glr_plot_gromov_001.png differ diff --git a/docs/source/auto_examples/images/sphx_glr_plot_gromov_002.png b/docs/source/auto_examples/images/sphx_glr_plot_gromov_002.png index 58c02d7..b2e3fa4 100644 Binary files a/docs/source/auto_examples/images/sphx_glr_plot_gromov_002.png and b/docs/source/auto_examples/images/sphx_glr_plot_gromov_002.png differ diff --git a/docs/source/auto_examples/images/sphx_glr_plot_gromov_barycenter_001.png b/docs/source/auto_examples/images/sphx_glr_plot_gromov_barycenter_001.png index 715a116..0665c9b 100644 Binary files a/docs/source/auto_examples/images/sphx_glr_plot_gromov_barycenter_001.png and b/docs/source/auto_examples/images/sphx_glr_plot_gromov_barycenter_001.png differ diff --git a/docs/source/auto_examples/images/sphx_glr_plot_otda_d2_001.png b/docs/source/auto_examples/images/sphx_glr_plot_otda_d2_001.png index ef8cfd1..ff9c008 100644 Binary files a/docs/source/auto_examples/images/sphx_glr_plot_otda_d2_001.png and b/docs/source/auto_examples/images/sphx_glr_plot_otda_d2_001.png differ diff --git a/docs/source/auto_examples/images/sphx_glr_plot_otda_d2_003.png b/docs/source/auto_examples/images/sphx_glr_plot_otda_d2_003.png index 1ba5b1b..e4831ba 100644 Binary files a/docs/source/auto_examples/images/sphx_glr_plot_otda_d2_003.png and b/docs/source/auto_examples/images/sphx_glr_plot_otda_d2_003.png differ diff --git a/docs/source/auto_examples/images/sphx_glr_plot_otda_d2_006.png b/docs/source/auto_examples/images/sphx_glr_plot_otda_d2_006.png index d67fea1..81cbbd0 100644 Binary files a/docs/source/auto_examples/images/sphx_glr_plot_otda_d2_006.png and b/docs/source/auto_examples/images/sphx_glr_plot_otda_d2_006.png differ diff --git a/docs/source/auto_examples/images/thumb/sphx_glr_plot_OT_1D_thumb.png b/docs/source/auto_examples/images/thumb/sphx_glr_plot_OT_1D_thumb.png index 63ff40c..a44f37b 100644 Binary files a/docs/source/auto_examples/images/thumb/sphx_glr_plot_OT_1D_thumb.png and b/docs/source/auto_examples/images/thumb/sphx_glr_plot_OT_1D_thumb.png differ diff --git a/docs/source/auto_examples/images/thumb/sphx_glr_plot_OT_L1_vs_L2_thumb.png b/docs/source/auto_examples/images/thumb/sphx_glr_plot_OT_L1_vs_L2_thumb.png index 95588f5..4989860 100644 Binary files a/docs/source/auto_examples/images/thumb/sphx_glr_plot_OT_L1_vs_L2_thumb.png and b/docs/source/auto_examples/images/thumb/sphx_glr_plot_OT_L1_vs_L2_thumb.png differ diff --git a/docs/source/auto_examples/images/thumb/sphx_glr_plot_barycenter_1D_thumb.png b/docs/source/auto_examples/images/thumb/sphx_glr_plot_barycenter_1D_thumb.png index 5c17671..9bdd23b 100644 Binary files a/docs/source/auto_examples/images/thumb/sphx_glr_plot_barycenter_1D_thumb.png and b/docs/source/auto_examples/images/thumb/sphx_glr_plot_barycenter_1D_thumb.png differ diff --git a/docs/source/auto_examples/images/thumb/sphx_glr_plot_gromov_barycenter_thumb.png b/docs/source/auto_examples/images/thumb/sphx_glr_plot_gromov_barycenter_thumb.png index 85a94ff..df25b39 100644 Binary files a/docs/source/auto_examples/images/thumb/sphx_glr_plot_gromov_barycenter_thumb.png and b/docs/source/auto_examples/images/thumb/sphx_glr_plot_gromov_barycenter_thumb.png differ diff --git a/docs/source/auto_examples/images/thumb/sphx_glr_plot_gromov_thumb.png b/docs/source/auto_examples/images/thumb/sphx_glr_plot_gromov_thumb.png index 26b0b2f..c54f6b3 100644 Binary files a/docs/source/auto_examples/images/thumb/sphx_glr_plot_gromov_thumb.png and b/docs/source/auto_examples/images/thumb/sphx_glr_plot_gromov_thumb.png differ diff --git a/docs/source/auto_examples/images/thumb/sphx_glr_plot_otda_d2_thumb.png b/docs/source/auto_examples/images/thumb/sphx_glr_plot_otda_d2_thumb.png index bd32092..80b9a32 100644 Binary files a/docs/source/auto_examples/images/thumb/sphx_glr_plot_otda_d2_thumb.png and b/docs/source/auto_examples/images/thumb/sphx_glr_plot_otda_d2_thumb.png differ diff --git a/docs/source/auto_examples/index.rst b/docs/source/auto_examples/index.rst index eb54ca8..227c40c 100644 --- a/docs/source/auto_examples/index.rst +++ b/docs/source/auto_examples/index.rst @@ -1,8 +1,12 @@ +:orphan: + POT Examples ============ This is a gallery of all the POT example files. + + .. raw:: html
@@ -45,13 +49,13 @@ This is a gallery of all the POT example files. .. raw:: html -
+
.. only:: html - .. figure:: /auto_examples/images/thumb/sphx_glr_plot_gromov_thumb.png + .. figure:: /auto_examples/images/thumb/sphx_glr_plot_OT_2D_samples_thumb.png - :ref:`sphx_glr_auto_examples_plot_gromov.py` + :ref:`sphx_glr_auto_examples_plot_OT_2D_samples.py` .. raw:: html @@ -61,17 +65,17 @@ This is a gallery of all the POT example files. .. toctree:: :hidden: - /auto_examples/plot_gromov + /auto_examples/plot_OT_2D_samples .. raw:: html -
+
.. only:: html - .. figure:: /auto_examples/images/thumb/sphx_glr_plot_OT_2D_samples_thumb.png + .. figure:: /auto_examples/images/thumb/sphx_glr_plot_compute_emd_thumb.png - :ref:`sphx_glr_auto_examples_plot_OT_2D_samples.py` + :ref:`sphx_glr_auto_examples_plot_compute_emd.py` .. raw:: html @@ -81,17 +85,17 @@ This is a gallery of all the POT example files. .. toctree:: :hidden: - /auto_examples/plot_OT_2D_samples + /auto_examples/plot_compute_emd .. raw:: html -
+
.. only:: html - .. figure:: /auto_examples/images/thumb/sphx_glr_plot_compute_emd_thumb.png + .. figure:: /auto_examples/images/thumb/sphx_glr_plot_WDA_thumb.png - :ref:`sphx_glr_auto_examples_plot_compute_emd.py` + :ref:`sphx_glr_auto_examples_plot_WDA.py` .. raw:: html @@ -101,17 +105,17 @@ This is a gallery of all the POT example files. .. toctree:: :hidden: - /auto_examples/plot_compute_emd + /auto_examples/plot_WDA .. raw:: html -
+
.. only:: html - .. figure:: /auto_examples/images/thumb/sphx_glr_plot_WDA_thumb.png + .. figure:: /auto_examples/images/thumb/sphx_glr_plot_gromov_thumb.png - :ref:`sphx_glr_auto_examples_plot_WDA.py` + :ref:`sphx_glr_auto_examples_plot_gromov.py` .. raw:: html @@ -121,7 +125,7 @@ This is a gallery of all the POT example files. .. toctree:: :hidden: - /auto_examples/plot_WDA + /auto_examples/plot_gromov .. raw:: html @@ -145,13 +149,13 @@ This is a gallery of all the POT example files. .. raw:: html -
+
.. only:: html - .. figure:: /auto_examples/images/thumb/sphx_glr_plot_barycenter_1D_thumb.png + .. figure:: /auto_examples/images/thumb/sphx_glr_plot_otda_mapping_colors_images_thumb.png - :ref:`sphx_glr_auto_examples_plot_barycenter_1D.py` + :ref:`sphx_glr_auto_examples_plot_otda_mapping_colors_images.py` .. raw:: html @@ -161,17 +165,17 @@ This is a gallery of all the POT example files. .. toctree:: :hidden: - /auto_examples/plot_barycenter_1D + /auto_examples/plot_otda_mapping_colors_images .. raw:: html -
+
.. only:: html - .. figure:: /auto_examples/images/thumb/sphx_glr_plot_otda_mapping_colors_images_thumb.png + .. figure:: /auto_examples/images/thumb/sphx_glr_plot_barycenter_1D_thumb.png - :ref:`sphx_glr_auto_examples_plot_otda_mapping_colors_images.py` + :ref:`sphx_glr_auto_examples_plot_barycenter_1D.py` .. raw:: html @@ -181,7 +185,7 @@ This is a gallery of all the POT example files. .. toctree:: :hidden: - /auto_examples/plot_otda_mapping_colors_images + /auto_examples/plot_barycenter_1D .. raw:: html @@ -308,19 +312,24 @@ This is a gallery of all the POT example files. -.. container:: sphx-glr-footer +.. only :: html + + .. container:: sphx-glr-footer .. container:: sphx-glr-download - :download:`Download all examples in Python source code: auto_examples_python.zip ` + :download:`Download all examples in Python source code: auto_examples_python.zip ` .. container:: sphx-glr-download - :download:`Download all examples in Jupyter notebooks: auto_examples_jupyter.zip ` + :download:`Download all examples in Jupyter notebooks: auto_examples_jupyter.zip ` + + +.. only:: html -.. rst-class:: sphx-glr-signature + .. rst-class:: sphx-glr-signature - `Generated by Sphinx-Gallery `_ + `Gallery generated by Sphinx-Gallery `_ diff --git a/docs/source/auto_examples/plot_OT_1D.ipynb b/docs/source/auto_examples/plot_OT_1D.ipynb index 26748c2..649efa6 100644 --- a/docs/source/auto_examples/plot_OT_1D.ipynb +++ b/docs/source/auto_examples/plot_OT_1D.ipynb @@ -1,126 +1,126 @@ { - "nbformat_minor": 0, - "nbformat": 4, "cells": [ { - "execution_count": null, - "cell_type": "code", - "source": [ - "%matplotlib inline" - ], - "outputs": [], + "execution_count": null, "metadata": { "collapsed": false - } - }, + }, + "outputs": [], + "source": [ + "%matplotlib inline" + ], + "cell_type": "code" + }, { + "metadata": {}, "source": [ "\n# 1D optimal transport\n\n\nThis example illustrates the computation of EMD and Sinkhorn transport plans\nand their visualization.\n\n\n" - ], - "cell_type": "markdown", - "metadata": {} - }, + ], + "cell_type": "markdown" + }, { - "execution_count": null, - "cell_type": "code", - "source": [ - "# Author: Remi Flamary \n#\n# License: MIT License\n\nimport numpy as np\nimport matplotlib.pylab as pl\nimport ot\nfrom ot.datasets import get_1D_gauss as gauss" - ], - "outputs": [], + "execution_count": null, "metadata": { "collapsed": false - } - }, + }, + "outputs": [], + "source": [ + "# Author: Remi Flamary \n#\n# License: MIT License\n\nimport numpy as np\nimport matplotlib.pylab as pl\nimport ot\nimport ot.plot\nfrom ot.datasets import get_1D_gauss as gauss" + ], + "cell_type": "code" + }, { + "metadata": {}, "source": [ "Generate data\n-------------\n\n" - ], - "cell_type": "markdown", - "metadata": {} - }, + ], + "cell_type": "markdown" + }, { - "execution_count": null, - "cell_type": "code", - "source": [ - "#%% parameters\n\nn = 100 # nb bins\n\n# bin positions\nx = np.arange(n, dtype=np.float64)\n\n# Gaussian distributions\na = gauss(n, m=20, s=5) # m= mean, s= std\nb = gauss(n, m=60, s=10)\n\n# loss matrix\nM = ot.dist(x.reshape((n, 1)), x.reshape((n, 1)))\nM /= M.max()" - ], - "outputs": [], + "execution_count": null, "metadata": { "collapsed": false - } - }, + }, + "outputs": [], + "source": [ + "#%% parameters\n\nn = 100 # nb bins\n\n# bin positions\nx = np.arange(n, dtype=np.float64)\n\n# Gaussian distributions\na = gauss(n, m=20, s=5) # m= mean, s= std\nb = gauss(n, m=60, s=10)\n\n# loss matrix\nM = ot.dist(x.reshape((n, 1)), x.reshape((n, 1)))\nM /= M.max()" + ], + "cell_type": "code" + }, { + "metadata": {}, "source": [ "Plot distributions and loss matrix\n----------------------------------\n\n" - ], - "cell_type": "markdown", - "metadata": {} - }, + ], + "cell_type": "markdown" + }, { - "execution_count": null, - "cell_type": "code", - "source": [ - "#%% plot the distributions\n\npl.figure(1, figsize=(6.4, 3))\npl.plot(x, a, 'b', label='Source distribution')\npl.plot(x, b, 'r', label='Target distribution')\npl.legend()\n\n#%% plot distributions and loss matrix\n\npl.figure(2, figsize=(5, 5))\not.plot.plot1D_mat(a, b, M, 'Cost matrix M')" - ], - "outputs": [], + "execution_count": null, "metadata": { "collapsed": false - } - }, + }, + "outputs": [], + "source": [ + "#%% plot the distributions\n\npl.figure(1, figsize=(6.4, 3))\npl.plot(x, a, 'b', label='Source distribution')\npl.plot(x, b, 'r', label='Target distribution')\npl.legend()\n\n#%% plot distributions and loss matrix\n\npl.figure(2, figsize=(5, 5))\not.plot.plot1D_mat(a, b, M, 'Cost matrix M')" + ], + "cell_type": "code" + }, { + "metadata": {}, "source": [ "Solve EMD\n---------\n\n" - ], - "cell_type": "markdown", - "metadata": {} - }, + ], + "cell_type": "markdown" + }, { - "execution_count": null, - "cell_type": "code", - "source": [ - "#%% EMD\n\nG0 = ot.emd(a, b, M)\n\npl.figure(3, figsize=(5, 5))\not.plot.plot1D_mat(a, b, G0, 'OT matrix G0')" - ], - "outputs": [], + "execution_count": null, "metadata": { "collapsed": false - } - }, + }, + "outputs": [], + "source": [ + "#%% EMD\n\nG0 = ot.emd(a, b, M)\n\npl.figure(3, figsize=(5, 5))\not.plot.plot1D_mat(a, b, G0, 'OT matrix G0')" + ], + "cell_type": "code" + }, { + "metadata": {}, "source": [ "Solve Sinkhorn\n--------------\n\n" - ], - "cell_type": "markdown", - "metadata": {} - }, + ], + "cell_type": "markdown" + }, { - "execution_count": null, - "cell_type": "code", - "source": [ - "#%% Sinkhorn\n\nlambd = 1e-3\nGs = ot.sinkhorn(a, b, M, lambd, verbose=True)\n\npl.figure(4, figsize=(5, 5))\not.plot.plot1D_mat(a, b, Gs, 'OT matrix Sinkhorn')\n\npl.show()" - ], - "outputs": [], + "execution_count": null, "metadata": { "collapsed": false - } + }, + "outputs": [], + "source": [ + "#%% Sinkhorn\n\nlambd = 1e-3\nGs = ot.sinkhorn(a, b, M, lambd, verbose=True)\n\npl.figure(4, figsize=(5, 5))\not.plot.plot1D_mat(a, b, Gs, 'OT matrix Sinkhorn')\n\npl.show()" + ], + "cell_type": "code" } - ], + ], "metadata": { - "kernelspec": { - "display_name": "Python 2", - "name": "python2", - "language": "python" - }, "language_info": { - "mimetype": "text/x-python", - "nbconvert_exporter": "python", - "name": "python", - "file_extension": ".py", - "version": "2.7.12", - "pygments_lexer": "ipython2", + "name": "python", "codemirror_mode": { - "version": 2, - "name": "ipython" - } + "name": "ipython", + "version": 3 + }, + "nbconvert_exporter": "python", + "version": "3.5.2", + "pygments_lexer": "ipython3", + "file_extension": ".py", + "mimetype": "text/x-python" + }, + "kernelspec": { + "display_name": "Python 3", + "name": "python3", + "language": "python" } - } + }, + "nbformat_minor": 0, + "nbformat": 4 } \ No newline at end of file diff --git a/docs/source/auto_examples/plot_OT_1D.py b/docs/source/auto_examples/plot_OT_1D.py index 719058f..90325c9 100644 --- a/docs/source/auto_examples/plot_OT_1D.py +++ b/docs/source/auto_examples/plot_OT_1D.py @@ -16,6 +16,7 @@ and their visualization. import numpy as np import matplotlib.pylab as pl import ot +import ot.plot from ot.datasets import get_1D_gauss as gauss ############################################################################## diff --git a/docs/source/auto_examples/plot_OT_1D.rst b/docs/source/auto_examples/plot_OT_1D.rst index 975a923..5e4f73e 100644 --- a/docs/source/auto_examples/plot_OT_1D.rst +++ b/docs/source/auto_examples/plot_OT_1D.rst @@ -23,6 +23,7 @@ and their visualization. import numpy as np import matplotlib.pylab as pl import ot + import ot.plot from ot.datasets import get_1D_gauss as gauss @@ -171,11 +172,13 @@ Solve Sinkhorn 110|1.527180e-10| -**Total running time of the script:** ( 0 minutes 1.198 seconds) +**Total running time of the script:** ( 0 minutes 1.061 seconds) -.. container:: sphx-glr-footer +.. only :: html + + .. container:: sphx-glr-footer .. container:: sphx-glr-download @@ -188,6 +191,9 @@ Solve Sinkhorn :download:`Download Jupyter notebook: plot_OT_1D.ipynb ` -.. rst-class:: sphx-glr-signature - `Generated by Sphinx-Gallery `_ +.. only:: html + + .. rst-class:: sphx-glr-signature + + `Gallery generated by Sphinx-Gallery `_ diff --git a/docs/source/auto_examples/plot_OT_L1_vs_L2.ipynb b/docs/source/auto_examples/plot_OT_L1_vs_L2.ipynb index 2b9a364..aea1b3d 100644 --- a/docs/source/auto_examples/plot_OT_L1_vs_L2.ipynb +++ b/docs/source/auto_examples/plot_OT_L1_vs_L2.ipynb @@ -1,126 +1,126 @@ { - "nbformat_minor": 0, - "nbformat": 4, "cells": [ { - "execution_count": null, - "cell_type": "code", - "source": [ - "%matplotlib inline" - ], - "outputs": [], + "execution_count": null, "metadata": { "collapsed": false - } - }, + }, + "outputs": [], + "source": [ + "%matplotlib inline" + ], + "cell_type": "code" + }, { + "metadata": {}, "source": [ "\n# 2D Optimal transport for different metrics\n\n\n2D OT on empirical distributio with different gound metric.\n\nStole the figure idea from Fig. 1 and 2 in\nhttps://arxiv.org/pdf/1706.07650.pdf\n\n\n\n" - ], - "cell_type": "markdown", - "metadata": {} - }, + ], + "cell_type": "markdown" + }, { - "execution_count": null, - "cell_type": "code", - "source": [ - "# Author: Remi Flamary \n#\n# License: MIT License\n\nimport numpy as np\nimport matplotlib.pylab as pl\nimport ot" - ], - "outputs": [], + "execution_count": null, "metadata": { "collapsed": false - } - }, + }, + "outputs": [], + "source": [ + "# Author: Remi Flamary \n#\n# License: MIT License\n\nimport numpy as np\nimport matplotlib.pylab as pl\nimport ot\nimport ot.plot" + ], + "cell_type": "code" + }, { + "metadata": {}, "source": [ "Dataset 1 : uniform sampling\n----------------------------\n\n" - ], - "cell_type": "markdown", - "metadata": {} - }, + ], + "cell_type": "markdown" + }, { - "execution_count": null, - "cell_type": "code", - "source": [ - "n = 20 # nb samples\nxs = np.zeros((n, 2))\nxs[:, 0] = np.arange(n) + 1\nxs[:, 1] = (np.arange(n) + 1) * -0.001 # to make it strictly convex...\n\nxt = np.zeros((n, 2))\nxt[:, 1] = np.arange(n) + 1\n\na, b = ot.unif(n), ot.unif(n) # uniform distribution on samples\n\n# loss matrix\nM1 = ot.dist(xs, xt, metric='euclidean')\nM1 /= M1.max()\n\n# loss matrix\nM2 = ot.dist(xs, xt, metric='sqeuclidean')\nM2 /= M2.max()\n\n# loss matrix\nMp = np.sqrt(ot.dist(xs, xt, metric='euclidean'))\nMp /= Mp.max()\n\n# Data\npl.figure(1, figsize=(7, 3))\npl.clf()\npl.plot(xs[:, 0], xs[:, 1], '+b', label='Source samples')\npl.plot(xt[:, 0], xt[:, 1], 'xr', label='Target samples')\npl.axis('equal')\npl.title('Source and traget distributions')\n\n\n# Cost matrices\npl.figure(2, figsize=(7, 3))\n\npl.subplot(1, 3, 1)\npl.imshow(M1, interpolation='nearest')\npl.title('Euclidean cost')\n\npl.subplot(1, 3, 2)\npl.imshow(M2, interpolation='nearest')\npl.title('Squared Euclidean cost')\n\npl.subplot(1, 3, 3)\npl.imshow(Mp, interpolation='nearest')\npl.title('Sqrt Euclidean cost')\npl.tight_layout()" - ], - "outputs": [], + "execution_count": null, "metadata": { "collapsed": false - } - }, + }, + "outputs": [], + "source": [ + "n = 20 # nb samples\nxs = np.zeros((n, 2))\nxs[:, 0] = np.arange(n) + 1\nxs[:, 1] = (np.arange(n) + 1) * -0.001 # to make it strictly convex...\n\nxt = np.zeros((n, 2))\nxt[:, 1] = np.arange(n) + 1\n\na, b = ot.unif(n), ot.unif(n) # uniform distribution on samples\n\n# loss matrix\nM1 = ot.dist(xs, xt, metric='euclidean')\nM1 /= M1.max()\n\n# loss matrix\nM2 = ot.dist(xs, xt, metric='sqeuclidean')\nM2 /= M2.max()\n\n# loss matrix\nMp = np.sqrt(ot.dist(xs, xt, metric='euclidean'))\nMp /= Mp.max()\n\n# Data\npl.figure(1, figsize=(7, 3))\npl.clf()\npl.plot(xs[:, 0], xs[:, 1], '+b', label='Source samples')\npl.plot(xt[:, 0], xt[:, 1], 'xr', label='Target samples')\npl.axis('equal')\npl.title('Source and traget distributions')\n\n\n# Cost matrices\npl.figure(2, figsize=(7, 3))\n\npl.subplot(1, 3, 1)\npl.imshow(M1, interpolation='nearest')\npl.title('Euclidean cost')\n\npl.subplot(1, 3, 2)\npl.imshow(M2, interpolation='nearest')\npl.title('Squared Euclidean cost')\n\npl.subplot(1, 3, 3)\npl.imshow(Mp, interpolation='nearest')\npl.title('Sqrt Euclidean cost')\npl.tight_layout()" + ], + "cell_type": "code" + }, { + "metadata": {}, "source": [ "Dataset 1 : Plot OT Matrices\n----------------------------\n\n" - ], - "cell_type": "markdown", - "metadata": {} - }, + ], + "cell_type": "markdown" + }, { - "execution_count": null, - "cell_type": "code", - "source": [ - "#%% EMD\nG1 = ot.emd(a, b, M1)\nG2 = ot.emd(a, b, M2)\nGp = ot.emd(a, b, Mp)\n\n# OT matrices\npl.figure(3, figsize=(7, 3))\n\npl.subplot(1, 3, 1)\not.plot.plot2D_samples_mat(xs, xt, G1, c=[.5, .5, 1])\npl.plot(xs[:, 0], xs[:, 1], '+b', label='Source samples')\npl.plot(xt[:, 0], xt[:, 1], 'xr', label='Target samples')\npl.axis('equal')\n# pl.legend(loc=0)\npl.title('OT Euclidean')\n\npl.subplot(1, 3, 2)\not.plot.plot2D_samples_mat(xs, xt, G2, c=[.5, .5, 1])\npl.plot(xs[:, 0], xs[:, 1], '+b', label='Source samples')\npl.plot(xt[:, 0], xt[:, 1], 'xr', label='Target samples')\npl.axis('equal')\n# pl.legend(loc=0)\npl.title('OT squared Euclidean')\n\npl.subplot(1, 3, 3)\not.plot.plot2D_samples_mat(xs, xt, Gp, c=[.5, .5, 1])\npl.plot(xs[:, 0], xs[:, 1], '+b', label='Source samples')\npl.plot(xt[:, 0], xt[:, 1], 'xr', label='Target samples')\npl.axis('equal')\n# pl.legend(loc=0)\npl.title('OT sqrt Euclidean')\npl.tight_layout()\n\npl.show()" - ], - "outputs": [], + "execution_count": null, "metadata": { "collapsed": false - } - }, + }, + "outputs": [], + "source": [ + "#%% EMD\nG1 = ot.emd(a, b, M1)\nG2 = ot.emd(a, b, M2)\nGp = ot.emd(a, b, Mp)\n\n# OT matrices\npl.figure(3, figsize=(7, 3))\n\npl.subplot(1, 3, 1)\not.plot.plot2D_samples_mat(xs, xt, G1, c=[.5, .5, 1])\npl.plot(xs[:, 0], xs[:, 1], '+b', label='Source samples')\npl.plot(xt[:, 0], xt[:, 1], 'xr', label='Target samples')\npl.axis('equal')\n# pl.legend(loc=0)\npl.title('OT Euclidean')\n\npl.subplot(1, 3, 2)\not.plot.plot2D_samples_mat(xs, xt, G2, c=[.5, .5, 1])\npl.plot(xs[:, 0], xs[:, 1], '+b', label='Source samples')\npl.plot(xt[:, 0], xt[:, 1], 'xr', label='Target samples')\npl.axis('equal')\n# pl.legend(loc=0)\npl.title('OT squared Euclidean')\n\npl.subplot(1, 3, 3)\not.plot.plot2D_samples_mat(xs, xt, Gp, c=[.5, .5, 1])\npl.plot(xs[:, 0], xs[:, 1], '+b', label='Source samples')\npl.plot(xt[:, 0], xt[:, 1], 'xr', label='Target samples')\npl.axis('equal')\n# pl.legend(loc=0)\npl.title('OT sqrt Euclidean')\npl.tight_layout()\n\npl.show()" + ], + "cell_type": "code" + }, { + "metadata": {}, "source": [ "Dataset 2 : Partial circle\n--------------------------\n\n" - ], - "cell_type": "markdown", - "metadata": {} - }, + ], + "cell_type": "markdown" + }, { - "execution_count": null, - "cell_type": "code", - "source": [ - "n = 50 # nb samples\nxtot = np.zeros((n + 1, 2))\nxtot[:, 0] = np.cos(\n (np.arange(n + 1) + 1.0) * 0.9 / (n + 2) * 2 * np.pi)\nxtot[:, 1] = np.sin(\n (np.arange(n + 1) + 1.0) * 0.9 / (n + 2) * 2 * np.pi)\n\nxs = xtot[:n, :]\nxt = xtot[1:, :]\n\na, b = ot.unif(n), ot.unif(n) # uniform distribution on samples\n\n# loss matrix\nM1 = ot.dist(xs, xt, metric='euclidean')\nM1 /= M1.max()\n\n# loss matrix\nM2 = ot.dist(xs, xt, metric='sqeuclidean')\nM2 /= M2.max()\n\n# loss matrix\nMp = np.sqrt(ot.dist(xs, xt, metric='euclidean'))\nMp /= Mp.max()\n\n\n# Data\npl.figure(4, figsize=(7, 3))\npl.clf()\npl.plot(xs[:, 0], xs[:, 1], '+b', label='Source samples')\npl.plot(xt[:, 0], xt[:, 1], 'xr', label='Target samples')\npl.axis('equal')\npl.title('Source and traget distributions')\n\n\n# Cost matrices\npl.figure(5, figsize=(7, 3))\n\npl.subplot(1, 3, 1)\npl.imshow(M1, interpolation='nearest')\npl.title('Euclidean cost')\n\npl.subplot(1, 3, 2)\npl.imshow(M2, interpolation='nearest')\npl.title('Squared Euclidean cost')\n\npl.subplot(1, 3, 3)\npl.imshow(Mp, interpolation='nearest')\npl.title('Sqrt Euclidean cost')\npl.tight_layout()" - ], - "outputs": [], + "execution_count": null, "metadata": { "collapsed": false - } - }, + }, + "outputs": [], + "source": [ + "n = 50 # nb samples\nxtot = np.zeros((n + 1, 2))\nxtot[:, 0] = np.cos(\n (np.arange(n + 1) + 1.0) * 0.9 / (n + 2) * 2 * np.pi)\nxtot[:, 1] = np.sin(\n (np.arange(n + 1) + 1.0) * 0.9 / (n + 2) * 2 * np.pi)\n\nxs = xtot[:n, :]\nxt = xtot[1:, :]\n\na, b = ot.unif(n), ot.unif(n) # uniform distribution on samples\n\n# loss matrix\nM1 = ot.dist(xs, xt, metric='euclidean')\nM1 /= M1.max()\n\n# loss matrix\nM2 = ot.dist(xs, xt, metric='sqeuclidean')\nM2 /= M2.max()\n\n# loss matrix\nMp = np.sqrt(ot.dist(xs, xt, metric='euclidean'))\nMp /= Mp.max()\n\n\n# Data\npl.figure(4, figsize=(7, 3))\npl.clf()\npl.plot(xs[:, 0], xs[:, 1], '+b', label='Source samples')\npl.plot(xt[:, 0], xt[:, 1], 'xr', label='Target samples')\npl.axis('equal')\npl.title('Source and traget distributions')\n\n\n# Cost matrices\npl.figure(5, figsize=(7, 3))\n\npl.subplot(1, 3, 1)\npl.imshow(M1, interpolation='nearest')\npl.title('Euclidean cost')\n\npl.subplot(1, 3, 2)\npl.imshow(M2, interpolation='nearest')\npl.title('Squared Euclidean cost')\n\npl.subplot(1, 3, 3)\npl.imshow(Mp, interpolation='nearest')\npl.title('Sqrt Euclidean cost')\npl.tight_layout()" + ], + "cell_type": "code" + }, { + "metadata": {}, "source": [ "Dataset 2 : Plot OT Matrices\n-----------------------------\n\n" - ], - "cell_type": "markdown", - "metadata": {} - }, + ], + "cell_type": "markdown" + }, { - "execution_count": null, - "cell_type": "code", - "source": [ - "#%% EMD\nG1 = ot.emd(a, b, M1)\nG2 = ot.emd(a, b, M2)\nGp = ot.emd(a, b, Mp)\n\n# OT matrices\npl.figure(6, figsize=(7, 3))\n\npl.subplot(1, 3, 1)\not.plot.plot2D_samples_mat(xs, xt, G1, c=[.5, .5, 1])\npl.plot(xs[:, 0], xs[:, 1], '+b', label='Source samples')\npl.plot(xt[:, 0], xt[:, 1], 'xr', label='Target samples')\npl.axis('equal')\n# pl.legend(loc=0)\npl.title('OT Euclidean')\n\npl.subplot(1, 3, 2)\not.plot.plot2D_samples_mat(xs, xt, G2, c=[.5, .5, 1])\npl.plot(xs[:, 0], xs[:, 1], '+b', label='Source samples')\npl.plot(xt[:, 0], xt[:, 1], 'xr', label='Target samples')\npl.axis('equal')\n# pl.legend(loc=0)\npl.title('OT squared Euclidean')\n\npl.subplot(1, 3, 3)\not.plot.plot2D_samples_mat(xs, xt, Gp, c=[.5, .5, 1])\npl.plot(xs[:, 0], xs[:, 1], '+b', label='Source samples')\npl.plot(xt[:, 0], xt[:, 1], 'xr', label='Target samples')\npl.axis('equal')\n# pl.legend(loc=0)\npl.title('OT sqrt Euclidean')\npl.tight_layout()\n\npl.show()" - ], - "outputs": [], + "execution_count": null, "metadata": { "collapsed": false - } + }, + "outputs": [], + "source": [ + "#%% EMD\nG1 = ot.emd(a, b, M1)\nG2 = ot.emd(a, b, M2)\nGp = ot.emd(a, b, Mp)\n\n# OT matrices\npl.figure(6, figsize=(7, 3))\n\npl.subplot(1, 3, 1)\not.plot.plot2D_samples_mat(xs, xt, G1, c=[.5, .5, 1])\npl.plot(xs[:, 0], xs[:, 1], '+b', label='Source samples')\npl.plot(xt[:, 0], xt[:, 1], 'xr', label='Target samples')\npl.axis('equal')\n# pl.legend(loc=0)\npl.title('OT Euclidean')\n\npl.subplot(1, 3, 2)\not.plot.plot2D_samples_mat(xs, xt, G2, c=[.5, .5, 1])\npl.plot(xs[:, 0], xs[:, 1], '+b', label='Source samples')\npl.plot(xt[:, 0], xt[:, 1], 'xr', label='Target samples')\npl.axis('equal')\n# pl.legend(loc=0)\npl.title('OT squared Euclidean')\n\npl.subplot(1, 3, 3)\not.plot.plot2D_samples_mat(xs, xt, Gp, c=[.5, .5, 1])\npl.plot(xs[:, 0], xs[:, 1], '+b', label='Source samples')\npl.plot(xt[:, 0], xt[:, 1], 'xr', label='Target samples')\npl.axis('equal')\n# pl.legend(loc=0)\npl.title('OT sqrt Euclidean')\npl.tight_layout()\n\npl.show()" + ], + "cell_type": "code" } - ], + ], "metadata": { - "kernelspec": { - "display_name": "Python 2", - "name": "python2", - "language": "python" - }, "language_info": { - "mimetype": "text/x-python", - "nbconvert_exporter": "python", - "name": "python", - "file_extension": ".py", - "version": "2.7.12", - "pygments_lexer": "ipython2", + "name": "python", "codemirror_mode": { - "version": 2, - "name": "ipython" - } + "name": "ipython", + "version": 3 + }, + "nbconvert_exporter": "python", + "version": "3.5.2", + "pygments_lexer": "ipython3", + "file_extension": ".py", + "mimetype": "text/x-python" + }, + "kernelspec": { + "display_name": "Python 3", + "name": "python3", + "language": "python" } - } + }, + "nbformat_minor": 0, + "nbformat": 4 } \ No newline at end of file diff --git a/docs/source/auto_examples/plot_OT_L1_vs_L2.py b/docs/source/auto_examples/plot_OT_L1_vs_L2.py index 090e809..c1ed226 100644 --- a/docs/source/auto_examples/plot_OT_L1_vs_L2.py +++ b/docs/source/auto_examples/plot_OT_L1_vs_L2.py @@ -19,6 +19,7 @@ https://arxiv.org/pdf/1706.07650.pdf import numpy as np import matplotlib.pylab as pl import ot +import ot.plot ############################################################################## # Dataset 1 : uniform sampling diff --git a/docs/source/auto_examples/plot_OT_L1_vs_L2.rst b/docs/source/auto_examples/plot_OT_L1_vs_L2.rst index a569b50..01d6ac2 100644 --- a/docs/source/auto_examples/plot_OT_L1_vs_L2.rst +++ b/docs/source/auto_examples/plot_OT_L1_vs_L2.rst @@ -26,6 +26,7 @@ https://arxiv.org/pdf/1706.07650.pdf import numpy as np import matplotlib.pylab as pl import ot + import ot.plot @@ -290,11 +291,13 @@ Dataset 2 : Plot OT Matrices -**Total running time of the script:** ( 0 minutes 1.976 seconds) +**Total running time of the script:** ( 0 minutes 3.750 seconds) -.. container:: sphx-glr-footer +.. only :: html + + .. container:: sphx-glr-footer .. container:: sphx-glr-download @@ -307,6 +310,9 @@ Dataset 2 : Plot OT Matrices :download:`Download Jupyter notebook: plot_OT_L1_vs_L2.ipynb ` -.. rst-class:: sphx-glr-signature - `Generated by Sphinx-Gallery `_ +.. only:: html + + .. rst-class:: sphx-glr-signature + + `Gallery generated by Sphinx-Gallery `_ diff --git a/docs/source/auto_examples/plot_barycenter_1D.ipynb b/docs/source/auto_examples/plot_barycenter_1D.ipynb index a19e0fd..01e759a 100644 --- a/docs/source/auto_examples/plot_barycenter_1D.ipynb +++ b/docs/source/auto_examples/plot_barycenter_1D.ipynb @@ -1,126 +1,54 @@ { - "nbformat_minor": 0, - "nbformat": 4, "cells": [ { - "execution_count": null, - "cell_type": "code", - "source": [ - "%matplotlib inline" - ], - "outputs": [], - "metadata": { - "collapsed": false - } - }, - { - "source": [ - "\n# 1D Wasserstein barycenter demo\n\n\nThis example illustrates the computation of regularized Wassersyein Barycenter\nas proposed in [3].\n\n\n[3] Benamou, J. D., Carlier, G., Cuturi, M., Nenna, L., & Peyr\u00e9, G. (2015).\nIterative Bregman projections for regularized transportation problems\nSIAM Journal on Scientific Computing, 37(2), A1111-A1138.\n\n\n" - ], - "cell_type": "markdown", - "metadata": {} - }, - { - "execution_count": null, - "cell_type": "code", - "source": [ - "# Author: Remi Flamary \n#\n# License: MIT License\n\nimport numpy as np\nimport matplotlib.pylab as pl\nimport ot\n# necessary for 3d plot even if not used\nfrom mpl_toolkits.mplot3d import Axes3D # noqa\nfrom matplotlib.collections import PolyCollection" - ], - "outputs": [], - "metadata": { - "collapsed": false - } - }, - { - "source": [ - "Generate data\n-------------\n\n" - ], - "cell_type": "markdown", - "metadata": {} - }, - { - "execution_count": null, - "cell_type": "code", - "source": [ - "#%% parameters\n\nn = 100 # nb bins\n\n# bin positions\nx = np.arange(n, dtype=np.float64)\n\n# Gaussian distributions\na1 = ot.datasets.get_1D_gauss(n, m=20, s=5) # m= mean, s= std\na2 = ot.datasets.get_1D_gauss(n, m=60, s=8)\n\n# creating matrix A containing all distributions\nA = np.vstack((a1, a2)).T\nn_distributions = A.shape[1]\n\n# loss matrix + normalization\nM = ot.utils.dist0(n)\nM /= M.max()" - ], - "outputs": [], + "execution_count": null, "metadata": { "collapsed": false - } - }, - { + }, + "outputs": [], "source": [ - "Plot data\n---------\n\n" - ], - "cell_type": "markdown", - "metadata": {} - }, - { - "execution_count": null, - "cell_type": "code", - "source": [ - "#%% plot the distributions\n\npl.figure(1, figsize=(6.4, 3))\nfor i in range(n_distributions):\n pl.plot(x, A[:, i])\npl.title('Distributions')\npl.tight_layout()" - ], - "outputs": [], - "metadata": { - "collapsed": false - } - }, + "%matplotlib inline" + ], + "cell_type": "code" + }, { + "metadata": {}, "source": [ - "Barycenter computation\n----------------------\n\n" - ], - "cell_type": "markdown", - "metadata": {} - }, + "\n# 1D Wasserstein barycenter demo\n\n\nThis example illustrates the computation of regularized Wassersyein Barycenter\nas proposed in [3].\n\n\n[3] Benamou, J. D., Carlier, G., Cuturi, M., Nenna, L., & Peyr\u00e9, G. (2015).\nIterative Bregman projections for regularized transportation problems\nSIAM Journal on Scientific Computing, 37(2), A1111-A1138.\n\n\n" + ], + "cell_type": "markdown" + }, { - "execution_count": null, - "cell_type": "code", - "source": [ - "#%% barycenter computation\n\nalpha = 0.2 # 0<=alpha<=1\nweights = np.array([1 - alpha, alpha])\n\n# l2bary\nbary_l2 = A.dot(weights)\n\n# wasserstein\nreg = 1e-3\nbary_wass = ot.bregman.barycenter(A, M, reg, weights)\n\npl.figure(2)\npl.clf()\npl.subplot(2, 1, 1)\nfor i in range(n_distributions):\n pl.plot(x, A[:, i])\npl.title('Distributions')\n\npl.subplot(2, 1, 2)\npl.plot(x, bary_l2, 'r', label='l2')\npl.plot(x, bary_wass, 'g', label='Wasserstein')\npl.legend()\npl.title('Barycenters')\npl.tight_layout()" - ], - "outputs": [], + "execution_count": null, "metadata": { "collapsed": false - } - }, - { + }, + "outputs": [], "source": [ - "Barycentric interpolation\n-------------------------\n\n" - ], - "cell_type": "markdown", - "metadata": {} - }, - { - "execution_count": null, - "cell_type": "code", - "source": [ - "#%% barycenter interpolation\n\nn_alpha = 11\nalpha_list = np.linspace(0, 1, n_alpha)\n\n\nB_l2 = np.zeros((n, n_alpha))\n\nB_wass = np.copy(B_l2)\n\nfor i in range(0, n_alpha):\n alpha = alpha_list[i]\n weights = np.array([1 - alpha, alpha])\n B_l2[:, i] = A.dot(weights)\n B_wass[:, i] = ot.bregman.barycenter(A, M, reg, weights)\n\n#%% plot interpolation\n\npl.figure(3)\n\ncmap = pl.cm.get_cmap('viridis')\nverts = []\nzs = alpha_list\nfor i, z in enumerate(zs):\n ys = B_l2[:, i]\n verts.append(list(zip(x, ys)))\n\nax = pl.gcf().gca(projection='3d')\n\npoly = PolyCollection(verts, facecolors=[cmap(a) for a in alpha_list])\npoly.set_alpha(0.7)\nax.add_collection3d(poly, zs=zs, zdir='y')\nax.set_xlabel('x')\nax.set_xlim3d(0, n)\nax.set_ylabel('$\\\\alpha$')\nax.set_ylim3d(0, 1)\nax.set_zlabel('')\nax.set_zlim3d(0, B_l2.max() * 1.01)\npl.title('Barycenter interpolation with l2')\npl.tight_layout()\n\npl.figure(4)\ncmap = pl.cm.get_cmap('viridis')\nverts = []\nzs = alpha_list\nfor i, z in enumerate(zs):\n ys = B_wass[:, i]\n verts.append(list(zip(x, ys)))\n\nax = pl.gcf().gca(projection='3d')\n\npoly = PolyCollection(verts, facecolors=[cmap(a) for a in alpha_list])\npoly.set_alpha(0.7)\nax.add_collection3d(poly, zs=zs, zdir='y')\nax.set_xlabel('x')\nax.set_xlim3d(0, n)\nax.set_ylabel('$\\\\alpha$')\nax.set_ylim3d(0, 1)\nax.set_zlabel('')\nax.set_zlim3d(0, B_l2.max() * 1.01)\npl.title('Barycenter interpolation with Wasserstein')\npl.tight_layout()\n\npl.show()" - ], - "outputs": [], - "metadata": { - "collapsed": false - } + "# Author: Remi Flamary \n#\n# License: MIT License\n\nimport numpy as np\nimport matplotlib.pylab as pl\nimport ot\n# necessary for 3d plot even if not used\nfrom mpl_toolkits.mplot3d import Axes3D # noqa\nfrom matplotlib.collections import PolyCollection\n\n#\n# Generate data\n# -------------\n\n#%% parameters\n\nn = 100 # nb bins\n\n# bin positions\nx = np.arange(n, dtype=np.float64)\n\n# Gaussian distributions\na1 = ot.datasets.get_1D_gauss(n, m=20, s=5) # m= mean, s= std\na2 = ot.datasets.get_1D_gauss(n, m=60, s=8)\n\n# creating matrix A containing all distributions\nA = np.vstack((a1, a2)).T\nn_distributions = A.shape[1]\n\n# loss matrix + normalization\nM = ot.utils.dist0(n)\nM /= M.max()\n\n#\n# Plot data\n# ---------\n\n#%% plot the distributions\n\npl.figure(1, figsize=(6.4, 3))\nfor i in range(n_distributions):\n pl.plot(x, A[:, i])\npl.title('Distributions')\npl.tight_layout()\n\n#\n# Barycenter computation\n# ----------------------\n\n#%% barycenter computation\n\nalpha = 0.2 # 0<=alpha<=1\nweights = np.array([1 - alpha, alpha])\n\n# l2bary\nbary_l2 = A.dot(weights)\n\n# wasserstein\nreg = 1e-3\nbary_wass = ot.bregman.barycenter(A, M, reg, weights)\n\npl.figure(2)\npl.clf()\npl.subplot(2, 1, 1)\nfor i in range(n_distributions):\n pl.plot(x, A[:, i])\npl.title('Distributions')\n\npl.subplot(2, 1, 2)\npl.plot(x, bary_l2, 'r', label='l2')\npl.plot(x, bary_wass, 'g', label='Wasserstein')\npl.legend()\npl.title('Barycenters')\npl.tight_layout()\n\n#\n# Barycentric interpolation\n# -------------------------\n\n#%% barycenter interpolation\n\nn_alpha = 11\nalpha_list = np.linspace(0, 1, n_alpha)\n\n\nB_l2 = np.zeros((n, n_alpha))\n\nB_wass = np.copy(B_l2)\n\nfor i in range(0, n_alpha):\n alpha = alpha_list[i]\n weights = np.array([1 - alpha, alpha])\n B_l2[:, i] = A.dot(weights)\n B_wass[:, i] = ot.bregman.barycenter(A, M, reg, weights)\n\n#%% plot interpolation\n\npl.figure(3)\n\ncmap = pl.cm.get_cmap('viridis')\nverts = []\nzs = alpha_list\nfor i, z in enumerate(zs):\n ys = B_l2[:, i]\n verts.append(list(zip(x, ys)))\n\nax = pl.gcf().gca(projection='3d')\n\npoly = PolyCollection(verts, facecolors=[cmap(a) for a in alpha_list])\npoly.set_alpha(0.7)\nax.add_collection3d(poly, zs=zs, zdir='y')\nax.set_xlabel('x')\nax.set_xlim3d(0, n)\nax.set_ylabel('$\\\\alpha$')\nax.set_ylim3d(0, 1)\nax.set_zlabel('')\nax.set_zlim3d(0, B_l2.max() * 1.01)\npl.title('Barycenter interpolation with l2')\npl.tight_layout()\n\npl.figure(4)\ncmap = pl.cm.get_cmap('viridis')\nverts = []\nzs = alpha_list\nfor i, z in enumerate(zs):\n ys = B_wass[:, i]\n verts.append(list(zip(x, ys)))\n\nax = pl.gcf().gca(projection='3d')\n\npoly = PolyCollection(verts, facecolors=[cmap(a) for a in alpha_list])\npoly.set_alpha(0.7)\nax.add_collection3d(poly, zs=zs, zdir='y')\nax.set_xlabel('x')\nax.set_xlim3d(0, n)\nax.set_ylabel('$\\\\alpha$')\nax.set_ylim3d(0, 1)\nax.set_zlabel('')\nax.set_zlim3d(0, B_l2.max() * 1.01)\npl.title('Barycenter interpolation with Wasserstein')\npl.tight_layout()\n\npl.show()" + ], + "cell_type": "code" } - ], + ], "metadata": { - "kernelspec": { - "display_name": "Python 2", - "name": "python2", - "language": "python" - }, "language_info": { - "mimetype": "text/x-python", - "nbconvert_exporter": "python", - "name": "python", - "file_extension": ".py", - "version": "2.7.12", - "pygments_lexer": "ipython2", + "name": "python", "codemirror_mode": { - "version": 2, - "name": "ipython" - } + "name": "ipython", + "version": 3 + }, + "nbconvert_exporter": "python", + "version": "3.5.2", + "pygments_lexer": "ipython3", + "file_extension": ".py", + "mimetype": "text/x-python" + }, + "kernelspec": { + "display_name": "Python 3", + "name": "python3", + "language": "python" } - } + }, + "nbformat_minor": 0, + "nbformat": 4 } \ No newline at end of file diff --git a/docs/source/auto_examples/plot_barycenter_1D.py b/docs/source/auto_examples/plot_barycenter_1D.py index 620936b..ecf640c 100644 --- a/docs/source/auto_examples/plot_barycenter_1D.py +++ b/docs/source/auto_examples/plot_barycenter_1D.py @@ -25,7 +25,7 @@ import ot from mpl_toolkits.mplot3d import Axes3D # noqa from matplotlib.collections import PolyCollection -############################################################################## +# # Generate data # ------------- @@ -48,7 +48,7 @@ n_distributions = A.shape[1] M = ot.utils.dist0(n) M /= M.max() -############################################################################## +# # Plot data # --------- @@ -60,7 +60,7 @@ for i in range(n_distributions): pl.title('Distributions') pl.tight_layout() -############################################################################## +# # Barycenter computation # ---------------------- @@ -90,7 +90,7 @@ pl.legend() pl.title('Barycenters') pl.tight_layout() -############################################################################## +# # Barycentric interpolation # ------------------------- diff --git a/docs/source/auto_examples/plot_barycenter_1D.rst b/docs/source/auto_examples/plot_barycenter_1D.rst index f17f2c2..5b627ca 100644 --- a/docs/source/auto_examples/plot_barycenter_1D.rst +++ b/docs/source/auto_examples/plot_barycenter_1D.rst @@ -18,34 +18,52 @@ SIAM Journal on Scientific Computing, 37(2), A1111-A1138. -.. code-block:: python +.. rst-class:: sphx-glr-horizontal - # Author: Remi Flamary - # - # License: MIT License - import numpy as np - import matplotlib.pylab as pl - import ot - # necessary for 3d plot even if not used - from mpl_toolkits.mplot3d import Axes3D # noqa - from matplotlib.collections import PolyCollection + * + .. image:: /auto_examples/images/sphx_glr_plot_barycenter_1D_001.png + :scale: 47 + * + .. image:: /auto_examples/images/sphx_glr_plot_barycenter_1D_002.png + :scale: 47 + * + .. image:: /auto_examples/images/sphx_glr_plot_barycenter_1D_003.png + :scale: 47 + + * + + .. image:: /auto_examples/images/sphx_glr_plot_barycenter_1D_004.png + :scale: 47 -Generate data -------------- .. code-block:: python + # Author: Remi Flamary + # + # License: MIT License + + import numpy as np + import matplotlib.pylab as pl + import ot + # necessary for 3d plot even if not used + from mpl_toolkits.mplot3d import Axes3D # noqa + from matplotlib.collections import PolyCollection + + # + # Generate data + # ------------- + #%% parameters n = 100 # nb bins @@ -65,19 +83,9 @@ Generate data M = ot.utils.dist0(n) M /= M.max() - - - - - - -Plot data ---------- - - - -.. code-block:: python - + # + # Plot data + # --------- #%% plot the distributions @@ -87,22 +95,9 @@ Plot data pl.title('Distributions') pl.tight_layout() - - - -.. image:: /auto_examples/images/sphx_glr_plot_barycenter_1D_001.png - :align: center - - - - -Barycenter computation ----------------------- - - - -.. code-block:: python - + # + # Barycenter computation + # ---------------------- #%% barycenter computation @@ -130,22 +125,9 @@ Barycenter computation pl.title('Barycenters') pl.tight_layout() - - - -.. image:: /auto_examples/images/sphx_glr_plot_barycenter_1D_003.png - :align: center - - - - -Barycentric interpolation -------------------------- - - - -.. code-block:: python - + # + # Barycentric interpolation + # ------------------------- #%% barycenter interpolation @@ -212,29 +194,13 @@ Barycentric interpolation pl.show() - - -.. rst-class:: sphx-glr-horizontal - - - * - - .. image:: /auto_examples/images/sphx_glr_plot_barycenter_1D_005.png - :scale: 47 - - * - - .. image:: /auto_examples/images/sphx_glr_plot_barycenter_1D_006.png - :scale: 47 +**Total running time of the script:** ( 0 minutes 0.636 seconds) +.. only :: html -**Total running time of the script:** ( 0 minutes 0.814 seconds) - - - -.. container:: sphx-glr-footer + .. container:: sphx-glr-footer .. container:: sphx-glr-download @@ -247,6 +213,9 @@ Barycentric interpolation :download:`Download Jupyter notebook: plot_barycenter_1D.ipynb ` -.. rst-class:: sphx-glr-signature - `Generated by Sphinx-Gallery `_ +.. only:: html + + .. rst-class:: sphx-glr-signature + + `Gallery generated by Sphinx-Gallery `_ diff --git a/docs/source/auto_examples/plot_gromov.ipynb b/docs/source/auto_examples/plot_gromov.ipynb index 865848e..6d6b522 100644 --- a/docs/source/auto_examples/plot_gromov.ipynb +++ b/docs/source/auto_examples/plot_gromov.ipynb @@ -1,126 +1,54 @@ { - "nbformat_minor": 0, - "nbformat": 4, "cells": [ { - "execution_count": null, - "cell_type": "code", - "source": [ - "%matplotlib inline" - ], - "outputs": [], - "metadata": { - "collapsed": false - } - }, - { - "source": [ - "\n# Gromov-Wasserstein example\n\n\nThis example is designed to show how to use the Gromov-Wassertsein distance\ncomputation in POT.\n\n" - ], - "cell_type": "markdown", - "metadata": {} - }, - { - "execution_count": null, - "cell_type": "code", - "source": [ - "# Author: Erwan Vautier \r\n# Nicolas Courty \r\n#\r\n# License: MIT License\r\n\r\nimport scipy as sp\r\nimport numpy as np\r\nimport matplotlib.pylab as pl\r\nfrom mpl_toolkits.mplot3d import Axes3D # noqa\r\nimport ot" - ], - "outputs": [], - "metadata": { - "collapsed": false - } - }, - { - "source": [ - "Sample two Gaussian distributions (2D and 3D)\r\n ---------------------------------------------\r\n\r\n The Gromov-Wasserstein distance allows to compute distances with samples that\r\n do not belong to the same metric space. For demonstration purpose, we sample\r\n two Gaussian distributions in 2- and 3-dimensional spaces.\r\n\n" - ], - "cell_type": "markdown", - "metadata": {} - }, - { - "execution_count": null, - "cell_type": "code", - "source": [ - "n_samples = 30 # nb samples\r\n\r\nmu_s = np.array([0, 0])\r\ncov_s = np.array([[1, 0], [0, 1]])\r\n\r\nmu_t = np.array([4, 4, 4])\r\ncov_t = np.array([[1, 0, 0], [0, 1, 0], [0, 0, 1]])\r\n\r\n\r\nxs = ot.datasets.get_2D_samples_gauss(n_samples, mu_s, cov_s)\r\nP = sp.linalg.sqrtm(cov_t)\r\nxt = np.random.randn(n_samples, 3).dot(P) + mu_t" - ], - "outputs": [], + "execution_count": null, "metadata": { "collapsed": false - } - }, - { + }, + "outputs": [], "source": [ - "Plotting the distributions\r\n--------------------------\r\n\n" - ], - "cell_type": "markdown", - "metadata": {} - }, - { - "execution_count": null, - "cell_type": "code", - "source": [ - "fig = pl.figure()\r\nax1 = fig.add_subplot(121)\r\nax1.plot(xs[:, 0], xs[:, 1], '+b', label='Source samples')\r\nax2 = fig.add_subplot(122, projection='3d')\r\nax2.scatter(xt[:, 0], xt[:, 1], xt[:, 2], color='r')\r\npl.show()" - ], - "outputs": [], - "metadata": { - "collapsed": false - } - }, + "%matplotlib inline" + ], + "cell_type": "code" + }, { + "metadata": {}, "source": [ - "Compute distance kernels, normalize them and then display\r\n---------------------------------------------------------\r\n\n" - ], - "cell_type": "markdown", - "metadata": {} - }, + "\n# Gromov-Wasserstein example\n\n\nThis example is designed to show how to use the Gromov-Wassertsein distance\ncomputation in POT.\n\n" + ], + "cell_type": "markdown" + }, { - "execution_count": null, - "cell_type": "code", - "source": [ - "C1 = sp.spatial.distance.cdist(xs, xs)\r\nC2 = sp.spatial.distance.cdist(xt, xt)\r\n\r\nC1 /= C1.max()\r\nC2 /= C2.max()\r\n\r\npl.figure()\r\npl.subplot(121)\r\npl.imshow(C1)\r\npl.subplot(122)\r\npl.imshow(C2)\r\npl.show()" - ], - "outputs": [], + "execution_count": null, "metadata": { "collapsed": false - } - }, - { + }, + "outputs": [], "source": [ - "Compute Gromov-Wasserstein plans and distance\r\n---------------------------------------------\r\n\n" - ], - "cell_type": "markdown", - "metadata": {} - }, - { - "execution_count": null, - "cell_type": "code", - "source": [ - "p = ot.unif(n_samples)\r\nq = ot.unif(n_samples)\r\n\r\ngw = ot.gromov_wasserstein(C1, C2, p, q, 'square_loss', epsilon=5e-4)\r\ngw_dist = ot.gromov_wasserstein2(C1, C2, p, q, 'square_loss', epsilon=5e-4)\r\n\r\nprint('Gromov-Wasserstein distances between the distribution: ' + str(gw_dist))\r\n\r\npl.figure()\r\npl.imshow(gw, cmap='jet')\r\npl.colorbar()\r\npl.show()" - ], - "outputs": [], - "metadata": { - "collapsed": false - } + "# Author: Erwan Vautier \n# Nicolas Courty \n#\n# License: MIT License\n\nimport scipy as sp\nimport numpy as np\nimport matplotlib.pylab as pl\nfrom mpl_toolkits.mplot3d import Axes3D # noqa\nimport ot\n\n\n#\n# Sample two Gaussian distributions (2D and 3D)\n# ---------------------------------------------\n#\n# The Gromov-Wasserstein distance allows to compute distances with samples that\n# do not belong to the same metric space. For demonstration purpose, we sample\n# two Gaussian distributions in 2- and 3-dimensional spaces.\n\n\nn_samples = 30 # nb samples\n\nmu_s = np.array([0, 0])\ncov_s = np.array([[1, 0], [0, 1]])\n\nmu_t = np.array([4, 4, 4])\ncov_t = np.array([[1, 0, 0], [0, 1, 0], [0, 0, 1]])\n\n\nxs = ot.datasets.get_2D_samples_gauss(n_samples, mu_s, cov_s)\nP = sp.linalg.sqrtm(cov_t)\nxt = np.random.randn(n_samples, 3).dot(P) + mu_t\n\n\n#\n# Plotting the distributions\n# --------------------------\n\n\nfig = pl.figure()\nax1 = fig.add_subplot(121)\nax1.plot(xs[:, 0], xs[:, 1], '+b', label='Source samples')\nax2 = fig.add_subplot(122, projection='3d')\nax2.scatter(xt[:, 0], xt[:, 1], xt[:, 2], color='r')\npl.show()\n\n\n#\n# Compute distance kernels, normalize them and then display\n# ---------------------------------------------------------\n\n\nC1 = sp.spatial.distance.cdist(xs, xs)\nC2 = sp.spatial.distance.cdist(xt, xt)\n\nC1 /= C1.max()\nC2 /= C2.max()\n\npl.figure()\npl.subplot(121)\npl.imshow(C1)\npl.subplot(122)\npl.imshow(C2)\npl.show()\n\n#\n# Compute Gromov-Wasserstein plans and distance\n# ---------------------------------------------\n\np = ot.unif(n_samples)\nq = ot.unif(n_samples)\n\ngw0, log0 = ot.gromov.gromov_wasserstein(\n C1, C2, p, q, 'square_loss', verbose=True, log=True)\n\ngw, log = ot.gromov.entropic_gromov_wasserstein(\n C1, C2, p, q, 'square_loss', epsilon=5e-4, log=True, verbose=True)\n\n\nprint('Gromov-Wasserstein distances: ' + str(log0['gw_dist']))\nprint('Entropic Gromov-Wasserstein distances: ' + str(log['gw_dist']))\n\n\npl.figure(1, (10, 5))\n\npl.subplot(1, 2, 1)\npl.imshow(gw0, cmap='jet')\npl.title('Gromov Wasserstein')\n\npl.subplot(1, 2, 2)\npl.imshow(gw, cmap='jet')\npl.title('Entropic Gromov Wasserstein')\n\npl.show()" + ], + "cell_type": "code" } - ], + ], "metadata": { - "kernelspec": { - "display_name": "Python 2", - "name": "python2", - "language": "python" - }, "language_info": { - "mimetype": "text/x-python", - "nbconvert_exporter": "python", - "name": "python", - "file_extension": ".py", - "version": "2.7.12", - "pygments_lexer": "ipython2", + "name": "python", "codemirror_mode": { - "version": 2, - "name": "ipython" - } + "name": "ipython", + "version": 3 + }, + "nbconvert_exporter": "python", + "version": "3.5.2", + "pygments_lexer": "ipython3", + "file_extension": ".py", + "mimetype": "text/x-python" + }, + "kernelspec": { + "display_name": "Python 3", + "name": "python3", + "language": "python" } - } + }, + "nbformat_minor": 0, + "nbformat": 4 } \ No newline at end of file diff --git a/docs/source/auto_examples/plot_gromov.py b/docs/source/auto_examples/plot_gromov.py index d3f724c..9188da9 100644 --- a/docs/source/auto_examples/plot_gromov.py +++ b/docs/source/auto_examples/plot_gromov.py @@ -20,7 +20,7 @@ from mpl_toolkits.mplot3d import Axes3D # noqa import ot -############################################################################## +# # Sample two Gaussian distributions (2D and 3D) # --------------------------------------------- # @@ -43,7 +43,7 @@ P = sp.linalg.sqrtm(cov_t) xt = np.random.randn(n_samples, 3).dot(P) + mu_t -############################################################################## +# # Plotting the distributions # -------------------------- @@ -56,7 +56,7 @@ ax2.scatter(xt[:, 0], xt[:, 1], xt[:, 2], color='r') pl.show() -############################################################################## +# # Compute distance kernels, normalize them and then display # --------------------------------------------------------- @@ -74,20 +74,32 @@ pl.subplot(122) pl.imshow(C2) pl.show() -############################################################################## +# # Compute Gromov-Wasserstein plans and distance # --------------------------------------------- - p = ot.unif(n_samples) q = ot.unif(n_samples) -gw = ot.gromov_wasserstein(C1, C2, p, q, 'square_loss', epsilon=5e-4) -gw_dist = ot.gromov_wasserstein2(C1, C2, p, q, 'square_loss', epsilon=5e-4) +gw0, log0 = ot.gromov.gromov_wasserstein( + C1, C2, p, q, 'square_loss', verbose=True, log=True) -print('Gromov-Wasserstein distances between the distribution: ' + str(gw_dist)) +gw, log = ot.gromov.entropic_gromov_wasserstein( + C1, C2, p, q, 'square_loss', epsilon=5e-4, log=True, verbose=True) -pl.figure() + +print('Gromov-Wasserstein distances: ' + str(log0['gw_dist'])) +print('Entropic Gromov-Wasserstein distances: ' + str(log['gw_dist'])) + + +pl.figure(1, (10, 5)) + +pl.subplot(1, 2, 1) +pl.imshow(gw0, cmap='jet') +pl.title('Gromov Wasserstein') + +pl.subplot(1, 2, 2) pl.imshow(gw, cmap='jet') -pl.colorbar() +pl.title('Entropic Gromov Wasserstein') + pl.show() diff --git a/docs/source/auto_examples/plot_gromov.rst b/docs/source/auto_examples/plot_gromov.rst index 65cf4e4..ad29f7a 100644 --- a/docs/source/auto_examples/plot_gromov.rst +++ b/docs/source/auto_examples/plot_gromov.rst @@ -12,157 +12,160 @@ computation in POT. -.. code-block:: python - - - # Author: Erwan Vautier - # Nicolas Courty - # - # License: MIT License - - import scipy as sp - import numpy as np - import matplotlib.pylab as pl - from mpl_toolkits.mplot3d import Axes3D # noqa - import ot - - +.. rst-class:: sphx-glr-horizontal + * + .. image:: /auto_examples/images/sphx_glr_plot_gromov_001.png + :scale: 47 + * -Sample two Gaussian distributions (2D and 3D) - --------------------------------------------- - - The Gromov-Wasserstein distance allows to compute distances with samples that - do not belong to the same metric space. For demonstration purpose, we sample - two Gaussian distributions in 2- and 3-dimensional spaces. + .. image:: /auto_examples/images/sphx_glr_plot_gromov_002.png + :scale: 47 +.. rst-class:: sphx-glr-script-out -.. code-block:: python - - - - n_samples = 30 # nb samples - - mu_s = np.array([0, 0]) - cov_s = np.array([[1, 0], [0, 1]]) - - mu_t = np.array([4, 4, 4]) - cov_t = np.array([[1, 0, 0], [0, 1, 0], [0, 0, 1]]) - - - xs = ot.datasets.get_2D_samples_gauss(n_samples, mu_s, cov_s) - P = sp.linalg.sqrtm(cov_t) - xt = np.random.randn(n_samples, 3).dot(P) + mu_t - - + Out:: + It. |Loss |Delta loss + -------------------------------- + 0|4.042674e-02|0.000000e+00 + 1|2.432476e-02|-6.619583e-01 + 2|2.170023e-02|-1.209448e-01 + 3|1.941223e-02|-1.178640e-01 + 4|1.823606e-02|-6.449667e-02 + 5|1.446641e-02|-2.605800e-01 + 6|1.184011e-02|-2.218140e-01 + 7|1.173274e-02|-9.150805e-03 + 8|1.173127e-02|-1.253458e-04 + 9|1.173126e-02|-1.256842e-06 + 10|1.173126e-02|-1.256876e-08 + 11|1.173126e-02|-1.256885e-10 + It. |Err + ------------------- + 0|7.034302e-02| + 10|1.044218e-03| + 20|5.426783e-08| + 30|3.532029e-12| + Gromov-Wasserstein distances: 0.0117312557987 + Entropic Gromov-Wasserstein distances: 0.0101639418389 +| -Plotting the distributions --------------------------- +.. code-block:: python -.. code-block:: python + # Author: Erwan Vautier + # Nicolas Courty + # + # License: MIT License - - - fig = pl.figure() - ax1 = fig.add_subplot(121) - ax1.plot(xs[:, 0], xs[:, 1], '+b', label='Source samples') - ax2 = fig.add_subplot(122, projection='3d') - ax2.scatter(xt[:, 0], xt[:, 1], xt[:, 2], color='r') - pl.show() - - + import scipy as sp + import numpy as np + import matplotlib.pylab as pl + from mpl_toolkits.mplot3d import Axes3D # noqa + import ot + # + # Sample two Gaussian distributions (2D and 3D) + # --------------------------------------------- + # + # The Gromov-Wasserstein distance allows to compute distances with samples that + # do not belong to the same metric space. For demonstration purpose, we sample + # two Gaussian distributions in 2- and 3-dimensional spaces. -.. image:: /auto_examples/images/sphx_glr_plot_gromov_001.png - :align: center + n_samples = 30 # nb samples + mu_s = np.array([0, 0]) + cov_s = np.array([[1, 0], [0, 1]]) + mu_t = np.array([4, 4, 4]) + cov_t = np.array([[1, 0, 0], [0, 1, 0], [0, 0, 1]]) -Compute distance kernels, normalize them and then display ---------------------------------------------------------- + xs = ot.datasets.get_2D_samples_gauss(n_samples, mu_s, cov_s) + P = sp.linalg.sqrtm(cov_t) + xt = np.random.randn(n_samples, 3).dot(P) + mu_t -.. code-block:: python + # + # Plotting the distributions + # -------------------------- - - - C1 = sp.spatial.distance.cdist(xs, xs) - C2 = sp.spatial.distance.cdist(xt, xt) - - C1 /= C1.max() - C2 /= C2.max() - - pl.figure() - pl.subplot(121) - pl.imshow(C1) - pl.subplot(122) - pl.imshow(C2) - pl.show() - + fig = pl.figure() + ax1 = fig.add_subplot(121) + ax1.plot(xs[:, 0], xs[:, 1], '+b', label='Source samples') + ax2 = fig.add_subplot(122, projection='3d') + ax2.scatter(xt[:, 0], xt[:, 1], xt[:, 2], color='r') + pl.show() -.. image:: /auto_examples/images/sphx_glr_plot_gromov_002.png - :align: center + # + # Compute distance kernels, normalize them and then display + # --------------------------------------------------------- + C1 = sp.spatial.distance.cdist(xs, xs) + C2 = sp.spatial.distance.cdist(xt, xt) + C1 /= C1.max() + C2 /= C2.max() -Compute Gromov-Wasserstein plans and distance ---------------------------------------------- + pl.figure() + pl.subplot(121) + pl.imshow(C1) + pl.subplot(122) + pl.imshow(C2) + pl.show() + # + # Compute Gromov-Wasserstein plans and distance + # --------------------------------------------- + p = ot.unif(n_samples) + q = ot.unif(n_samples) -.. code-block:: python + gw0, log0 = ot.gromov.gromov_wasserstein( + C1, C2, p, q, 'square_loss', verbose=True, log=True) - - - p = ot.unif(n_samples) - q = ot.unif(n_samples) - - gw = ot.gromov_wasserstein(C1, C2, p, q, 'square_loss', epsilon=5e-4) - gw_dist = ot.gromov_wasserstein2(C1, C2, p, q, 'square_loss', epsilon=5e-4) - - print('Gromov-Wasserstein distances between the distribution: ' + str(gw_dist)) - - pl.figure() - pl.imshow(gw, cmap='jet') - pl.colorbar() - pl.show() + gw, log = ot.gromov.entropic_gromov_wasserstein( + C1, C2, p, q, 'square_loss', epsilon=5e-4, log=True, verbose=True) + print('Gromov-Wasserstein distances: ' + str(log0['gw_dist'])) + print('Entropic Gromov-Wasserstein distances: ' + str(log['gw_dist'])) -.. image:: /auto_examples/images/sphx_glr_plot_gromov_003.png - :align: center + pl.figure(1, (10, 5)) -.. rst-class:: sphx-glr-script-out + pl.subplot(1, 2, 1) + pl.imshow(gw0, cmap='jet') + pl.title('Gromov Wasserstein') - Out:: + pl.subplot(1, 2, 2) + pl.imshow(gw, cmap='jet') + pl.title('Entropic Gromov Wasserstein') - Gromov-Wasserstein distances between the distribution: 0.225058076974 + pl.show() +**Total running time of the script:** ( 0 minutes 1.465 seconds) -**Total running time of the script:** ( 0 minutes 4.070 seconds) +.. only :: html -.. container:: sphx-glr-footer + .. container:: sphx-glr-footer .. container:: sphx-glr-download @@ -175,6 +178,9 @@ Compute Gromov-Wasserstein plans and distance :download:`Download Jupyter notebook: plot_gromov.ipynb ` -.. rst-class:: sphx-glr-signature - `Generated by Sphinx-Gallery `_ +.. only:: html + + .. rst-class:: sphx-glr-signature + + `Gallery generated by Sphinx-Gallery `_ diff --git a/docs/source/auto_examples/plot_gromov_barycenter.ipynb b/docs/source/auto_examples/plot_gromov_barycenter.ipynb index d38dfbb..4c2f28f 100644 --- a/docs/source/auto_examples/plot_gromov_barycenter.ipynb +++ b/docs/source/auto_examples/plot_gromov_barycenter.ipynb @@ -1,126 +1,126 @@ { - "nbformat_minor": 0, - "nbformat": 4, "cells": [ { - "execution_count": null, - "cell_type": "code", - "source": [ - "%matplotlib inline" - ], - "outputs": [], + "execution_count": null, "metadata": { "collapsed": false - } - }, + }, + "outputs": [], + "source": [ + "%matplotlib inline" + ], + "cell_type": "code" + }, { + "metadata": {}, "source": [ "\n# Gromov-Wasserstein Barycenter example\n\n\nThis example is designed to show how to use the Gromov-Wasserstein distance\ncomputation in POT.\n\n" - ], - "cell_type": "markdown", - "metadata": {} - }, + ], + "cell_type": "markdown" + }, { - "execution_count": null, - "cell_type": "code", - "source": [ - "# Author: Erwan Vautier \r\n# Nicolas Courty \r\n#\r\n# License: MIT License\r\n\r\n\r\nimport numpy as np\r\nimport scipy as sp\r\n\r\nimport scipy.ndimage as spi\r\nimport matplotlib.pylab as pl\r\nfrom sklearn import manifold\r\nfrom sklearn.decomposition import PCA\r\n\r\nimport ot" - ], - "outputs": [], + "execution_count": null, "metadata": { "collapsed": false - } - }, - { + }, + "outputs": [], "source": [ - "Smacof MDS\r\n ----------\r\n\r\n This function allows to find an embedding of points given a dissimilarity matrix\r\n that will be given by the output of the algorithm\r\n\n" - ], - "cell_type": "markdown", - "metadata": {} - }, + "# Author: Erwan Vautier \n# Nicolas Courty \n#\n# License: MIT License\n\n\nimport numpy as np\nimport scipy as sp\n\nimport scipy.ndimage as spi\nimport matplotlib.pylab as pl\nfrom sklearn import manifold\nfrom sklearn.decomposition import PCA\n\nimport ot" + ], + "cell_type": "code" + }, { - "execution_count": null, - "cell_type": "code", + "metadata": {}, "source": [ - "def smacof_mds(C, dim, max_iter=3000, eps=1e-9):\r\n \"\"\"\r\n Returns an interpolated point cloud following the dissimilarity matrix C\r\n using SMACOF multidimensional scaling (MDS) in specific dimensionned\r\n target space\r\n\r\n Parameters\r\n ----------\r\n C : ndarray, shape (ns, ns)\r\n dissimilarity matrix\r\n dim : int\r\n dimension of the targeted space\r\n max_iter : int\r\n Maximum number of iterations of the SMACOF algorithm for a single run\r\n eps : float\r\n relative tolerance w.r.t stress to declare converge\r\n\r\n Returns\r\n -------\r\n npos : ndarray, shape (R, dim)\r\n Embedded coordinates of the interpolated point cloud (defined with\r\n one isometry)\r\n \"\"\"\r\n\r\n rng = np.random.RandomState(seed=3)\r\n\r\n mds = manifold.MDS(\r\n dim,\r\n max_iter=max_iter,\r\n eps=1e-9,\r\n dissimilarity='precomputed',\r\n n_init=1)\r\n pos = mds.fit(C).embedding_\r\n\r\n nmds = manifold.MDS(\r\n 2,\r\n max_iter=max_iter,\r\n eps=1e-9,\r\n dissimilarity=\"precomputed\",\r\n random_state=rng,\r\n n_init=1)\r\n npos = nmds.fit_transform(C, init=pos)\r\n\r\n return npos" - ], - "outputs": [], + "Smacof MDS\n----------\n\nThis function allows to find an embedding of points given a dissimilarity matrix\nthat will be given by the output of the algorithm\n\n" + ], + "cell_type": "markdown" + }, + { + "execution_count": null, "metadata": { "collapsed": false - } - }, - { + }, + "outputs": [], "source": [ - "Data preparation\r\n ----------------\r\n\r\n The four distributions are constructed from 4 simple images\r\n\n" - ], - "cell_type": "markdown", - "metadata": {} - }, + "def smacof_mds(C, dim, max_iter=3000, eps=1e-9):\n \"\"\"\n Returns an interpolated point cloud following the dissimilarity matrix C\n using SMACOF multidimensional scaling (MDS) in specific dimensionned\n target space\n\n Parameters\n ----------\n C : ndarray, shape (ns, ns)\n dissimilarity matrix\n dim : int\n dimension of the targeted space\n max_iter : int\n Maximum number of iterations of the SMACOF algorithm for a single run\n eps : float\n relative tolerance w.r.t stress to declare converge\n\n Returns\n -------\n npos : ndarray, shape (R, dim)\n Embedded coordinates of the interpolated point cloud (defined with\n one isometry)\n \"\"\"\n\n rng = np.random.RandomState(seed=3)\n\n mds = manifold.MDS(\n dim,\n max_iter=max_iter,\n eps=1e-9,\n dissimilarity='precomputed',\n n_init=1)\n pos = mds.fit(C).embedding_\n\n nmds = manifold.MDS(\n 2,\n max_iter=max_iter,\n eps=1e-9,\n dissimilarity=\"precomputed\",\n random_state=rng,\n n_init=1)\n npos = nmds.fit_transform(C, init=pos)\n\n return npos" + ], + "cell_type": "code" + }, { - "execution_count": null, - "cell_type": "code", + "metadata": {}, "source": [ - "def im2mat(I):\r\n \"\"\"Converts and image to matrix (one pixel per line)\"\"\"\r\n return I.reshape((I.shape[0] * I.shape[1], I.shape[2]))\r\n\r\n\r\nsquare = spi.imread('../data/square.png').astype(np.float64)[:, :, 2] / 256\r\ncross = spi.imread('../data/cross.png').astype(np.float64)[:, :, 2] / 256\r\ntriangle = spi.imread('../data/triangle.png').astype(np.float64)[:, :, 2] / 256\r\nstar = spi.imread('../data/star.png').astype(np.float64)[:, :, 2] / 256\r\n\r\nshapes = [square, cross, triangle, star]\r\n\r\nS = 4\r\nxs = [[] for i in range(S)]\r\n\r\n\r\nfor nb in range(4):\r\n for i in range(8):\r\n for j in range(8):\r\n if shapes[nb][i, j] < 0.95:\r\n xs[nb].append([j, 8 - i])\r\n\r\nxs = np.array([np.array(xs[0]), np.array(xs[1]),\r\n np.array(xs[2]), np.array(xs[3])])" - ], - "outputs": [], + "Data preparation\n----------------\n\nThe four distributions are constructed from 4 simple images\n\n" + ], + "cell_type": "markdown" + }, + { + "execution_count": null, "metadata": { "collapsed": false - } - }, - { + }, + "outputs": [], "source": [ - "Barycenter computation\r\n----------------------\r\n\n" - ], - "cell_type": "markdown", - "metadata": {} - }, + "def im2mat(I):\n \"\"\"Converts and image to matrix (one pixel per line)\"\"\"\n return I.reshape((I.shape[0] * I.shape[1], I.shape[2]))\n\n\nsquare = spi.imread('../data/square.png').astype(np.float64)[:, :, 2] / 256\ncross = spi.imread('../data/cross.png').astype(np.float64)[:, :, 2] / 256\ntriangle = spi.imread('../data/triangle.png').astype(np.float64)[:, :, 2] / 256\nstar = spi.imread('../data/star.png').astype(np.float64)[:, :, 2] / 256\n\nshapes = [square, cross, triangle, star]\n\nS = 4\nxs = [[] for i in range(S)]\n\n\nfor nb in range(4):\n for i in range(8):\n for j in range(8):\n if shapes[nb][i, j] < 0.95:\n xs[nb].append([j, 8 - i])\n\nxs = np.array([np.array(xs[0]), np.array(xs[1]),\n np.array(xs[2]), np.array(xs[3])])" + ], + "cell_type": "code" + }, { - "execution_count": null, - "cell_type": "code", + "metadata": {}, "source": [ - "ns = [len(xs[s]) for s in range(S)]\r\nn_samples = 30\r\n\r\n\"\"\"Compute all distances matrices for the four shapes\"\"\"\r\nCs = [sp.spatial.distance.cdist(xs[s], xs[s]) for s in range(S)]\r\nCs = [cs / cs.max() for cs in Cs]\r\n\r\nps = [ot.unif(ns[s]) for s in range(S)]\r\np = ot.unif(n_samples)\r\n\r\n\r\nlambdast = [[float(i) / 3, float(3 - i) / 3] for i in [1, 2]]\r\n\r\nCt01 = [0 for i in range(2)]\r\nfor i in range(2):\r\n Ct01[i] = ot.gromov.gromov_barycenters(n_samples, [Cs[0], Cs[1]],\r\n [ps[0], ps[1]\r\n ], p, lambdast[i], 'square_loss', 5e-4,\r\n max_iter=100, tol=1e-3)\r\n\r\nCt02 = [0 for i in range(2)]\r\nfor i in range(2):\r\n Ct02[i] = ot.gromov.gromov_barycenters(n_samples, [Cs[0], Cs[2]],\r\n [ps[0], ps[2]\r\n ], p, lambdast[i], 'square_loss', 5e-4,\r\n max_iter=100, tol=1e-3)\r\n\r\nCt13 = [0 for i in range(2)]\r\nfor i in range(2):\r\n Ct13[i] = ot.gromov.gromov_barycenters(n_samples, [Cs[1], Cs[3]],\r\n [ps[1], ps[3]\r\n ], p, lambdast[i], 'square_loss', 5e-4,\r\n max_iter=100, tol=1e-3)\r\n\r\nCt23 = [0 for i in range(2)]\r\nfor i in range(2):\r\n Ct23[i] = ot.gromov.gromov_barycenters(n_samples, [Cs[2], Cs[3]],\r\n [ps[2], ps[3]\r\n ], p, lambdast[i], 'square_loss', 5e-4,\r\n max_iter=100, tol=1e-3)" - ], - "outputs": [], + "Barycenter computation\n----------------------\n\n" + ], + "cell_type": "markdown" + }, + { + "execution_count": null, "metadata": { "collapsed": false - } - }, - { + }, + "outputs": [], "source": [ - "Visualization\r\n -------------\r\n\r\n The PCA helps in getting consistency between the rotations\r\n\n" - ], - "cell_type": "markdown", - "metadata": {} - }, + "ns = [len(xs[s]) for s in range(S)]\nn_samples = 30\n\n\"\"\"Compute all distances matrices for the four shapes\"\"\"\nCs = [sp.spatial.distance.cdist(xs[s], xs[s]) for s in range(S)]\nCs = [cs / cs.max() for cs in Cs]\n\nps = [ot.unif(ns[s]) for s in range(S)]\np = ot.unif(n_samples)\n\n\nlambdast = [[float(i) / 3, float(3 - i) / 3] for i in [1, 2]]\n\nCt01 = [0 for i in range(2)]\nfor i in range(2):\n Ct01[i] = ot.gromov.gromov_barycenters(n_samples, [Cs[0], Cs[1]],\n [ps[0], ps[1]\n ], p, lambdast[i], 'square_loss', # 5e-4,\n max_iter=100, tol=1e-3)\n\nCt02 = [0 for i in range(2)]\nfor i in range(2):\n Ct02[i] = ot.gromov.gromov_barycenters(n_samples, [Cs[0], Cs[2]],\n [ps[0], ps[2]\n ], p, lambdast[i], 'square_loss', # 5e-4,\n max_iter=100, tol=1e-3)\n\nCt13 = [0 for i in range(2)]\nfor i in range(2):\n Ct13[i] = ot.gromov.gromov_barycenters(n_samples, [Cs[1], Cs[3]],\n [ps[1], ps[3]\n ], p, lambdast[i], 'square_loss', # 5e-4,\n max_iter=100, tol=1e-3)\n\nCt23 = [0 for i in range(2)]\nfor i in range(2):\n Ct23[i] = ot.gromov.gromov_barycenters(n_samples, [Cs[2], Cs[3]],\n [ps[2], ps[3]\n ], p, lambdast[i], 'square_loss', # 5e-4,\n max_iter=100, tol=1e-3)" + ], + "cell_type": "code" + }, { - "execution_count": null, - "cell_type": "code", + "metadata": {}, "source": [ - "clf = PCA(n_components=2)\r\nnpos = [0, 0, 0, 0]\r\nnpos = [smacof_mds(Cs[s], 2) for s in range(S)]\r\n\r\nnpost01 = [0, 0]\r\nnpost01 = [smacof_mds(Ct01[s], 2) for s in range(2)]\r\nnpost01 = [clf.fit_transform(npost01[s]) for s in range(2)]\r\n\r\nnpost02 = [0, 0]\r\nnpost02 = [smacof_mds(Ct02[s], 2) for s in range(2)]\r\nnpost02 = [clf.fit_transform(npost02[s]) for s in range(2)]\r\n\r\nnpost13 = [0, 0]\r\nnpost13 = [smacof_mds(Ct13[s], 2) for s in range(2)]\r\nnpost13 = [clf.fit_transform(npost13[s]) for s in range(2)]\r\n\r\nnpost23 = [0, 0]\r\nnpost23 = [smacof_mds(Ct23[s], 2) for s in range(2)]\r\nnpost23 = [clf.fit_transform(npost23[s]) for s in range(2)]\r\n\r\n\r\nfig = pl.figure(figsize=(10, 10))\r\n\r\nax1 = pl.subplot2grid((4, 4), (0, 0))\r\npl.xlim((-1, 1))\r\npl.ylim((-1, 1))\r\nax1.scatter(npos[0][:, 0], npos[0][:, 1], color='r')\r\n\r\nax2 = pl.subplot2grid((4, 4), (0, 1))\r\npl.xlim((-1, 1))\r\npl.ylim((-1, 1))\r\nax2.scatter(npost01[1][:, 0], npost01[1][:, 1], color='b')\r\n\r\nax3 = pl.subplot2grid((4, 4), (0, 2))\r\npl.xlim((-1, 1))\r\npl.ylim((-1, 1))\r\nax3.scatter(npost01[0][:, 0], npost01[0][:, 1], color='b')\r\n\r\nax4 = pl.subplot2grid((4, 4), (0, 3))\r\npl.xlim((-1, 1))\r\npl.ylim((-1, 1))\r\nax4.scatter(npos[1][:, 0], npos[1][:, 1], color='r')\r\n\r\nax5 = pl.subplot2grid((4, 4), (1, 0))\r\npl.xlim((-1, 1))\r\npl.ylim((-1, 1))\r\nax5.scatter(npost02[1][:, 0], npost02[1][:, 1], color='b')\r\n\r\nax6 = pl.subplot2grid((4, 4), (1, 3))\r\npl.xlim((-1, 1))\r\npl.ylim((-1, 1))\r\nax6.scatter(npost13[1][:, 0], npost13[1][:, 1], color='b')\r\n\r\nax7 = pl.subplot2grid((4, 4), (2, 0))\r\npl.xlim((-1, 1))\r\npl.ylim((-1, 1))\r\nax7.scatter(npost02[0][:, 0], npost02[0][:, 1], color='b')\r\n\r\nax8 = pl.subplot2grid((4, 4), (2, 3))\r\npl.xlim((-1, 1))\r\npl.ylim((-1, 1))\r\nax8.scatter(npost13[0][:, 0], npost13[0][:, 1], color='b')\r\n\r\nax9 = pl.subplot2grid((4, 4), (3, 0))\r\npl.xlim((-1, 1))\r\npl.ylim((-1, 1))\r\nax9.scatter(npos[2][:, 0], npos[2][:, 1], color='r')\r\n\r\nax10 = pl.subplot2grid((4, 4), (3, 1))\r\npl.xlim((-1, 1))\r\npl.ylim((-1, 1))\r\nax10.scatter(npost23[1][:, 0], npost23[1][:, 1], color='b')\r\n\r\nax11 = pl.subplot2grid((4, 4), (3, 2))\r\npl.xlim((-1, 1))\r\npl.ylim((-1, 1))\r\nax11.scatter(npost23[0][:, 0], npost23[0][:, 1], color='b')\r\n\r\nax12 = pl.subplot2grid((4, 4), (3, 3))\r\npl.xlim((-1, 1))\r\npl.ylim((-1, 1))\r\nax12.scatter(npos[3][:, 0], npos[3][:, 1], color='r')" - ], - "outputs": [], + "Visualization\n-------------\n\nThe PCA helps in getting consistency between the rotations\n\n" + ], + "cell_type": "markdown" + }, + { + "execution_count": null, "metadata": { "collapsed": false - } + }, + "outputs": [], + "source": [ + "clf = PCA(n_components=2)\nnpos = [0, 0, 0, 0]\nnpos = [smacof_mds(Cs[s], 2) for s in range(S)]\n\nnpost01 = [0, 0]\nnpost01 = [smacof_mds(Ct01[s], 2) for s in range(2)]\nnpost01 = [clf.fit_transform(npost01[s]) for s in range(2)]\n\nnpost02 = [0, 0]\nnpost02 = [smacof_mds(Ct02[s], 2) for s in range(2)]\nnpost02 = [clf.fit_transform(npost02[s]) for s in range(2)]\n\nnpost13 = [0, 0]\nnpost13 = [smacof_mds(Ct13[s], 2) for s in range(2)]\nnpost13 = [clf.fit_transform(npost13[s]) for s in range(2)]\n\nnpost23 = [0, 0]\nnpost23 = [smacof_mds(Ct23[s], 2) for s in range(2)]\nnpost23 = [clf.fit_transform(npost23[s]) for s in range(2)]\n\n\nfig = pl.figure(figsize=(10, 10))\n\nax1 = pl.subplot2grid((4, 4), (0, 0))\npl.xlim((-1, 1))\npl.ylim((-1, 1))\nax1.scatter(npos[0][:, 0], npos[0][:, 1], color='r')\n\nax2 = pl.subplot2grid((4, 4), (0, 1))\npl.xlim((-1, 1))\npl.ylim((-1, 1))\nax2.scatter(npost01[1][:, 0], npost01[1][:, 1], color='b')\n\nax3 = pl.subplot2grid((4, 4), (0, 2))\npl.xlim((-1, 1))\npl.ylim((-1, 1))\nax3.scatter(npost01[0][:, 0], npost01[0][:, 1], color='b')\n\nax4 = pl.subplot2grid((4, 4), (0, 3))\npl.xlim((-1, 1))\npl.ylim((-1, 1))\nax4.scatter(npos[1][:, 0], npos[1][:, 1], color='r')\n\nax5 = pl.subplot2grid((4, 4), (1, 0))\npl.xlim((-1, 1))\npl.ylim((-1, 1))\nax5.scatter(npost02[1][:, 0], npost02[1][:, 1], color='b')\n\nax6 = pl.subplot2grid((4, 4), (1, 3))\npl.xlim((-1, 1))\npl.ylim((-1, 1))\nax6.scatter(npost13[1][:, 0], npost13[1][:, 1], color='b')\n\nax7 = pl.subplot2grid((4, 4), (2, 0))\npl.xlim((-1, 1))\npl.ylim((-1, 1))\nax7.scatter(npost02[0][:, 0], npost02[0][:, 1], color='b')\n\nax8 = pl.subplot2grid((4, 4), (2, 3))\npl.xlim((-1, 1))\npl.ylim((-1, 1))\nax8.scatter(npost13[0][:, 0], npost13[0][:, 1], color='b')\n\nax9 = pl.subplot2grid((4, 4), (3, 0))\npl.xlim((-1, 1))\npl.ylim((-1, 1))\nax9.scatter(npos[2][:, 0], npos[2][:, 1], color='r')\n\nax10 = pl.subplot2grid((4, 4), (3, 1))\npl.xlim((-1, 1))\npl.ylim((-1, 1))\nax10.scatter(npost23[1][:, 0], npost23[1][:, 1], color='b')\n\nax11 = pl.subplot2grid((4, 4), (3, 2))\npl.xlim((-1, 1))\npl.ylim((-1, 1))\nax11.scatter(npost23[0][:, 0], npost23[0][:, 1], color='b')\n\nax12 = pl.subplot2grid((4, 4), (3, 3))\npl.xlim((-1, 1))\npl.ylim((-1, 1))\nax12.scatter(npos[3][:, 0], npos[3][:, 1], color='r')" + ], + "cell_type": "code" } - ], + ], "metadata": { - "kernelspec": { - "display_name": "Python 2", - "name": "python2", - "language": "python" - }, "language_info": { - "mimetype": "text/x-python", - "nbconvert_exporter": "python", - "name": "python", - "file_extension": ".py", - "version": "2.7.12", - "pygments_lexer": "ipython2", + "name": "python", "codemirror_mode": { - "version": 2, - "name": "ipython" - } + "name": "ipython", + "version": 3 + }, + "nbconvert_exporter": "python", + "version": "3.5.2", + "pygments_lexer": "ipython3", + "file_extension": ".py", + "mimetype": "text/x-python" + }, + "kernelspec": { + "display_name": "Python 3", + "name": "python3", + "language": "python" } - } + }, + "nbformat_minor": 0, + "nbformat": 4 } \ No newline at end of file diff --git a/docs/source/auto_examples/plot_gromov_barycenter.py b/docs/source/auto_examples/plot_gromov_barycenter.py index 180b0cf..58fc51a 100644 --- a/docs/source/auto_examples/plot_gromov_barycenter.py +++ b/docs/source/auto_examples/plot_gromov_barycenter.py @@ -132,28 +132,28 @@ Ct01 = [0 for i in range(2)] for i in range(2): Ct01[i] = ot.gromov.gromov_barycenters(n_samples, [Cs[0], Cs[1]], [ps[0], ps[1] - ], p, lambdast[i], 'square_loss', 5e-4, + ], p, lambdast[i], 'square_loss', # 5e-4, max_iter=100, tol=1e-3) Ct02 = [0 for i in range(2)] for i in range(2): Ct02[i] = ot.gromov.gromov_barycenters(n_samples, [Cs[0], Cs[2]], [ps[0], ps[2] - ], p, lambdast[i], 'square_loss', 5e-4, + ], p, lambdast[i], 'square_loss', # 5e-4, max_iter=100, tol=1e-3) Ct13 = [0 for i in range(2)] for i in range(2): Ct13[i] = ot.gromov.gromov_barycenters(n_samples, [Cs[1], Cs[3]], [ps[1], ps[3] - ], p, lambdast[i], 'square_loss', 5e-4, + ], p, lambdast[i], 'square_loss', # 5e-4, max_iter=100, tol=1e-3) Ct23 = [0 for i in range(2)] for i in range(2): Ct23[i] = ot.gromov.gromov_barycenters(n_samples, [Cs[2], Cs[3]], [ps[2], ps[3] - ], p, lambdast[i], 'square_loss', 5e-4, + ], p, lambdast[i], 'square_loss', # 5e-4, max_iter=100, tol=1e-3) diff --git a/docs/source/auto_examples/plot_gromov_barycenter.rst b/docs/source/auto_examples/plot_gromov_barycenter.rst index ca2d4e9..531ee22 100644 --- a/docs/source/auto_examples/plot_gromov_barycenter.rst +++ b/docs/source/auto_examples/plot_gromov_barycenter.rst @@ -14,285 +14,285 @@ computation in POT. .. code-block:: python - - # Author: Erwan Vautier - # Nicolas Courty - # - # License: MIT License - - - import numpy as np - import scipy as sp - - import scipy.ndimage as spi - import matplotlib.pylab as pl - from sklearn import manifold - from sklearn.decomposition import PCA - - import ot - + # Author: Erwan Vautier + # Nicolas Courty + # + # License: MIT License + import numpy as np + import scipy as sp + import scipy.ndimage as spi + import matplotlib.pylab as pl + from sklearn import manifold + from sklearn.decomposition import PCA + import ot -Smacof MDS - ---------- - - This function allows to find an embedding of points given a dissimilarity matrix - that will be given by the output of the algorithm + + + + + + +Smacof MDS +---------- + +This function allows to find an embedding of points given a dissimilarity matrix +that will be given by the output of the algorithm .. code-block:: python - - - def smacof_mds(C, dim, max_iter=3000, eps=1e-9): - """ - Returns an interpolated point cloud following the dissimilarity matrix C - using SMACOF multidimensional scaling (MDS) in specific dimensionned - target space - - Parameters - ---------- - C : ndarray, shape (ns, ns) - dissimilarity matrix - dim : int - dimension of the targeted space - max_iter : int - Maximum number of iterations of the SMACOF algorithm for a single run - eps : float - relative tolerance w.r.t stress to declare converge - - Returns - ------- - npos : ndarray, shape (R, dim) - Embedded coordinates of the interpolated point cloud (defined with - one isometry) - """ - - rng = np.random.RandomState(seed=3) - - mds = manifold.MDS( - dim, - max_iter=max_iter, - eps=1e-9, - dissimilarity='precomputed', - n_init=1) - pos = mds.fit(C).embedding_ - - nmds = manifold.MDS( - 2, - max_iter=max_iter, - eps=1e-9, - dissimilarity="precomputed", - random_state=rng, - n_init=1) - npos = nmds.fit_transform(C, init=pos) - - return npos - - - - - - - - -Data preparation - ---------------- - - The four distributions are constructed from 4 simple images + + + def smacof_mds(C, dim, max_iter=3000, eps=1e-9): + """ + Returns an interpolated point cloud following the dissimilarity matrix C + using SMACOF multidimensional scaling (MDS) in specific dimensionned + target space + + Parameters + ---------- + C : ndarray, shape (ns, ns) + dissimilarity matrix + dim : int + dimension of the targeted space + max_iter : int + Maximum number of iterations of the SMACOF algorithm for a single run + eps : float + relative tolerance w.r.t stress to declare converge + + Returns + ------- + npos : ndarray, shape (R, dim) + Embedded coordinates of the interpolated point cloud (defined with + one isometry) + """ + + rng = np.random.RandomState(seed=3) + + mds = manifold.MDS( + dim, + max_iter=max_iter, + eps=1e-9, + dissimilarity='precomputed', + n_init=1) + pos = mds.fit(C).embedding_ + + nmds = manifold.MDS( + 2, + max_iter=max_iter, + eps=1e-9, + dissimilarity="precomputed", + random_state=rng, + n_init=1) + npos = nmds.fit_transform(C, init=pos) + + return npos + + + + + + + + +Data preparation +---------------- + +The four distributions are constructed from 4 simple images .. code-block:: python - - - def im2mat(I): - """Converts and image to matrix (one pixel per line)""" - return I.reshape((I.shape[0] * I.shape[1], I.shape[2])) - - - square = spi.imread('../data/square.png').astype(np.float64)[:, :, 2] / 256 - cross = spi.imread('../data/cross.png').astype(np.float64)[:, :, 2] / 256 - triangle = spi.imread('../data/triangle.png').astype(np.float64)[:, :, 2] / 256 - star = spi.imread('../data/star.png').astype(np.float64)[:, :, 2] / 256 - - shapes = [square, cross, triangle, star] - - S = 4 - xs = [[] for i in range(S)] - - - for nb in range(4): - for i in range(8): - for j in range(8): - if shapes[nb][i, j] < 0.95: - xs[nb].append([j, 8 - i]) - - xs = np.array([np.array(xs[0]), np.array(xs[1]), - np.array(xs[2]), np.array(xs[3])]) - + def im2mat(I): + """Converts and image to matrix (one pixel per line)""" + return I.reshape((I.shape[0] * I.shape[1], I.shape[2])) + + + square = spi.imread('../data/square.png').astype(np.float64)[:, :, 2] / 256 + cross = spi.imread('../data/cross.png').astype(np.float64)[:, :, 2] / 256 + triangle = spi.imread('../data/triangle.png').astype(np.float64)[:, :, 2] / 256 + star = spi.imread('../data/star.png').astype(np.float64)[:, :, 2] / 256 + + shapes = [square, cross, triangle, star] + + S = 4 + xs = [[] for i in range(S)] + + for nb in range(4): + for i in range(8): + for j in range(8): + if shapes[nb][i, j] < 0.95: + xs[nb].append([j, 8 - i]) + xs = np.array([np.array(xs[0]), np.array(xs[1]), + np.array(xs[2]), np.array(xs[3])]) -Barycenter computation ----------------------- + + + + + +Barycenter computation +---------------------- .. code-block:: python - - - ns = [len(xs[s]) for s in range(S)] - n_samples = 30 - - """Compute all distances matrices for the four shapes""" - Cs = [sp.spatial.distance.cdist(xs[s], xs[s]) for s in range(S)] - Cs = [cs / cs.max() for cs in Cs] - - ps = [ot.unif(ns[s]) for s in range(S)] - p = ot.unif(n_samples) - - - lambdast = [[float(i) / 3, float(3 - i) / 3] for i in [1, 2]] - - Ct01 = [0 for i in range(2)] - for i in range(2): - Ct01[i] = ot.gromov.gromov_barycenters(n_samples, [Cs[0], Cs[1]], - [ps[0], ps[1] - ], p, lambdast[i], 'square_loss', 5e-4, - max_iter=100, tol=1e-3) - - Ct02 = [0 for i in range(2)] - for i in range(2): - Ct02[i] = ot.gromov.gromov_barycenters(n_samples, [Cs[0], Cs[2]], - [ps[0], ps[2] - ], p, lambdast[i], 'square_loss', 5e-4, - max_iter=100, tol=1e-3) - - Ct13 = [0 for i in range(2)] - for i in range(2): - Ct13[i] = ot.gromov.gromov_barycenters(n_samples, [Cs[1], Cs[3]], - [ps[1], ps[3] - ], p, lambdast[i], 'square_loss', 5e-4, - max_iter=100, tol=1e-3) - - Ct23 = [0 for i in range(2)] - for i in range(2): - Ct23[i] = ot.gromov.gromov_barycenters(n_samples, [Cs[2], Cs[3]], - [ps[2], ps[3] - ], p, lambdast[i], 'square_loss', 5e-4, - max_iter=100, tol=1e-3) - - - - - - - - -Visualization - ------------- - - The PCA helps in getting consistency between the rotations + + + ns = [len(xs[s]) for s in range(S)] + n_samples = 30 + + """Compute all distances matrices for the four shapes""" + Cs = [sp.spatial.distance.cdist(xs[s], xs[s]) for s in range(S)] + Cs = [cs / cs.max() for cs in Cs] + + ps = [ot.unif(ns[s]) for s in range(S)] + p = ot.unif(n_samples) + + + lambdast = [[float(i) / 3, float(3 - i) / 3] for i in [1, 2]] + + Ct01 = [0 for i in range(2)] + for i in range(2): + Ct01[i] = ot.gromov.gromov_barycenters(n_samples, [Cs[0], Cs[1]], + [ps[0], ps[1] + ], p, lambdast[i], 'square_loss', # 5e-4, + max_iter=100, tol=1e-3) + + Ct02 = [0 for i in range(2)] + for i in range(2): + Ct02[i] = ot.gromov.gromov_barycenters(n_samples, [Cs[0], Cs[2]], + [ps[0], ps[2] + ], p, lambdast[i], 'square_loss', # 5e-4, + max_iter=100, tol=1e-3) + + Ct13 = [0 for i in range(2)] + for i in range(2): + Ct13[i] = ot.gromov.gromov_barycenters(n_samples, [Cs[1], Cs[3]], + [ps[1], ps[3] + ], p, lambdast[i], 'square_loss', # 5e-4, + max_iter=100, tol=1e-3) + + Ct23 = [0 for i in range(2)] + for i in range(2): + Ct23[i] = ot.gromov.gromov_barycenters(n_samples, [Cs[2], Cs[3]], + [ps[2], ps[3] + ], p, lambdast[i], 'square_loss', # 5e-4, + max_iter=100, tol=1e-3) + + + + + + + + +Visualization +------------- + +The PCA helps in getting consistency between the rotations .. code-block:: python - - - clf = PCA(n_components=2) - npos = [0, 0, 0, 0] - npos = [smacof_mds(Cs[s], 2) for s in range(S)] - - npost01 = [0, 0] - npost01 = [smacof_mds(Ct01[s], 2) for s in range(2)] - npost01 = [clf.fit_transform(npost01[s]) for s in range(2)] - - npost02 = [0, 0] - npost02 = [smacof_mds(Ct02[s], 2) for s in range(2)] - npost02 = [clf.fit_transform(npost02[s]) for s in range(2)] - - npost13 = [0, 0] - npost13 = [smacof_mds(Ct13[s], 2) for s in range(2)] - npost13 = [clf.fit_transform(npost13[s]) for s in range(2)] - - npost23 = [0, 0] - npost23 = [smacof_mds(Ct23[s], 2) for s in range(2)] - npost23 = [clf.fit_transform(npost23[s]) for s in range(2)] - - - fig = pl.figure(figsize=(10, 10)) - - ax1 = pl.subplot2grid((4, 4), (0, 0)) - pl.xlim((-1, 1)) - pl.ylim((-1, 1)) - ax1.scatter(npos[0][:, 0], npos[0][:, 1], color='r') - - ax2 = pl.subplot2grid((4, 4), (0, 1)) - pl.xlim((-1, 1)) - pl.ylim((-1, 1)) - ax2.scatter(npost01[1][:, 0], npost01[1][:, 1], color='b') - - ax3 = pl.subplot2grid((4, 4), (0, 2)) - pl.xlim((-1, 1)) - pl.ylim((-1, 1)) - ax3.scatter(npost01[0][:, 0], npost01[0][:, 1], color='b') - - ax4 = pl.subplot2grid((4, 4), (0, 3)) - pl.xlim((-1, 1)) - pl.ylim((-1, 1)) - ax4.scatter(npos[1][:, 0], npos[1][:, 1], color='r') - - ax5 = pl.subplot2grid((4, 4), (1, 0)) - pl.xlim((-1, 1)) - pl.ylim((-1, 1)) - ax5.scatter(npost02[1][:, 0], npost02[1][:, 1], color='b') - - ax6 = pl.subplot2grid((4, 4), (1, 3)) - pl.xlim((-1, 1)) - pl.ylim((-1, 1)) - ax6.scatter(npost13[1][:, 0], npost13[1][:, 1], color='b') - - ax7 = pl.subplot2grid((4, 4), (2, 0)) - pl.xlim((-1, 1)) - pl.ylim((-1, 1)) - ax7.scatter(npost02[0][:, 0], npost02[0][:, 1], color='b') - - ax8 = pl.subplot2grid((4, 4), (2, 3)) - pl.xlim((-1, 1)) - pl.ylim((-1, 1)) - ax8.scatter(npost13[0][:, 0], npost13[0][:, 1], color='b') - - ax9 = pl.subplot2grid((4, 4), (3, 0)) - pl.xlim((-1, 1)) - pl.ylim((-1, 1)) - ax9.scatter(npos[2][:, 0], npos[2][:, 1], color='r') - - ax10 = pl.subplot2grid((4, 4), (3, 1)) - pl.xlim((-1, 1)) - pl.ylim((-1, 1)) - ax10.scatter(npost23[1][:, 0], npost23[1][:, 1], color='b') - - ax11 = pl.subplot2grid((4, 4), (3, 2)) - pl.xlim((-1, 1)) - pl.ylim((-1, 1)) - ax11.scatter(npost23[0][:, 0], npost23[0][:, 1], color='b') - - ax12 = pl.subplot2grid((4, 4), (3, 3)) - pl.xlim((-1, 1)) - pl.ylim((-1, 1)) - ax12.scatter(npos[3][:, 0], npos[3][:, 1], color='r') + + + clf = PCA(n_components=2) + npos = [0, 0, 0, 0] + npos = [smacof_mds(Cs[s], 2) for s in range(S)] + + npost01 = [0, 0] + npost01 = [smacof_mds(Ct01[s], 2) for s in range(2)] + npost01 = [clf.fit_transform(npost01[s]) for s in range(2)] + + npost02 = [0, 0] + npost02 = [smacof_mds(Ct02[s], 2) for s in range(2)] + npost02 = [clf.fit_transform(npost02[s]) for s in range(2)] + + npost13 = [0, 0] + npost13 = [smacof_mds(Ct13[s], 2) for s in range(2)] + npost13 = [clf.fit_transform(npost13[s]) for s in range(2)] + + npost23 = [0, 0] + npost23 = [smacof_mds(Ct23[s], 2) for s in range(2)] + npost23 = [clf.fit_transform(npost23[s]) for s in range(2)] + + + fig = pl.figure(figsize=(10, 10)) + + ax1 = pl.subplot2grid((4, 4), (0, 0)) + pl.xlim((-1, 1)) + pl.ylim((-1, 1)) + ax1.scatter(npos[0][:, 0], npos[0][:, 1], color='r') + + ax2 = pl.subplot2grid((4, 4), (0, 1)) + pl.xlim((-1, 1)) + pl.ylim((-1, 1)) + ax2.scatter(npost01[1][:, 0], npost01[1][:, 1], color='b') + + ax3 = pl.subplot2grid((4, 4), (0, 2)) + pl.xlim((-1, 1)) + pl.ylim((-1, 1)) + ax3.scatter(npost01[0][:, 0], npost01[0][:, 1], color='b') + + ax4 = pl.subplot2grid((4, 4), (0, 3)) + pl.xlim((-1, 1)) + pl.ylim((-1, 1)) + ax4.scatter(npos[1][:, 0], npos[1][:, 1], color='r') + + ax5 = pl.subplot2grid((4, 4), (1, 0)) + pl.xlim((-1, 1)) + pl.ylim((-1, 1)) + ax5.scatter(npost02[1][:, 0], npost02[1][:, 1], color='b') + + ax6 = pl.subplot2grid((4, 4), (1, 3)) + pl.xlim((-1, 1)) + pl.ylim((-1, 1)) + ax6.scatter(npost13[1][:, 0], npost13[1][:, 1], color='b') + + ax7 = pl.subplot2grid((4, 4), (2, 0)) + pl.xlim((-1, 1)) + pl.ylim((-1, 1)) + ax7.scatter(npost02[0][:, 0], npost02[0][:, 1], color='b') + + ax8 = pl.subplot2grid((4, 4), (2, 3)) + pl.xlim((-1, 1)) + pl.ylim((-1, 1)) + ax8.scatter(npost13[0][:, 0], npost13[0][:, 1], color='b') + + ax9 = pl.subplot2grid((4, 4), (3, 0)) + pl.xlim((-1, 1)) + pl.ylim((-1, 1)) + ax9.scatter(npos[2][:, 0], npos[2][:, 1], color='r') + + ax10 = pl.subplot2grid((4, 4), (3, 1)) + pl.xlim((-1, 1)) + pl.ylim((-1, 1)) + ax10.scatter(npost23[1][:, 0], npost23[1][:, 1], color='b') + + ax11 = pl.subplot2grid((4, 4), (3, 2)) + pl.xlim((-1, 1)) + pl.ylim((-1, 1)) + ax11.scatter(npost23[0][:, 0], npost23[0][:, 1], color='b') + + ax12 = pl.subplot2grid((4, 4), (3, 3)) + pl.xlim((-1, 1)) + pl.ylim((-1, 1)) + ax12.scatter(npos[3][:, 0], npos[3][:, 1], color='r') @@ -302,11 +302,13 @@ Visualization -**Total running time of the script:** ( 8 minutes 43.875 seconds) +**Total running time of the script:** ( 0 minutes 5.906 seconds) + +.. only :: html -.. container:: sphx-glr-footer + .. container:: sphx-glr-footer .. container:: sphx-glr-download @@ -319,6 +321,9 @@ Visualization :download:`Download Jupyter notebook: plot_gromov_barycenter.ipynb ` -.. rst-class:: sphx-glr-signature - `Generated by Sphinx-Gallery `_ +.. only:: html + + .. rst-class:: sphx-glr-signature + + `Gallery generated by Sphinx-Gallery `_ diff --git a/docs/source/auto_examples/plot_optim_OTreg.ipynb b/docs/source/auto_examples/plot_optim_OTreg.ipynb index 333331b..02bf175 100644 --- a/docs/source/auto_examples/plot_optim_OTreg.ipynb +++ b/docs/source/auto_examples/plot_optim_OTreg.ipynb @@ -1,144 +1,144 @@ { - "nbformat_minor": 0, - "nbformat": 4, "cells": [ { - "execution_count": null, - "cell_type": "code", - "source": [ - "%matplotlib inline" - ], - "outputs": [], + "execution_count": null, "metadata": { "collapsed": false - } - }, + }, + "outputs": [], + "source": [ + "%matplotlib inline" + ], + "cell_type": "code" + }, { + "metadata": {}, "source": [ "\n# Regularized OT with generic solver\n\n\nIllustrates the use of the generic solver for regularized OT with\nuser-designed regularization term. It uses Conditional gradient as in [6] and\ngeneralized Conditional Gradient as proposed in [5][7].\n\n\n[5] N. Courty; R. Flamary; D. Tuia; A. Rakotomamonjy, Optimal Transport for\nDomain Adaptation, in IEEE Transactions on Pattern Analysis and Machine\nIntelligence , vol.PP, no.99, pp.1-1.\n\n[6] Ferradans, S., Papadakis, N., Peyr\u00e9, G., & Aujol, J. F. (2014).\nRegularized discrete optimal transport. SIAM Journal on Imaging Sciences,\n7(3), 1853-1882.\n\n[7] Rakotomamonjy, A., Flamary, R., & Courty, N. (2015). Generalized\nconditional gradient: analysis of convergence and applications.\narXiv preprint arXiv:1510.06567.\n\n\n\n\n" - ], - "cell_type": "markdown", - "metadata": {} - }, + ], + "cell_type": "markdown" + }, { - "execution_count": null, - "cell_type": "code", - "source": [ - "import numpy as np\nimport matplotlib.pylab as pl\nimport ot" - ], - "outputs": [], + "execution_count": null, "metadata": { "collapsed": false - } - }, + }, + "outputs": [], + "source": [ + "import numpy as np\nimport matplotlib.pylab as pl\nimport ot\nimport ot.plot" + ], + "cell_type": "code" + }, { + "metadata": {}, "source": [ "Generate data\n-------------\n\n" - ], - "cell_type": "markdown", - "metadata": {} - }, + ], + "cell_type": "markdown" + }, { - "execution_count": null, - "cell_type": "code", - "source": [ - "#%% parameters\n\nn = 100 # nb bins\n\n# bin positions\nx = np.arange(n, dtype=np.float64)\n\n# Gaussian distributions\na = ot.datasets.get_1D_gauss(n, m=20, s=5) # m= mean, s= std\nb = ot.datasets.get_1D_gauss(n, m=60, s=10)\n\n# loss matrix\nM = ot.dist(x.reshape((n, 1)), x.reshape((n, 1)))\nM /= M.max()" - ], - "outputs": [], + "execution_count": null, "metadata": { "collapsed": false - } - }, + }, + "outputs": [], + "source": [ + "#%% parameters\n\nn = 100 # nb bins\n\n# bin positions\nx = np.arange(n, dtype=np.float64)\n\n# Gaussian distributions\na = ot.datasets.get_1D_gauss(n, m=20, s=5) # m= mean, s= std\nb = ot.datasets.get_1D_gauss(n, m=60, s=10)\n\n# loss matrix\nM = ot.dist(x.reshape((n, 1)), x.reshape((n, 1)))\nM /= M.max()" + ], + "cell_type": "code" + }, { + "metadata": {}, "source": [ "Solve EMD\n---------\n\n" - ], - "cell_type": "markdown", - "metadata": {} - }, + ], + "cell_type": "markdown" + }, { - "execution_count": null, - "cell_type": "code", - "source": [ - "#%% EMD\n\nG0 = ot.emd(a, b, M)\n\npl.figure(3, figsize=(5, 5))\not.plot.plot1D_mat(a, b, G0, 'OT matrix G0')" - ], - "outputs": [], + "execution_count": null, "metadata": { "collapsed": false - } - }, + }, + "outputs": [], + "source": [ + "#%% EMD\n\nG0 = ot.emd(a, b, M)\n\npl.figure(3, figsize=(5, 5))\not.plot.plot1D_mat(a, b, G0, 'OT matrix G0')" + ], + "cell_type": "code" + }, { + "metadata": {}, "source": [ "Solve EMD with Frobenius norm regularization\n--------------------------------------------\n\n" - ], - "cell_type": "markdown", - "metadata": {} - }, + ], + "cell_type": "markdown" + }, { - "execution_count": null, - "cell_type": "code", - "source": [ - "#%% Example with Frobenius norm regularization\n\n\ndef f(G):\n return 0.5 * np.sum(G**2)\n\n\ndef df(G):\n return G\n\n\nreg = 1e-1\n\nGl2 = ot.optim.cg(a, b, M, reg, f, df, verbose=True)\n\npl.figure(3)\not.plot.plot1D_mat(a, b, Gl2, 'OT matrix Frob. reg')" - ], - "outputs": [], + "execution_count": null, "metadata": { "collapsed": false - } - }, + }, + "outputs": [], + "source": [ + "#%% Example with Frobenius norm regularization\n\n\ndef f(G):\n return 0.5 * np.sum(G**2)\n\n\ndef df(G):\n return G\n\n\nreg = 1e-1\n\nGl2 = ot.optim.cg(a, b, M, reg, f, df, verbose=True)\n\npl.figure(3)\not.plot.plot1D_mat(a, b, Gl2, 'OT matrix Frob. reg')" + ], + "cell_type": "code" + }, { + "metadata": {}, "source": [ "Solve EMD with entropic regularization\n--------------------------------------\n\n" - ], - "cell_type": "markdown", - "metadata": {} - }, + ], + "cell_type": "markdown" + }, { - "execution_count": null, - "cell_type": "code", - "source": [ - "#%% Example with entropic regularization\n\n\ndef f(G):\n return np.sum(G * np.log(G))\n\n\ndef df(G):\n return np.log(G) + 1.\n\n\nreg = 1e-3\n\nGe = ot.optim.cg(a, b, M, reg, f, df, verbose=True)\n\npl.figure(4, figsize=(5, 5))\not.plot.plot1D_mat(a, b, Ge, 'OT matrix Entrop. reg')" - ], - "outputs": [], + "execution_count": null, "metadata": { "collapsed": false - } - }, + }, + "outputs": [], + "source": [ + "#%% Example with entropic regularization\n\n\ndef f(G):\n return np.sum(G * np.log(G))\n\n\ndef df(G):\n return np.log(G) + 1.\n\n\nreg = 1e-3\n\nGe = ot.optim.cg(a, b, M, reg, f, df, verbose=True)\n\npl.figure(4, figsize=(5, 5))\not.plot.plot1D_mat(a, b, Ge, 'OT matrix Entrop. reg')" + ], + "cell_type": "code" + }, { + "metadata": {}, "source": [ "Solve EMD with Frobenius norm + entropic regularization\n-------------------------------------------------------\n\n" - ], - "cell_type": "markdown", - "metadata": {} - }, + ], + "cell_type": "markdown" + }, { - "execution_count": null, - "cell_type": "code", - "source": [ - "#%% Example with Frobenius norm + entropic regularization with gcg\n\n\ndef f(G):\n return 0.5 * np.sum(G**2)\n\n\ndef df(G):\n return G\n\n\nreg1 = 1e-3\nreg2 = 1e-1\n\nGel2 = ot.optim.gcg(a, b, M, reg1, reg2, f, df, verbose=True)\n\npl.figure(5, figsize=(5, 5))\not.plot.plot1D_mat(a, b, Gel2, 'OT entropic + matrix Frob. reg')\npl.show()" - ], - "outputs": [], + "execution_count": null, "metadata": { "collapsed": false - } + }, + "outputs": [], + "source": [ + "#%% Example with Frobenius norm + entropic regularization with gcg\n\n\ndef f(G):\n return 0.5 * np.sum(G**2)\n\n\ndef df(G):\n return G\n\n\nreg1 = 1e-3\nreg2 = 1e-1\n\nGel2 = ot.optim.gcg(a, b, M, reg1, reg2, f, df, verbose=True)\n\npl.figure(5, figsize=(5, 5))\not.plot.plot1D_mat(a, b, Gel2, 'OT entropic + matrix Frob. reg')\npl.show()" + ], + "cell_type": "code" } - ], + ], "metadata": { - "kernelspec": { - "display_name": "Python 2", - "name": "python2", - "language": "python" - }, "language_info": { - "mimetype": "text/x-python", - "nbconvert_exporter": "python", - "name": "python", - "file_extension": ".py", - "version": "2.7.12", - "pygments_lexer": "ipython2", + "name": "python", "codemirror_mode": { - "version": 2, - "name": "ipython" - } + "name": "ipython", + "version": 3 + }, + "nbconvert_exporter": "python", + "version": "3.5.2", + "pygments_lexer": "ipython3", + "file_extension": ".py", + "mimetype": "text/x-python" + }, + "kernelspec": { + "display_name": "Python 3", + "name": "python3", + "language": "python" } - } + }, + "nbformat_minor": 0, + "nbformat": 4 } \ No newline at end of file diff --git a/docs/source/auto_examples/plot_optim_OTreg.py b/docs/source/auto_examples/plot_optim_OTreg.py index e1a737e..92df016 100644 --- a/docs/source/auto_examples/plot_optim_OTreg.py +++ b/docs/source/auto_examples/plot_optim_OTreg.py @@ -28,7 +28,7 @@ arXiv preprint arXiv:1510.06567. import numpy as np import matplotlib.pylab as pl import ot - +import ot.plot ############################################################################## # Generate data diff --git a/docs/source/auto_examples/plot_optim_OTreg.rst b/docs/source/auto_examples/plot_optim_OTreg.rst index 480149a..5927428 100644 --- a/docs/source/auto_examples/plot_optim_OTreg.rst +++ b/docs/source/auto_examples/plot_optim_OTreg.rst @@ -35,7 +35,7 @@ arXiv preprint arXiv:1510.06567. import numpy as np import matplotlib.pylab as pl import ot - + import ot.plot @@ -636,11 +636,13 @@ Solve EMD with Frobenius norm + entropic regularization 4|1.609284e-01|-1.111407e-12 -**Total running time of the script:** ( 0 minutes 2.800 seconds) +**Total running time of the script:** ( 0 minutes 2.589 seconds) + +.. only :: html -.. container:: sphx-glr-footer + .. container:: sphx-glr-footer .. container:: sphx-glr-download @@ -653,6 +655,9 @@ Solve EMD with Frobenius norm + entropic regularization :download:`Download Jupyter notebook: plot_optim_OTreg.ipynb ` -.. rst-class:: sphx-glr-signature - `Generated by Sphinx-Gallery `_ +.. only:: html + + .. rst-class:: sphx-glr-signature + + `Gallery generated by Sphinx-Gallery `_ diff --git a/docs/source/auto_examples/plot_otda_d2.ipynb b/docs/source/auto_examples/plot_otda_d2.ipynb index 7bfcc9a..9c58e64 100644 --- a/docs/source/auto_examples/plot_otda_d2.ipynb +++ b/docs/source/auto_examples/plot_otda_d2.ipynb @@ -1,144 +1,144 @@ { - "nbformat_minor": 0, - "nbformat": 4, "cells": [ { - "execution_count": null, - "cell_type": "code", - "source": [ - "%matplotlib inline" - ], - "outputs": [], + "execution_count": null, "metadata": { "collapsed": false - } - }, + }, + "outputs": [], + "source": [ + "%matplotlib inline" + ], + "cell_type": "code" + }, { + "metadata": {}, "source": [ "\n# OT for domain adaptation on empirical distributions\n\n\nThis example introduces a domain adaptation in a 2D setting. It explicits\nthe problem of domain adaptation and introduces some optimal transport\napproaches to solve it.\n\nQuantities such as optimal couplings, greater coupling coefficients and\ntransported samples are represented in order to give a visual understanding\nof what the transport methods are doing.\n\n" - ], - "cell_type": "markdown", - "metadata": {} - }, + ], + "cell_type": "markdown" + }, { - "execution_count": null, - "cell_type": "code", - "source": [ - "# Authors: Remi Flamary \n# Stanislas Chambon \n#\n# License: MIT License\n\nimport matplotlib.pylab as pl\nimport ot" - ], - "outputs": [], + "execution_count": null, "metadata": { "collapsed": false - } - }, + }, + "outputs": [], + "source": [ + "# Authors: Remi Flamary \n# Stanislas Chambon \n#\n# License: MIT License\n\nimport matplotlib.pylab as pl\nimport ot\nimport ot.plot" + ], + "cell_type": "code" + }, { + "metadata": {}, "source": [ "generate data\n-------------\n\n" - ], - "cell_type": "markdown", - "metadata": {} - }, + ], + "cell_type": "markdown" + }, { - "execution_count": null, - "cell_type": "code", - "source": [ - "n_samples_source = 150\nn_samples_target = 150\n\nXs, ys = ot.datasets.get_data_classif('3gauss', n_samples_source)\nXt, yt = ot.datasets.get_data_classif('3gauss2', n_samples_target)\n\n# Cost matrix\nM = ot.dist(Xs, Xt, metric='sqeuclidean')" - ], - "outputs": [], + "execution_count": null, "metadata": { "collapsed": false - } - }, + }, + "outputs": [], + "source": [ + "n_samples_source = 150\nn_samples_target = 150\n\nXs, ys = ot.datasets.get_data_classif('3gauss', n_samples_source)\nXt, yt = ot.datasets.get_data_classif('3gauss2', n_samples_target)\n\n# Cost matrix\nM = ot.dist(Xs, Xt, metric='sqeuclidean')" + ], + "cell_type": "code" + }, { + "metadata": {}, "source": [ "Instantiate the different transport algorithms and fit them\n-----------------------------------------------------------\n\n" - ], - "cell_type": "markdown", - "metadata": {} - }, + ], + "cell_type": "markdown" + }, { - "execution_count": null, - "cell_type": "code", - "source": [ - "# EMD Transport\not_emd = ot.da.EMDTransport()\not_emd.fit(Xs=Xs, Xt=Xt)\n\n# Sinkhorn Transport\not_sinkhorn = ot.da.SinkhornTransport(reg_e=1e-1)\not_sinkhorn.fit(Xs=Xs, Xt=Xt)\n\n# Sinkhorn Transport with Group lasso regularization\not_lpl1 = ot.da.SinkhornLpl1Transport(reg_e=1e-1, reg_cl=1e0)\not_lpl1.fit(Xs=Xs, ys=ys, Xt=Xt)\n\n# transport source samples onto target samples\ntransp_Xs_emd = ot_emd.transform(Xs=Xs)\ntransp_Xs_sinkhorn = ot_sinkhorn.transform(Xs=Xs)\ntransp_Xs_lpl1 = ot_lpl1.transform(Xs=Xs)" - ], - "outputs": [], + "execution_count": null, "metadata": { "collapsed": false - } - }, + }, + "outputs": [], + "source": [ + "# EMD Transport\not_emd = ot.da.EMDTransport()\not_emd.fit(Xs=Xs, Xt=Xt)\n\n# Sinkhorn Transport\not_sinkhorn = ot.da.SinkhornTransport(reg_e=1e-1)\not_sinkhorn.fit(Xs=Xs, Xt=Xt)\n\n# Sinkhorn Transport with Group lasso regularization\not_lpl1 = ot.da.SinkhornLpl1Transport(reg_e=1e-1, reg_cl=1e0)\not_lpl1.fit(Xs=Xs, ys=ys, Xt=Xt)\n\n# transport source samples onto target samples\ntransp_Xs_emd = ot_emd.transform(Xs=Xs)\ntransp_Xs_sinkhorn = ot_sinkhorn.transform(Xs=Xs)\ntransp_Xs_lpl1 = ot_lpl1.transform(Xs=Xs)" + ], + "cell_type": "code" + }, { + "metadata": {}, "source": [ "Fig 1 : plots source and target samples + matrix of pairwise distance\n---------------------------------------------------------------------\n\n" - ], - "cell_type": "markdown", - "metadata": {} - }, + ], + "cell_type": "markdown" + }, { - "execution_count": null, - "cell_type": "code", - "source": [ - "pl.figure(1, figsize=(10, 10))\npl.subplot(2, 2, 1)\npl.scatter(Xs[:, 0], Xs[:, 1], c=ys, marker='+', label='Source samples')\npl.xticks([])\npl.yticks([])\npl.legend(loc=0)\npl.title('Source samples')\n\npl.subplot(2, 2, 2)\npl.scatter(Xt[:, 0], Xt[:, 1], c=yt, marker='o', label='Target samples')\npl.xticks([])\npl.yticks([])\npl.legend(loc=0)\npl.title('Target samples')\n\npl.subplot(2, 2, 3)\npl.imshow(M, interpolation='nearest')\npl.xticks([])\npl.yticks([])\npl.title('Matrix of pairwise distances')\npl.tight_layout()" - ], - "outputs": [], + "execution_count": null, "metadata": { "collapsed": false - } - }, + }, + "outputs": [], + "source": [ + "pl.figure(1, figsize=(10, 10))\npl.subplot(2, 2, 1)\npl.scatter(Xs[:, 0], Xs[:, 1], c=ys, marker='+', label='Source samples')\npl.xticks([])\npl.yticks([])\npl.legend(loc=0)\npl.title('Source samples')\n\npl.subplot(2, 2, 2)\npl.scatter(Xt[:, 0], Xt[:, 1], c=yt, marker='o', label='Target samples')\npl.xticks([])\npl.yticks([])\npl.legend(loc=0)\npl.title('Target samples')\n\npl.subplot(2, 2, 3)\npl.imshow(M, interpolation='nearest')\npl.xticks([])\npl.yticks([])\npl.title('Matrix of pairwise distances')\npl.tight_layout()" + ], + "cell_type": "code" + }, { + "metadata": {}, "source": [ "Fig 2 : plots optimal couplings for the different methods\n---------------------------------------------------------\n\n" - ], - "cell_type": "markdown", - "metadata": {} - }, + ], + "cell_type": "markdown" + }, { - "execution_count": null, - "cell_type": "code", - "source": [ - "pl.figure(2, figsize=(10, 6))\n\npl.subplot(2, 3, 1)\npl.imshow(ot_emd.coupling_, interpolation='nearest')\npl.xticks([])\npl.yticks([])\npl.title('Optimal coupling\\nEMDTransport')\n\npl.subplot(2, 3, 2)\npl.imshow(ot_sinkhorn.coupling_, interpolation='nearest')\npl.xticks([])\npl.yticks([])\npl.title('Optimal coupling\\nSinkhornTransport')\n\npl.subplot(2, 3, 3)\npl.imshow(ot_lpl1.coupling_, interpolation='nearest')\npl.xticks([])\npl.yticks([])\npl.title('Optimal coupling\\nSinkhornLpl1Transport')\n\npl.subplot(2, 3, 4)\not.plot.plot2D_samples_mat(Xs, Xt, ot_emd.coupling_, c=[.5, .5, 1])\npl.scatter(Xs[:, 0], Xs[:, 1], c=ys, marker='+', label='Source samples')\npl.scatter(Xt[:, 0], Xt[:, 1], c=yt, marker='o', label='Target samples')\npl.xticks([])\npl.yticks([])\npl.title('Main coupling coefficients\\nEMDTransport')\n\npl.subplot(2, 3, 5)\not.plot.plot2D_samples_mat(Xs, Xt, ot_sinkhorn.coupling_, c=[.5, .5, 1])\npl.scatter(Xs[:, 0], Xs[:, 1], c=ys, marker='+', label='Source samples')\npl.scatter(Xt[:, 0], Xt[:, 1], c=yt, marker='o', label='Target samples')\npl.xticks([])\npl.yticks([])\npl.title('Main coupling coefficients\\nSinkhornTransport')\n\npl.subplot(2, 3, 6)\not.plot.plot2D_samples_mat(Xs, Xt, ot_lpl1.coupling_, c=[.5, .5, 1])\npl.scatter(Xs[:, 0], Xs[:, 1], c=ys, marker='+', label='Source samples')\npl.scatter(Xt[:, 0], Xt[:, 1], c=yt, marker='o', label='Target samples')\npl.xticks([])\npl.yticks([])\npl.title('Main coupling coefficients\\nSinkhornLpl1Transport')\npl.tight_layout()" - ], - "outputs": [], + "execution_count": null, "metadata": { "collapsed": false - } - }, + }, + "outputs": [], + "source": [ + "pl.figure(2, figsize=(10, 6))\n\npl.subplot(2, 3, 1)\npl.imshow(ot_emd.coupling_, interpolation='nearest')\npl.xticks([])\npl.yticks([])\npl.title('Optimal coupling\\nEMDTransport')\n\npl.subplot(2, 3, 2)\npl.imshow(ot_sinkhorn.coupling_, interpolation='nearest')\npl.xticks([])\npl.yticks([])\npl.title('Optimal coupling\\nSinkhornTransport')\n\npl.subplot(2, 3, 3)\npl.imshow(ot_lpl1.coupling_, interpolation='nearest')\npl.xticks([])\npl.yticks([])\npl.title('Optimal coupling\\nSinkhornLpl1Transport')\n\npl.subplot(2, 3, 4)\not.plot.plot2D_samples_mat(Xs, Xt, ot_emd.coupling_, c=[.5, .5, 1])\npl.scatter(Xs[:, 0], Xs[:, 1], c=ys, marker='+', label='Source samples')\npl.scatter(Xt[:, 0], Xt[:, 1], c=yt, marker='o', label='Target samples')\npl.xticks([])\npl.yticks([])\npl.title('Main coupling coefficients\\nEMDTransport')\n\npl.subplot(2, 3, 5)\not.plot.plot2D_samples_mat(Xs, Xt, ot_sinkhorn.coupling_, c=[.5, .5, 1])\npl.scatter(Xs[:, 0], Xs[:, 1], c=ys, marker='+', label='Source samples')\npl.scatter(Xt[:, 0], Xt[:, 1], c=yt, marker='o', label='Target samples')\npl.xticks([])\npl.yticks([])\npl.title('Main coupling coefficients\\nSinkhornTransport')\n\npl.subplot(2, 3, 6)\not.plot.plot2D_samples_mat(Xs, Xt, ot_lpl1.coupling_, c=[.5, .5, 1])\npl.scatter(Xs[:, 0], Xs[:, 1], c=ys, marker='+', label='Source samples')\npl.scatter(Xt[:, 0], Xt[:, 1], c=yt, marker='o', label='Target samples')\npl.xticks([])\npl.yticks([])\npl.title('Main coupling coefficients\\nSinkhornLpl1Transport')\npl.tight_layout()" + ], + "cell_type": "code" + }, { + "metadata": {}, "source": [ "Fig 3 : plot transported samples\n--------------------------------\n\n" - ], - "cell_type": "markdown", - "metadata": {} - }, + ], + "cell_type": "markdown" + }, { - "execution_count": null, - "cell_type": "code", - "source": [ - "# display transported samples\npl.figure(4, figsize=(10, 4))\npl.subplot(1, 3, 1)\npl.scatter(Xt[:, 0], Xt[:, 1], c=yt, marker='o',\n label='Target samples', alpha=0.5)\npl.scatter(transp_Xs_emd[:, 0], transp_Xs_emd[:, 1], c=ys,\n marker='+', label='Transp samples', s=30)\npl.title('Transported samples\\nEmdTransport')\npl.legend(loc=0)\npl.xticks([])\npl.yticks([])\n\npl.subplot(1, 3, 2)\npl.scatter(Xt[:, 0], Xt[:, 1], c=yt, marker='o',\n label='Target samples', alpha=0.5)\npl.scatter(transp_Xs_sinkhorn[:, 0], transp_Xs_sinkhorn[:, 1], c=ys,\n marker='+', label='Transp samples', s=30)\npl.title('Transported samples\\nSinkhornTransport')\npl.xticks([])\npl.yticks([])\n\npl.subplot(1, 3, 3)\npl.scatter(Xt[:, 0], Xt[:, 1], c=yt, marker='o',\n label='Target samples', alpha=0.5)\npl.scatter(transp_Xs_lpl1[:, 0], transp_Xs_lpl1[:, 1], c=ys,\n marker='+', label='Transp samples', s=30)\npl.title('Transported samples\\nSinkhornLpl1Transport')\npl.xticks([])\npl.yticks([])\n\npl.tight_layout()\npl.show()" - ], - "outputs": [], + "execution_count": null, "metadata": { "collapsed": false - } + }, + "outputs": [], + "source": [ + "# display transported samples\npl.figure(4, figsize=(10, 4))\npl.subplot(1, 3, 1)\npl.scatter(Xt[:, 0], Xt[:, 1], c=yt, marker='o',\n label='Target samples', alpha=0.5)\npl.scatter(transp_Xs_emd[:, 0], transp_Xs_emd[:, 1], c=ys,\n marker='+', label='Transp samples', s=30)\npl.title('Transported samples\\nEmdTransport')\npl.legend(loc=0)\npl.xticks([])\npl.yticks([])\n\npl.subplot(1, 3, 2)\npl.scatter(Xt[:, 0], Xt[:, 1], c=yt, marker='o',\n label='Target samples', alpha=0.5)\npl.scatter(transp_Xs_sinkhorn[:, 0], transp_Xs_sinkhorn[:, 1], c=ys,\n marker='+', label='Transp samples', s=30)\npl.title('Transported samples\\nSinkhornTransport')\npl.xticks([])\npl.yticks([])\n\npl.subplot(1, 3, 3)\npl.scatter(Xt[:, 0], Xt[:, 1], c=yt, marker='o',\n label='Target samples', alpha=0.5)\npl.scatter(transp_Xs_lpl1[:, 0], transp_Xs_lpl1[:, 1], c=ys,\n marker='+', label='Transp samples', s=30)\npl.title('Transported samples\\nSinkhornLpl1Transport')\npl.xticks([])\npl.yticks([])\n\npl.tight_layout()\npl.show()" + ], + "cell_type": "code" } - ], + ], "metadata": { - "kernelspec": { - "display_name": "Python 2", - "name": "python2", - "language": "python" - }, "language_info": { - "mimetype": "text/x-python", - "nbconvert_exporter": "python", - "name": "python", - "file_extension": ".py", - "version": "2.7.12", - "pygments_lexer": "ipython2", + "name": "python", "codemirror_mode": { - "version": 2, - "name": "ipython" - } + "name": "ipython", + "version": 3 + }, + "nbconvert_exporter": "python", + "version": "3.5.2", + "pygments_lexer": "ipython3", + "file_extension": ".py", + "mimetype": "text/x-python" + }, + "kernelspec": { + "display_name": "Python 3", + "name": "python3", + "language": "python" } - } + }, + "nbformat_minor": 0, + "nbformat": 4 } \ No newline at end of file diff --git a/docs/source/auto_examples/plot_otda_d2.py b/docs/source/auto_examples/plot_otda_d2.py index e53d7d6..70beb35 100644 --- a/docs/source/auto_examples/plot_otda_d2.py +++ b/docs/source/auto_examples/plot_otda_d2.py @@ -20,7 +20,7 @@ of what the transport methods are doing. import matplotlib.pylab as pl import ot - +import ot.plot ############################################################################## # generate data diff --git a/docs/source/auto_examples/plot_otda_d2.rst b/docs/source/auto_examples/plot_otda_d2.rst index 1bbe6d9..e5a60c4 100644 --- a/docs/source/auto_examples/plot_otda_d2.rst +++ b/docs/source/auto_examples/plot_otda_d2.rst @@ -27,7 +27,7 @@ of what the transport methods are doing. import matplotlib.pylab as pl import ot - + import ot.plot @@ -242,11 +242,13 @@ Fig 3 : plot transported samples -**Total running time of the script:** ( 0 minutes 47.000 seconds) +**Total running time of the script:** ( 0 minutes 39.829 seconds) + +.. only :: html -.. container:: sphx-glr-footer + .. container:: sphx-glr-footer .. container:: sphx-glr-download @@ -259,6 +261,9 @@ Fig 3 : plot transported samples :download:`Download Jupyter notebook: plot_otda_d2.ipynb ` -.. rst-class:: sphx-glr-signature - `Generated by Sphinx-Gallery `_ +.. only:: html + + .. rst-class:: sphx-glr-signature + + `Gallery generated by Sphinx-Gallery `_ -- cgit v1.2.3