{
  "cells": [
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "%matplotlib inline"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "\n# The Johnson-Lindenstrauss bound for embedding with random projections\n\n\n\nThe `Johnson-Lindenstrauss lemma`_ states that any high dimensional\ndataset can be randomly projected into a lower dimensional Euclidean\nspace while controlling the distortion in the pairwise distances.\n\n\n\nTheoretical bounds\n==================\n\nThe distortion introduced by a random projection `p` is asserted by\nthe fact that `p` is defining an eps-embedding with good probability\nas defined by:\n\n\\begin{align}(1 - eps) \\|u - v\\|^2 < \\|p(u) - p(v)\\|^2 < (1 + eps) \\|u - v\\|^2\\end{align}\n\nWhere u and v are any rows taken from a dataset of shape [n_samples,\nn_features] and p is a projection by a random Gaussian N(0, 1) matrix\nwith shape [n_components, n_features] (or a sparse Achlioptas matrix).\n\nThe minimum number of components to guarantees the eps-embedding is\ngiven by:\n\n\\begin{align}n\\_components >= 4 log(n\\_samples) / (eps^2 / 2 - eps^3 / 3)\\end{align}\n\n\nThe first plot shows that with an increasing number of samples ``n_samples``,\nthe minimal number of dimensions ``n_components`` increased logarithmically\nin order to guarantee an ``eps``-embedding.\n\nThe second plot shows that an increase of the admissible\ndistortion ``eps`` allows to reduce drastically the minimal number of\ndimensions ``n_components`` for a given number of samples ``n_samples``\n\n\nEmpirical validation\n====================\n\nWe validate the above bounds on the digits dataset or on the 20 newsgroups\ntext document (TF-IDF word frequencies) dataset:\n\n- for the digits dataset, some 8x8 gray level pixels data for 500\n  handwritten digits pictures are randomly projected to spaces for various\n  larger number of dimensions ``n_components``.\n\n- for the 20 newsgroups dataset some 500 documents with 100k\n  features in total are projected using a sparse random matrix to smaller\n  euclidean spaces with various values for the target number of dimensions\n  ``n_components``.\n\nThe default dataset is the digits dataset. To run the example on the twenty\nnewsgroups dataset, pass the --twenty-newsgroups command line argument to this\nscript.\n\nFor each value of ``n_components``, we plot:\n\n- 2D distribution of sample pairs with pairwise distances in original\n  and projected spaces as x and y axis respectively.\n\n- 1D histogram of the ratio of those distances (projected / original).\n\nWe can see that for low values of ``n_components`` the distribution is wide\nwith many distorted pairs and a skewed distribution (due to the hard\nlimit of zero ratio on the left as distances are always positives)\nwhile for larger values of n_components the distortion is controlled\nand the distances are well preserved by the random projection.\n\n\nRemarks\n=======\n\nAccording to the JL lemma, projecting 500 samples without too much distortion\nwill require at least several thousands dimensions, irrespective of the\nnumber of features of the original dataset.\n\nHence using random projections on the digits dataset which only has 64 features\nin the input space does not make sense: it does not allow for dimensionality\nreduction in this case.\n\nOn the twenty newsgroups on the other hand the dimensionality can be decreased\nfrom 56436 down to 10000 while reasonably preserving pairwise distances.\n\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "print(__doc__)\n\nimport sys\nfrom time import time\nimport numpy as np\nimport matplotlib\nimport matplotlib.pyplot as plt\nfrom distutils.version import LooseVersion\nfrom sklearn.random_projection import johnson_lindenstrauss_min_dim\nfrom sklearn.random_projection import SparseRandomProjection\nfrom sklearn.datasets import fetch_20newsgroups_vectorized\nfrom sklearn.datasets import load_digits\nfrom sklearn.metrics.pairwise import euclidean_distances\n\n# `normed` is being deprecated in favor of `density` in histograms\nif LooseVersion(matplotlib.__version__) >= '2.1':\n    density_param = {'density': True}\nelse:\n    density_param = {'normed': True}\n\n# Part 1: plot the theoretical dependency between n_components_min and\n# n_samples\n\n# range of admissible distortions\neps_range = np.linspace(0.1, 0.99, 5)\ncolors = plt.cm.Blues(np.linspace(0.3, 1.0, len(eps_range)))\n\n# range of number of samples (observation) to embed\nn_samples_range = np.logspace(1, 9, 9)\n\nplt.figure()\nfor eps, color in zip(eps_range, colors):\n    min_n_components = johnson_lindenstrauss_min_dim(n_samples_range, eps=eps)\n    plt.loglog(n_samples_range, min_n_components, color=color)\n\nplt.legend([\"eps = %0.1f\" % eps for eps in eps_range], loc=\"lower right\")\nplt.xlabel(\"Number of observations to eps-embed\")\nplt.ylabel(\"Minimum number of dimensions\")\nplt.title(\"Johnson-Lindenstrauss bounds:\\nn_samples vs n_components\")\n\n# range of admissible distortions\neps_range = np.linspace(0.01, 0.99, 100)\n\n# range of number of samples (observation) to embed\nn_samples_range = np.logspace(2, 6, 5)\ncolors = plt.cm.Blues(np.linspace(0.3, 1.0, len(n_samples_range)))\n\nplt.figure()\nfor n_samples, color in zip(n_samples_range, colors):\n    min_n_components = johnson_lindenstrauss_min_dim(n_samples, eps=eps_range)\n    plt.semilogy(eps_range, min_n_components, color=color)\n\nplt.legend([\"n_samples = %d\" % n for n in n_samples_range], loc=\"upper right\")\nplt.xlabel(\"Distortion eps\")\nplt.ylabel(\"Minimum number of dimensions\")\nplt.title(\"Johnson-Lindenstrauss bounds:\\nn_components vs eps\")\n\n# Part 2: perform sparse random projection of some digits images which are\n# quite low dimensional and dense or documents of the 20 newsgroups dataset\n# which is both high dimensional and sparse\n\nif '--twenty-newsgroups' in sys.argv:\n    # Need an internet connection hence not enabled by default\n    data = fetch_20newsgroups_vectorized().data[:500]\nelse:\n    data = load_digits().data[:500]\n\nn_samples, n_features = data.shape\nprint(\"Embedding %d samples with dim %d using various random projections\"\n      % (n_samples, n_features))\n\nn_components_range = np.array([300, 1000, 10000])\ndists = euclidean_distances(data, squared=True).ravel()\n\n# select only non-identical samples pairs\nnonzero = dists != 0\ndists = dists[nonzero]\n\nfor n_components in n_components_range:\n    t0 = time()\n    rp = SparseRandomProjection(n_components=n_components)\n    projected_data = rp.fit_transform(data)\n    print(\"Projected %d samples from %d to %d in %0.3fs\"\n          % (n_samples, n_features, n_components, time() - t0))\n    if hasattr(rp, 'components_'):\n        n_bytes = rp.components_.data.nbytes\n        n_bytes += rp.components_.indices.nbytes\n        print(\"Random matrix with size: %0.3fMB\" % (n_bytes / 1e6))\n\n    projected_dists = euclidean_distances(\n        projected_data, squared=True).ravel()[nonzero]\n\n    plt.figure()\n    plt.hexbin(dists, projected_dists, gridsize=100, cmap=plt.cm.PuBu)\n    plt.xlabel(\"Pairwise squared distances in original space\")\n    plt.ylabel(\"Pairwise squared distances in projected space\")\n    plt.title(\"Pairwise distances distribution for n_components=%d\" %\n              n_components)\n    cb = plt.colorbar()\n    cb.set_label('Sample pairs counts')\n\n    rates = projected_dists / dists\n    print(\"Mean distances rate: %0.2f (%0.2f)\"\n          % (np.mean(rates), np.std(rates)))\n\n    plt.figure()\n    plt.hist(rates, bins=50, range=(0., 2.), edgecolor='k', **density_param)\n    plt.xlabel(\"Squared distances rate: projected / original\")\n    plt.ylabel(\"Distribution of samples pairs\")\n    plt.title(\"Histogram of pairwise distance rates for n_components=%d\" %\n              n_components)\n\n    # TODO: compute the expected value of eps and add them to the previous plot\n    # as vertical lines / region\n\nplt.show()"
      ]
    }
  ],
  "metadata": {
    "kernelspec": {
      "display_name": "Python 3",
      "language": "python",
      "name": "python3"
    },
    "language_info": {
      "codemirror_mode": {
        "name": "ipython",
        "version": 3
      },
      "file_extension": ".py",
      "mimetype": "text/x-python",
      "name": "python",
      "nbconvert_exporter": "python",
      "pygments_lexer": "ipython3",
      "version": "3.6.7"
    }
  },
  "nbformat": 4,
  "nbformat_minor": 0
}