|
26 | 26 | },
|
27 | 27 | "outputs": [],
|
28 | 28 | "source": [
|
29 |
| - "# Author: Jake Vanderplas -- < [email protected]>\n\nfrom collections import OrderedDict\nfrom functools import partial\nfrom time import time\n\nimport matplotlib.pyplot as plt\nfrom mpl_toolkits.mplot3d import Axes3D\nfrom matplotlib.ticker import NullFormatter\n\nfrom sklearn import manifold, datasets\n\n# Next line to silence pyflakes. This import is needed.\nAxes3D\n\nn_points = 1000\nX, color = datasets.make_s_curve(n_points, random_state=0)\nn_neighbors = 10\nn_components = 2\n\n# Create figure\nfig = plt.figure(figsize=(15, 8))\nfig.suptitle(\n \"Manifold Learning with %i points, %i neighbors\" % (n_points, n_neighbors),\n fontsize=14,\n)\n\n# Add 3d scatter plot\nax = fig.add_subplot(251, projection=\"3d\")\nax.scatter(X[:, 0], X[:, 1], X[:, 2], c=color, cmap=plt.cm.Spectral)\nax.view_init(4, -72)\n\n# Set-up manifold methods\nLLE = partial(\n manifold.LocallyLinearEmbedding,\n n_neighbors=n_neighbors,\n n_components=n_components,\n eigen_solver=\"auto\",\n random_state=0,\n)\n\nmethods = OrderedDict()\nmethods[\"LLE\"] = LLE(method=\"standard\")\nmethods[\"LTSA\"] = LLE(method=\"ltsa\")\nmethods[\"Hessian LLE\"] = LLE(method=\"hessian\")\nmethods[\"Modified LLE\"] = LLE(method=\"modified\")\nmethods[\"Isomap\"] = manifold.Isomap(n_neighbors=n_neighbors, n_components=n_components)\nmethods[\"MDS\"] = manifold.MDS(n_components, max_iter=50, n_init=1, random_state=0)\nmethods[\"SE\"] = manifold.SpectralEmbedding(\n n_components=n_components, n_neighbors=n_neighbors, random_state=0\n)\nmethods[\"t-SNE\"] = manifold.TSNE(\n n_components=n_components, perplexity=30, n_iter=250, init=\"pca\", random_state=0\n)\n\n# Plot results\nfor i, (label, method) in enumerate(methods.items()):\n t0 = time()\n Y = method.fit_transform(X)\n t1 = time()\n print(\"%s: %.2g sec\" % (label, t1 - t0))\n ax = fig.add_subplot(2, 5, 2 + i + (i > 3))\n ax.scatter(Y[:, 0], Y[:, 1], c=color, cmap=plt.cm.Spectral)\n ax.set_title(\"%s (%.2g sec)\" % (label, t1 - t0))\n ax.xaxis.set_major_formatter(NullFormatter())\n ax.yaxis.set_major_formatter(NullFormatter())\n ax.axis(\"tight\")\n\nplt.show()" |
| 29 | + "# Author: Jake Vanderplas -- <[email protected]>" |
| 30 | + ] |
| 31 | + }, |
| 32 | + { |
| 33 | + "cell_type": "markdown", |
| 34 | + "metadata": {}, |
| 35 | + "source": [ |
| 36 | + "## Dataset preparation\n\nWe start by generating the S-curve dataset.\n\n" |
| 37 | + ] |
| 38 | + }, |
| 39 | + { |
| 40 | + "cell_type": "code", |
| 41 | + "execution_count": null, |
| 42 | + "metadata": { |
| 43 | + "collapsed": false |
| 44 | + }, |
| 45 | + "outputs": [], |
| 46 | + "source": [ |
| 47 | + "from numpy.random import RandomState\nimport matplotlib.pyplot as plt\nfrom matplotlib import ticker\n\nfrom sklearn import manifold, datasets\n\nrng = RandomState(0)\n\nn_samples = 1500\nS_points, S_color = datasets.make_s_curve(n_samples, random_state=rng)" |
| 48 | + ] |
| 49 | + }, |
| 50 | + { |
| 51 | + "cell_type": "markdown", |
| 52 | + "metadata": {}, |
| 53 | + "source": [ |
| 54 | + "Let's look at the original data. Also define some helping\nfunctions, which we will use further on.\n\n" |
| 55 | + ] |
| 56 | + }, |
| 57 | + { |
| 58 | + "cell_type": "code", |
| 59 | + "execution_count": null, |
| 60 | + "metadata": { |
| 61 | + "collapsed": false |
| 62 | + }, |
| 63 | + "outputs": [], |
| 64 | + "source": [ |
| 65 | + "def plot_3d(points, points_color, title):\n x, y, z = points.T\n\n fig, ax = plt.subplots(\n figsize=(6, 6),\n facecolor=\"white\",\n tight_layout=True,\n subplot_kw={\"projection\": \"3d\"},\n )\n fig.suptitle(title, size=16)\n col = ax.scatter(x, y, z, c=points_color, s=50, alpha=0.8)\n ax.view_init(azim=-60, elev=9)\n ax.xaxis.set_major_locator(ticker.MultipleLocator(1))\n ax.yaxis.set_major_locator(ticker.MultipleLocator(1))\n ax.zaxis.set_major_locator(ticker.MultipleLocator(1))\n\n fig.colorbar(col, ax=ax, orientation=\"horizontal\", shrink=0.6, aspect=60, pad=0.01)\n plt.show()\n\n\ndef plot_2d(points, points_color, title):\n fig, ax = plt.subplots(figsize=(3, 3), facecolor=\"white\", constrained_layout=True)\n fig.suptitle(title, size=16)\n add_2d_scatter(ax, points, points_color)\n plt.show()\n\n\ndef add_2d_scatter(ax, points, points_color, title=None):\n x, y = points.T\n ax.scatter(x, y, c=points_color, s=50, alpha=0.8)\n ax.set_title(title)\n ax.xaxis.set_major_formatter(ticker.NullFormatter())\n ax.yaxis.set_major_formatter(ticker.NullFormatter())\n\n\nplot_3d(S_points, S_color, \"Original S-curve samples\")" |
| 66 | + ] |
| 67 | + }, |
| 68 | + { |
| 69 | + "cell_type": "markdown", |
| 70 | + "metadata": {}, |
| 71 | + "source": [ |
| 72 | + "## Define algorithms for the manifold learning\n\nManifold learning is an approach to non-linear dimensionality reduction.\nAlgorithms for this task are based on the idea that the dimensionality of\nmany data sets is only artificially high.\n\nRead more in the `User Guide <manifold>`.\n\n" |
| 73 | + ] |
| 74 | + }, |
| 75 | + { |
| 76 | + "cell_type": "code", |
| 77 | + "execution_count": null, |
| 78 | + "metadata": { |
| 79 | + "collapsed": false |
| 80 | + }, |
| 81 | + "outputs": [], |
| 82 | + "source": [ |
| 83 | + "n_neighbors = 12 # neighborhood which is used to recover the locally linear structure\nn_components = 2 # number of coordinates for the manifold" |
| 84 | + ] |
| 85 | + }, |
| 86 | + { |
| 87 | + "cell_type": "markdown", |
| 88 | + "metadata": {}, |
| 89 | + "source": [ |
| 90 | + "### Locally Linear Embeddings\n\nLocally linear embedding (LLE) can be thought of as a series of local\nPrincipal Component Analyses which are globally compared to find the\nbest non-linear embedding.\nRead more in the `User Guide <locally_linear_embedding>`.\n\n" |
| 91 | + ] |
| 92 | + }, |
| 93 | + { |
| 94 | + "cell_type": "code", |
| 95 | + "execution_count": null, |
| 96 | + "metadata": { |
| 97 | + "collapsed": false |
| 98 | + }, |
| 99 | + "outputs": [], |
| 100 | + "source": [ |
| 101 | + "params = {\n \"n_neighbors\": n_neighbors,\n \"n_components\": n_components,\n \"eigen_solver\": \"auto\",\n \"random_state\": rng,\n}\n\nlle_standart = manifold.LocallyLinearEmbedding(method=\"standard\", **params)\nS_standart = lle_standart.fit_transform(S_points)\n\nlle_ltsa = manifold.LocallyLinearEmbedding(method=\"ltsa\", **params)\nS_ltsa = lle_ltsa.fit_transform(S_points)\n\nlle_hessian = manifold.LocallyLinearEmbedding(method=\"hessian\", **params)\nS_hessian = lle_hessian.fit_transform(S_points)\n\nlle_mod = manifold.LocallyLinearEmbedding(method=\"modified\", modified_tol=0.8, **params)\nS_mod = lle_mod.fit_transform(S_points)" |
| 102 | + ] |
| 103 | + }, |
| 104 | + { |
| 105 | + "cell_type": "code", |
| 106 | + "execution_count": null, |
| 107 | + "metadata": { |
| 108 | + "collapsed": false |
| 109 | + }, |
| 110 | + "outputs": [], |
| 111 | + "source": [ |
| 112 | + "fig, axs = plt.subplots(\n nrows=2, ncols=2, figsize=(7, 7), facecolor=\"white\", constrained_layout=True\n)\nfig.suptitle(\"Locally Linear Embeddings\", size=16)\n\nlle_methods = [\n (\"Standart locally linear embedding\", S_standart),\n (\"Local tangent space alignment\", S_ltsa),\n (\"Hessian eigenmap\", S_hessian),\n (\"Modified locally linear embedding\", S_mod),\n]\nfor ax, method in zip(axs.flat, lle_methods):\n name, points = method\n add_2d_scatter(ax, points, S_color, name)\n\nplt.show()" |
| 113 | + ] |
| 114 | + }, |
| 115 | + { |
| 116 | + "cell_type": "markdown", |
| 117 | + "metadata": {}, |
| 118 | + "source": [ |
| 119 | + "### Isomap Embedding\n\nNon-linear dimensionality reduction through Isometric Mapping.\nIsomap seeks a lower-dimensional embedding which maintains geodesic\ndistances between all points. Read more in the `User Guide <isomap>`.\n\n" |
| 120 | + ] |
| 121 | + }, |
| 122 | + { |
| 123 | + "cell_type": "code", |
| 124 | + "execution_count": null, |
| 125 | + "metadata": { |
| 126 | + "collapsed": false |
| 127 | + }, |
| 128 | + "outputs": [], |
| 129 | + "source": [ |
| 130 | + "isomap = manifold.Isomap(n_neighbors=n_neighbors, n_components=n_components, p=1)\nS_isomap = isomap.fit_transform(S_points)\n\nplot_2d(S_isomap, S_color, \"Isomap Embedding\")" |
| 131 | + ] |
| 132 | + }, |
| 133 | + { |
| 134 | + "cell_type": "markdown", |
| 135 | + "metadata": {}, |
| 136 | + "source": [ |
| 137 | + "### Multidimensional scaling\n\nMultidimensional scaling (MDS) seeks a low-dimensional representation\nof the data in which the distances respect well the distances in the\noriginal high-dimensional space.\nRead more in the `User Guide <multidimensional_scaling>`.\n\n" |
| 138 | + ] |
| 139 | + }, |
| 140 | + { |
| 141 | + "cell_type": "code", |
| 142 | + "execution_count": null, |
| 143 | + "metadata": { |
| 144 | + "collapsed": false |
| 145 | + }, |
| 146 | + "outputs": [], |
| 147 | + "source": [ |
| 148 | + "md_scaling = manifold.MDS(\n n_components=n_components, max_iter=50, n_init=4, random_state=rng\n)\nS_scaling = md_scaling.fit_transform(S_points)\n\nplot_2d(S_scaling, S_color, \"Multidimensional scaling\")" |
| 149 | + ] |
| 150 | + }, |
| 151 | + { |
| 152 | + "cell_type": "markdown", |
| 153 | + "metadata": {}, |
| 154 | + "source": [ |
| 155 | + "### Spectral embedding for non-linear dimensionality reduction\n\nThis implementation uses Laplacian Eigenmaps, which finds a low dimensional\nrepresentation of the data using a spectral decomposition of the graph Laplacian.\nRead more in the `User Guide <spectral_embedding>`.\n\n" |
| 156 | + ] |
| 157 | + }, |
| 158 | + { |
| 159 | + "cell_type": "code", |
| 160 | + "execution_count": null, |
| 161 | + "metadata": { |
| 162 | + "collapsed": false |
| 163 | + }, |
| 164 | + "outputs": [], |
| 165 | + "source": [ |
| 166 | + "spectral = manifold.SpectralEmbedding(\n n_components=n_components, n_neighbors=n_neighbors\n)\nS_spectral = spectral.fit_transform(S_points)\n\nplot_2d(S_spectral, S_color, \"Spectral Embedding\")" |
| 167 | + ] |
| 168 | + }, |
| 169 | + { |
| 170 | + "cell_type": "markdown", |
| 171 | + "metadata": {}, |
| 172 | + "source": [ |
| 173 | + "### T-distributed Stochastic Neighbor Embedding\n\nIt converts similarities between data points to joint probabilities and\ntries to minimize the Kullback-Leibler divergence between the joint probabilities\nof the low-dimensional embedding and the high-dimensional data. t-SNE has a cost\nfunction that is not convex, i.e. with different initializations we can get\ndifferent results. Read more in the `User Guide <t_sne>`.\n\n" |
| 174 | + ] |
| 175 | + }, |
| 176 | + { |
| 177 | + "cell_type": "code", |
| 178 | + "execution_count": null, |
| 179 | + "metadata": { |
| 180 | + "collapsed": false |
| 181 | + }, |
| 182 | + "outputs": [], |
| 183 | + "source": [ |
| 184 | + "t_sne = manifold.TSNE(\n n_components=n_components,\n learning_rate=\"auto\",\n perplexity=30,\n n_iter=250,\n init=\"random\",\n random_state=rng,\n)\nS_t_sne = t_sne.fit_transform(S_points)\n\nplot_2d(S_t_sne, S_color, \"T-distributed Stochastic \\n Neighbor Embedding\")" |
30 | 185 | ]
|
31 | 186 | }
|
32 | 187 | ],
|
|
0 commit comments