{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "import numpy as np\n",
    "import matplotlib.pyplot as plt\n",
    "from sklearn.feature_extraction.image import img_to_graph\n",
    "from sklearn.cluster import spectral_clustering\n",
    "from sklearn.datasets import load_digits"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "digits = load_digits()\n",
    "img = digits.images[0].astype(float)\n",
    "mask = img.astype(bool)\n",
    "\n",
    "graph = img_to_graph(img, mask=mask)\n",
    "graph.data = np.exp(-graph.data/graph.data.std())"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "labels = spectral_clustering(graph, n_clusters=3)\n",
    "label_im = -np.ones(mask.shape)\n",
    "label_im[mask] = labels"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "%matplotlib inline\n",
    "plt.matshow(img, False)\n",
    "plt.gca().axis('off')\n",
    "plt.title('Original')\n",
    "\n",
    "plt.figure()\n",
    "plt.matshow(label_im, False)\n",
    "plt.gca().axis('off')\n",
    "plt.title('Clustered')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": []
  }
 ],
 "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.4.3"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 0
}
