Format: application/octet-stream
⬇ Download File (14.1 KB)
   1  {
   2   "cells": [
   3    {
   4     "cell_type": "markdown",
   5     "metadata": {},
   6     "source": [
   7      "# Applied Machine Learning: Unsupervised Learning"
   8     ]
   9    },
  10    {
  11     "cell_type": "markdown",
  12     "metadata": {},
  13     "source": [
  14      "## Preamble and Datasets"
  15     ]
  16    },
  17    {
  18     "cell_type": "code",
  19     "execution_count": null,
  20     "metadata": {},
  21     "outputs": [],
  22     "source": [
  23      "%matplotlib notebook\n",
  24      "import numpy as np\n",
  25      "import pandas as pd\n",
  26      "import seaborn as sn\n",
  27      "import matplotlib.pyplot as plt\n",
  28      "from sklearn.datasets import load_breast_cancer\n",
  29      "\n",
  30      "# Breast cancer dataset\n",
  31      "cancer = load_breast_cancer()\n",
  32      "(X_cancer, y_cancer) = load_breast_cancer(return_X_y = True)\n",
  33      "\n",
  34      "# Our sample fruits dataset\n",
  35      "fruits = pd.read_table('fruit_data_with_colors.txt')\n",
  36      "X_fruits = fruits[['mass','width','height', 'color_score']]\n",
  37      "y_fruits = fruits[['fruit_label']] - 1"
  38     ]
  39    },
  40    {
  41     "cell_type": "markdown",
  42     "metadata": {},
  43     "source": [
  44      "## Dimensionality Reduction and Manifold Learning"
  45     ]
  46    },
  47    {
  48     "cell_type": "markdown",
  49     "metadata": {},
  50     "source": [
  51      "### Principal Components Analysis (PCA)"
  52     ]
  53    },
  54    {
  55     "cell_type": "markdown",
  56     "metadata": {},
  57     "source": [
  58      "#### Using PCA to find the first two principal components of the breast cancer dataset"
  59     ]
  60    },
  61    {
  62     "cell_type": "code",
  63     "execution_count": null,
  64     "metadata": {},
  65     "outputs": [],
  66     "source": [
  67      "from sklearn.preprocessing import StandardScaler\n",
  68      "from sklearn.decomposition import PCA\n",
  69      "from sklearn.datasets import load_breast_cancer\n",
  70      "\n",
  71      "cancer = load_breast_cancer()\n",
  72      "(X_cancer, y_cancer) = load_breast_cancer(return_X_y = True)\n",
  73      "\n",
  74      "# Before applying PCA, each feature should be centered (zero mean) and with unit variance\n",
  75      "X_normalized = StandardScaler().fit(X_cancer).transform(X_cancer)  \n",
  76      "\n",
  77      "pca = PCA(n_components = 2).fit(X_normalized)\n",
  78      "\n",
  79      "X_pca = pca.transform(X_normalized)\n",
  80      "print(X_cancer.shape, X_pca.shape)"
  81     ]
  82    },
  83    {
  84     "cell_type": "markdown",
  85     "metadata": {},
  86     "source": [
  87      "#### Plotting the PCA-transformed version of the breast cancer dataset"
  88     ]
  89    },
  90    {
  91     "cell_type": "code",
  92     "execution_count": null,
  93     "metadata": {},
  94     "outputs": [],
  95     "source": [
  96      "from adspy_shared_utilities import plot_labelled_scatter\n",
  97      "plot_labelled_scatter(X_pca, y_cancer, ['malignant', 'benign'])\n",
  98      "\n",
  99      "plt.xlabel('First principal component')\n",
 100      "plt.ylabel('Second principal component')\n",
 101      "plt.title('Breast Cancer Dataset PCA (n_components = 2)');"
 102     ]
 103    },
 104    {
 105     "cell_type": "markdown",
 106     "metadata": {},
 107     "source": [
 108      "#### Plotting the magnitude of each feature value for the first two principal components"
 109     ]
 110    },
 111    {
 112     "cell_type": "code",
 113     "execution_count": null,
 114     "metadata": {},
 115     "outputs": [],
 116     "source": [
 117      "fig = plt.figure(figsize=(8, 4))\n",
 118      "plt.imshow(pca.components_, interpolation = 'none', cmap = 'plasma')\n",
 119      "feature_names = list(cancer.feature_names)\n",
 120      "\n",
 121      "plt.gca().set_xticks(np.arange(-.5, len(feature_names)));\n",
 122      "plt.gca().set_yticks(np.arange(0.5, 2));\n",
 123      "plt.gca().set_xticklabels(feature_names, rotation=90, ha='left', fontsize=12);\n",
 124      "plt.gca().set_yticklabels(['First PC', 'Second PC'], va='bottom', fontsize=12);\n",
 125      "\n",
 126      "plt.colorbar(orientation='horizontal', ticks=[pca.components_.min(), 0, \n",
 127      "                                              pca.components_.max()], pad=0.65);"
 128     ]
 129    },
 130    {
 131     "cell_type": "markdown",
 132     "metadata": {},
 133     "source": [
 134      "#### PCA on the fruit dataset (for comparison)"
 135     ]
 136    },
 137    {
 138     "cell_type": "code",
 139     "execution_count": null,
 140     "metadata": {},
 141     "outputs": [],
 142     "source": [
 143      "from sklearn.preprocessing import StandardScaler\n",
 144      "from sklearn.decomposition import PCA\n",
 145      "\n",
 146      "# each feature should be centered (zero mean) and with unit variance\n",
 147      "X_normalized = StandardScaler().fit(X_fruits).transform(X_fruits)  \n",
 148      "\n",
 149      "pca = PCA(n_components = 2).fit(X_normalized)\n",
 150      "X_pca = pca.transform(X_normalized)\n",
 151      "\n",
 152      "from adspy_shared_utilities import plot_labelled_scatter\n",
 153      "plot_labelled_scatter(X_pca, y_fruits, ['apple','mandarin','orange','lemon'])\n",
 154      "\n",
 155      "plt.xlabel('First principal component')\n",
 156      "plt.ylabel('Second principal component')\n",
 157      "plt.title('Fruits Dataset PCA (n_components = 2)');"
 158     ]
 159    },
 160    {
 161     "cell_type": "markdown",
 162     "metadata": {},
 163     "source": [
 164      "### Manifold learning methods"
 165     ]
 166    },
 167    {
 168     "cell_type": "markdown",
 169     "metadata": {},
 170     "source": [
 171      "#### Multidimensional scaling (MDS) on the fruit dataset"
 172     ]
 173    },
 174    {
 175     "cell_type": "code",
 176     "execution_count": null,
 177     "metadata": {},
 178     "outputs": [],
 179     "source": [
 180      "from adspy_shared_utilities import plot_labelled_scatter\n",
 181      "from sklearn.preprocessing import StandardScaler\n",
 182      "from sklearn.manifold import MDS\n",
 183      "\n",
 184      "# each feature should be centered (zero mean) and with unit variance\n",
 185      "X_fruits_normalized = StandardScaler().fit(X_fruits).transform(X_fruits)  \n",
 186      "\n",
 187      "mds = MDS(n_components = 2)\n",
 188      "\n",
 189      "X_fruits_mds = mds.fit_transform(X_fruits_normalized)\n",
 190      "\n",
 191      "plot_labelled_scatter(X_fruits_mds, y_fruits, ['apple', 'mandarin', 'orange', 'lemon'])\n",
 192      "plt.xlabel('First MDS feature')\n",
 193      "plt.ylabel('Second MDS feature')\n",
 194      "plt.title('Fruit sample dataset MDS');"
 195     ]
 196    },
 197    {
 198     "cell_type": "markdown",
 199     "metadata": {},
 200     "source": [
 201      "#### Multidimensional scaling (MDS) on the breast cancer dataset"
 202     ]
 203    },
 204    {
 205     "cell_type": "markdown",
 206     "metadata": {},
 207     "source": [
 208      "(This example is not covered in the lecture video, but is included here so you can compare it to the results from PCA.)"
 209     ]
 210    },
 211    {
 212     "cell_type": "code",
 213     "execution_count": null,
 214     "metadata": {},
 215     "outputs": [],
 216     "source": [
 217      "from sklearn.preprocessing import StandardScaler\n",
 218      "from sklearn.manifold import MDS\n",
 219      "from sklearn.datasets import load_breast_cancer\n",
 220      "\n",
 221      "cancer = load_breast_cancer()\n",
 222      "(X_cancer, y_cancer) = load_breast_cancer(return_X_y = True)\n",
 223      "\n",
 224      "# each feature should be centered (zero mean) and with unit variance\n",
 225      "X_normalized = StandardScaler().fit(X_cancer).transform(X_cancer)  \n",
 226      "\n",
 227      "mds = MDS(n_components = 2)\n",
 228      "\n",
 229      "X_mds = mds.fit_transform(X_normalized)\n",
 230      "\n",
 231      "from adspy_shared_utilities import plot_labelled_scatter\n",
 232      "plot_labelled_scatter(X_mds, y_cancer, ['malignant', 'benign'])\n",
 233      "\n",
 234      "plt.xlabel('First MDS dimension')\n",
 235      "plt.ylabel('Second MDS dimension')\n",
 236      "plt.title('Breast Cancer Dataset MDS (n_components = 2)');"
 237     ]
 238    },
 239    {
 240     "cell_type": "markdown",
 241     "metadata": {
 242      "collapsed": true
 243     },
 244     "source": [
 245      "#### t-SNE on the fruit dataset"
 246     ]
 247    },
 248    {
 249     "cell_type": "markdown",
 250     "metadata": {},
 251     "source": [
 252      "(This example from the lecture video is included so that you can see how some dimensionality reduction methods may be less successful on some datasets. Here, it doesn't work as well at finding structure in the small fruits dataset, compared to other methods like MDS.)"
 253     ]
 254    },
 255    {
 256     "cell_type": "code",
 257     "execution_count": null,
 258     "metadata": {},
 259     "outputs": [],
 260     "source": [
 261      "from sklearn.manifold import TSNE\n",
 262      "\n",
 263      "tsne = TSNE(random_state = 0)\n",
 264      "\n",
 265      "X_tsne = tsne.fit_transform(X_fruits_normalized)\n",
 266      "\n",
 267      "plot_labelled_scatter(X_tsne, y_fruits, \n",
 268      "    ['apple', 'mandarin', 'orange', 'lemon'])\n",
 269      "plt.xlabel('First t-SNE feature')\n",
 270      "plt.ylabel('Second t-SNE feature')\n",
 271      "plt.title('Fruits dataset t-SNE');"
 272     ]
 273    },
 274    {
 275     "cell_type": "markdown",
 276     "metadata": {},
 277     "source": [
 278      "#### t-SNE on the breast cancer dataset"
 279     ]
 280    },
 281    {
 282     "cell_type": "markdown",
 283     "metadata": {},
 284     "source": [
 285      "Although not shown in the lecture video, this example is included for comparison, showing the results of running t-SNE on the breast cancer dataset.  See the reading \"How to Use t-SNE effectively\" for further details on how the visualizations from t-SNE are affected by specific parameter settings."
 286     ]
 287    },
 288    {
 289     "cell_type": "code",
 290     "execution_count": null,
 291     "metadata": {},
 292     "outputs": [],
 293     "source": [
 294      "tsne = TSNE(random_state = 0)\n",
 295      "\n",
 296      "X_tsne = tsne.fit_transform(X_normalized)\n",
 297      "\n",
 298      "plot_labelled_scatter(X_tsne, y_cancer, \n",
 299      "    ['malignant', 'benign'])\n",
 300      "plt.xlabel('First t-SNE feature')\n",
 301      "plt.ylabel('Second t-SNE feature')\n",
 302      "plt.title('Breast cancer dataset t-SNE');"
 303     ]
 304    },
 305    {
 306     "cell_type": "markdown",
 307     "metadata": {},
 308     "source": [
 309      "## Clustering"
 310     ]
 311    },
 312    {
 313     "cell_type": "markdown",
 314     "metadata": {
 315      "collapsed": true
 316     },
 317     "source": [
 318      "### K-means"
 319     ]
 320    },
 321    {
 322     "cell_type": "markdown",
 323     "metadata": {},
 324     "source": [
 325      "This example from the lecture video creates an artificial dataset with make_blobs, then applies k-means to find 3 clusters, and plots the points in each cluster identified by a corresponding color."
 326     ]
 327    },
 328    {
 329     "cell_type": "code",
 330     "execution_count": null,
 331     "metadata": {},
 332     "outputs": [],
 333     "source": [
 334      "from sklearn.datasets import make_blobs\n",
 335      "from sklearn.cluster import KMeans\n",
 336      "from adspy_shared_utilities import plot_labelled_scatter\n",
 337      "\n",
 338      "X, y = make_blobs(random_state = 10)\n",
 339      "\n",
 340      "kmeans = KMeans(n_clusters = 3)\n",
 341      "kmeans.fit(X)\n",
 342      "\n",
 343      "plot_labelled_scatter(X, kmeans.labels_, ['Cluster 1', 'Cluster 2', 'Cluster 3'])\n"
 344     ]
 345    },
 346    {
 347     "cell_type": "markdown",
 348     "metadata": {},
 349     "source": [
 350      "Example showing k-means used to find 4 clusters in the fruits dataset.  Note that in general, it's important to scale the individual features before applying k-means clustering."
 351     ]
 352    },
 353    {
 354     "cell_type": "code",
 355     "execution_count": null,
 356     "metadata": {},
 357     "outputs": [],
 358     "source": [
 359      "from sklearn.datasets import make_blobs\n",
 360      "from sklearn.cluster import KMeans\n",
 361      "from adspy_shared_utilities import plot_labelled_scatter\n",
 362      "from sklearn.preprocessing import MinMaxScaler\n",
 363      "\n",
 364      "fruits = pd.read_table('fruit_data_with_colors.txt')\n",
 365      "X_fruits = fruits[['mass','width','height', 'color_score']].as_matrix()\n",
 366      "y_fruits = fruits[['fruit_label']] - 1\n",
 367      "\n",
 368      "X_fruits_normalized = MinMaxScaler().fit(X_fruits).transform(X_fruits)  \n",
 369      "\n",
 370      "kmeans = KMeans(n_clusters = 4, random_state = 0)\n",
 371      "kmeans.fit(X_fruits)\n",
 372      "\n",
 373      "plot_labelled_scatter(X_fruits_normalized, kmeans.labels_, \n",
 374      "                      ['Cluster 1', 'Cluster 2', 'Cluster 3', 'Cluster 4'])"
 375     ]
 376    },
 377    {
 378     "cell_type": "markdown",
 379     "metadata": {},
 380     "source": [
 381      "### Agglomerative clustering"
 382     ]
 383    },
 384    {
 385     "cell_type": "code",
 386     "execution_count": null,
 387     "metadata": {
 388      "scrolled": false
 389     },
 390     "outputs": [],
 391     "source": [
 392      "from sklearn.datasets import make_blobs\n",
 393      "from sklearn.cluster import AgglomerativeClustering\n",
 394      "from adspy_shared_utilities import plot_labelled_scatter\n",
 395      "\n",
 396      "X, y = make_blobs(random_state = 10)\n",
 397      "\n",
 398      "cls = AgglomerativeClustering(n_clusters = 3)\n",
 399      "cls_assignment = cls.fit_predict(X)\n",
 400      "\n",
 401      "plot_labelled_scatter(X, cls_assignment, \n",
 402      "        ['Cluster 1', 'Cluster 2', 'Cluster 3'])"
 403     ]
 404    },
 405    {
 406     "cell_type": "markdown",
 407     "metadata": {},
 408     "source": [
 409      "#### Creating a dendrogram (using scipy)"
 410     ]
 411    },
 412    {
 413     "cell_type": "markdown",
 414     "metadata": {},
 415     "source": [
 416      "This dendrogram plot is based on the dataset created in the previous step with make_blobs, but for clarity, only 10 samples have been selected for this example, as plotted here:"
 417     ]
 418    },
 419    {
 420     "cell_type": "code",
 421     "execution_count": null,
 422     "metadata": {},
 423     "outputs": [],
 424     "source": [
 425      "X, y = make_blobs(random_state = 10, n_samples = 10)\n",
 426      "plot_labelled_scatter(X, y, \n",
 427      "        ['Cluster 1', 'Cluster 2', 'Cluster 3'])\n",
 428      "print(X)"
 429     ]
 430    },
 431    {
 432     "cell_type": "markdown",
 433     "metadata": {},
 434     "source": [
 435      "And here's the dendrogram corresponding to agglomerative clustering of the 10 points above using Ward's method.  The index 0..9 of the points corresponds to the index of the points in the X array above.  For example, point 0 (5.69, -9.47) and point 9 (5.43, -9.76) are the closest two points and are clustered first."
 436     ]
 437    },
 438    {
 439     "cell_type": "code",
 440     "execution_count": null,
 441     "metadata": {},
 442     "outputs": [],
 443     "source": [
 444      "from scipy.cluster.hierarchy import ward, dendrogram\n",
 445      "plt.figure()\n",
 446      "dendrogram(ward(X))\n",
 447      "plt.show()"
 448     ]
 449    },
 450    {
 451     "cell_type": "markdown",
 452     "metadata": {},
 453     "source": [
 454      "### DBSCAN clustering"
 455     ]
 456    },
 457    {
 458     "cell_type": "code",
 459     "execution_count": null,
 460     "metadata": {},
 461     "outputs": [],
 462     "source": [
 463      "from sklearn.cluster import DBSCAN\n",
 464      "from sklearn.datasets import make_blobs\n",
 465      "\n",
 466      "X, y = make_blobs(random_state = 9, n_samples = 25)\n",
 467      "\n",
 468      "dbscan = DBSCAN(eps = 2, min_samples = 2)\n",
 469      "\n",
 470      "cls = dbscan.fit_predict(X)\n",
 471      "print(\"Cluster membership values:\\n{}\".format(cls))\n",
 472      "\n",
 473      "plot_labelled_scatter(X, cls + 1, \n",
 474      "        ['Noise', 'Cluster 0', 'Cluster 1', 'Cluster 2'])"
 475     ]
 476    },
 477    {
 478     "cell_type": "code",
 479     "execution_count": null,
 480     "metadata": {
 481      "collapsed": true
 482     },
 483     "outputs": [],
 484     "source": []
 485    }
 486   ],
 487   "metadata": {
 488    "anaconda-cloud": {},
 489    "kernelspec": {
 490     "display_name": "Python [conda env:NotebookRecording]",
 491     "language": "python",
 492     "name": "conda-env-NotebookRecording-py"
 493    },
 494    "language_info": {
 495     "codemirror_mode": {
 496      "name": "ipython",
 497      "version": 3
 498     },
 499     "file_extension": ".py",
 500     "mimetype": "text/x-python",
 501     "name": "python",
 502     "nbconvert_exporter": "python",
 503     "pygments_lexer": "ipython3",
 504     "version": "3.5.3"
 505    }
 506   },
 507   "nbformat": 4,
 508   "nbformat_minor": 1
 509  }
 510