{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "from sklearn.metrics.pairwise import cosine_similarity\n",
    "import networkx as nx\n",
    "import matplotlib.pyplot as plt\n",
    "import numpy as np\n",
    "import dautil as dl\n",
    "import ch8util"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "context = dl.nb.Context('cos_similarity')\n",
    "lr = dl.nb.LatexRenderer(chapter=8, start=8, context=context)\n",
    "lr.render(r'k(x, y) = \\frac{x y^\\top}{\\|x\\| \\|y\\|}')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "def add_nodes(G, nodes, start, terms):\n",
    "    for n in nodes:\n",
    "        words = top_3_words(tfidf, n, terms)\n",
    "        G.add_node(n, words='{0}: {1}'.\n",
    "                   format(n, \" \".join(words.tolist())))\n",
    "        G.add_edge(start, n)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "def top_3_words(tfidf, row, terms):\n",
    "    indices = np.argsort(tfidf[row].toarray().ravel())[-3:]\n",
    "\n",
    "    return terms[indices]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "tfidf = ch8util.load_tfidf()\n",
    "terms = ch8util.load_terms()\n",
    "\n",
    "sims = cosine_similarity(tfidf, tfidf)\n",
    "G = nx.Graph()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "for i, row in enumerate(sims):\n",
    "    over_limit = np.where(row > np.percentile(row, 90))[0]\n",
    "    nodes = set(over_limit.tolist())\n",
    "    nodes.remove(i)\n",
    "    add_nodes(G, nodes, i, terms)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "%matplotlib inline\n",
    "dl.nb.RcWidget(context)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "labels = nx.get_node_attributes(G, 'words')\n",
    "nx.draw_networkx(G, pos=nx.spring_layout(G), labels=labels)\n",
    "plt.axis('off')\n",
    "plt.title('Graph of News Articles in the Brown Corpus')\n",
    "print('Density', nx.density(G))\n",
    "print('Average Clustering',\n",
    "      nx.average_clustering(G))\n",
    "print('Degree Assortativity Coefficient',\n",
    "      nx.degree_assortativity_coefficient(G))\n",
    "print('Graph Clique Number', nx.graph_clique_number(G))"
   ]
  },
  {
   "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
}
