<commit_before>{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Similarity Queries using Annoy Tutorial"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "This tutorial is about using the [Annoy(Approximate Nearest Neighbors Oh Yeah)]((https://github.com/spotify/annoy \"Link to annoy repo\") library for similarity queries in gensim"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Why use Annoy?\n",
    "The current implementation for finding k nearest neighbors in a vector space in gensim has linear complexity via brute force in the number of indexed documents, although with extremely low constant factors. The retrieved results are exact, which is an overkill in many applications: approximate results retrieved in sub-linear time may be enough. Annoy can find approximate nearest neighbors much faster."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "For the following examples, we'll use the Lee Corpus (which you already have if you've installed gensim)\n",
    "\n",
    "See the [Word2Vec tutorial](https://github.com/RaRe-Technologies/gensim/blob/develop/docs/notebooks/word2vec.ipynb) for how to initialize and save this model."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Word2Vec(vocab=6981, size=100, alpha=0.025)\n"
     ]
    }
   ],
   "source": [
    "# Load the model\n",
    "import gensim, os\n",
    "from gensim.models.word2vec import Word2Vec\n",
    "\n",
    "# Set file names for train and test data\n",
    "test_data_dir = '{}'.format(os.sep).join([gensim.__path__[0], 'test', 'test_data']) + os.sep\n",
    "lee_train_file = test_data_dir + 'lee_background.cor'\n",
    "\n",
    "class MyText(object):\n",
    "    def __iter__(self):\n",
    "        for line in open(lee_train_file):\n",
    "            # assume there's one document per line, tokens separated by whitespace\n",
    "            yield gensim.utils.simple_preprocess(line)\n",
    "\n",
    "sentences = MyText()\n",
    "model = Word2Vec(sentences, min_count=1)\n",
    "print(model)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "\n",
    "#### Comparing the traditional implementation and the Annoy  \n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "These benchmarks are run on a 2.4GHz 4 core i7 processor  "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "#Set up the model and vector that we are using in the comparison\n",
    "try:\n",
    "    from gensim.similarities.index import AnnoyIndexer\n",
    "except ImportError:\n",
    "    raise ValueError(\"SKIP: Please install the annoy indexer\")\n",
    "\n",
    "model.init_sims()\n",
    "annoy_index = AnnoyIndexer(model, 300)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "[(u'the', 1.0),\n",
       " (u'on', 0.999976396560669),\n",
       " (u'in', 0.9999759197235107),\n",
       " (u'two', 0.9999756217002869),\n",
       " (u'after', 0.9999749660491943)]"
      ]
     },
     "execution_count": 3,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# Dry run to make sure both indices are fully in RAM\n",
    "vector = model.wv.syn0norm[0]\n",
    "model.most_similar([vector], topn=5, indexer=annoy_index)\n",
    "model.most_similar([vector], topn=5)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Gensim: 0.002638526\n",
      "Annoy: 0.001149898\n",
      "\n",
      "Annoy is 2.29 times faster on average over 1000 random queries on this particular run\n"
     ]
    }
   ],
   "source": [
    "import time, numpy\n",
    "\n",
    "def avg_query_time(annoy_index=None):\n",
    "    \"\"\"\n",
    "    Average query time of a most_similar method over 1000 random queries,\n",
    "    uses annoy if given an indexer\n",
    "    \"\"\"\n",
    "    total_time = 0\n",
    "    for _ in range(1000):\n",
    "        rand_vec = model.wv.syn0norm[numpy.random.randint(0, len(model.vocab))]\n",
    "        start_time = time.clock()\n",
    "        model.most_similar([rand_vec], topn=5, indexer=annoy_index)\n",
    "        total_time += time.clock() - start_time\n",
    "    return total_time / 1000\n",
    "\n",
    "gensim_time = avg_query_time()\n",
    "annoy_time = avg_query_time(annoy_index)\n",
    "print \"Gensim: {}\".format(gensim_time) \n",
    "print \"Annoy: {}\".format(annoy_time)\n",
    "print \"\\nAnnoy is {} times faster on average over 1000 random queries on \\\n",
    "this particular run\".format(numpy.round(gensim_time / annoy_time, 2))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "\n",
    "**This speedup factor is by no means constant** and will vary greatly from run to run and is particular to this data set, BLAS setup, Annoy parameters(as tree size increases speedup factor decreases), machine specifications, among other factors.\n",
    "\n",
    ">**Note**: Initialization time for the annoy indexer was not included in the times. The optimal knn algorithm for you to use will depend on how many queries you need to make and the size of the corpus. If you are making very few similarity queries, the time taken to initialize the annoy indexer will be longer than the time it would take the brute force method to retrieve results. If you are making many queries however, the time it takes to initialize the annoy indexer will be made up for by the incredibly fast retrieval times for queries once the indexer has been initialized"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## What is Annoy?"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Annoy is an open source library to search for points in space that are close to a given query point. It also creates large read-only file-based data structures that are mmapped into memory so that many processes may share the same data. For our purpose, it is used to find similarity between words or documents in a vector space. [See the tutorial on similarity queries for more information on them](https://github.com/RaRe-Technologies/gensim/blob/develop/docs/notebooks/Similarity_Queries.ipynb)."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Getting Started"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "First thing to do is to install annoy, by running the following in the command line:\n",<commit_msg>Add note about Annoy speed depending on numpy BLAS setup  in annoytutorial.ipynb (#1137)<commit_after>{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Similarity Queries using Annoy Tutorial"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "This tutorial is about using the [Annoy(Approximate Nearest Neighbors Oh Yeah)]((https://github.com/spotify/annoy \"Link to annoy repo\") library for similarity queries in gensim"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Why use Annoy?\n",
    "The current implementation for finding k nearest neighbors in a vector space in gensim has linear complexity via brute force in the number of indexed documents, although with extremely low constant factors. The retrieved results are exact, which is an overkill in many applications: approximate results retrieved in sub-linear time may be enough. Annoy can find approximate nearest neighbors much faster."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "For the following examples, we'll use the Lee Corpus (which you already have if you've installed gensim)\n",
    "\n",
    "See the [Word2Vec tutorial](https://github.com/RaRe-Technologies/gensim/blob/develop/docs/notebooks/word2vec.ipynb) for how to initialize and save this model."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Word2Vec(vocab=6981, size=100, alpha=0.025)\n"
     ]
    }
   ],
   "source": [
    "# Load the model\n",
    "import gensim, os\n",
    "from gensim.models.word2vec import Word2Vec\n",
    "\n",
    "# Set file names for train and test data\n",
    "test_data_dir = '{}'.format(os.sep).join([gensim.__path__[0], 'test', 'test_data']) + os.sep\n",
    "lee_train_file = test_data_dir + 'lee_background.cor'\n",
    "\n",
    "class MyText(object):\n",
    "    def __iter__(self):\n",
    "        for line in open(lee_train_file):\n",
    "            # assume there's one document per line, tokens separated by whitespace\n",
    "            yield gensim.utils.simple_preprocess(line)\n",
    "\n",
    "sentences = MyText()\n",
    "model = Word2Vec(sentences, min_count=1)\n",
    "print(model)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "\n",
    "#### Comparing the traditional implementation and the Annoy  \n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "These benchmarks are run on a 2.4GHz 4 core i7 processor  "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "#Set up the model and vector that we are using in the comparison\n",
    "try:\n",
    "    from gensim.similarities.index import AnnoyIndexer\n",
    "except ImportError:\n",
    "    raise ValueError(\"SKIP: Please install the annoy indexer\")\n",
    "\n",
    "model.init_sims()\n",
    "annoy_index = AnnoyIndexer(model, 300)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "[(u'the', 1.0),\n",
       " (u'on', 0.999976396560669),\n",
       " (u'in', 0.9999759197235107),\n",
       " (u'two', 0.9999756217002869),\n",
       " (u'after', 0.9999749660491943)]"
      ]
     },
     "execution_count": 3,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# Dry run to make sure both indices are fully in RAM\n",
    "vector = model.wv.syn0norm[0]\n",
    "model.most_similar([vector], topn=5, indexer=annoy_index)\n",
    "model.most_similar([vector], topn=5)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Gensim: 0.002638526\n",
      "Annoy: 0.001149898\n",
      "\n",
      "Annoy is 2.29 times faster on average over 1000 random queries on this particular run\n"
     ]
    }
   ],
   "source": [
    "import time, numpy\n",
    "\n",
    "def avg_query_time(annoy_index=None):\n",
    "    \"\"\"\n",
    "    Average query time of a most_similar method over 1000 random queries,\n",
    "    uses annoy if given an indexer\n",
    "    \"\"\"\n",
    "    total_time = 0\n",
    "    for _ in range(1000):\n",
    "        rand_vec = model.wv.syn0norm[numpy.random.randint(0, len(model.vocab))]\n",
    "        start_time = time.clock()\n",
    "        model.most_similar([rand_vec], topn=5, indexer=annoy_index)\n",
    "        total_time += time.clock() - start_time\n",
    "    return total_time / 1000\n",
    "\n",
    "gensim_time = avg_query_time()\n",
    "annoy_time = avg_query_time(annoy_index)\n",
    "print \"Gensim: {}\".format(gensim_time) \n",
    "print \"Annoy: {}\".format(annoy_time)\n",
    "print \"\\nAnnoy is {} times faster on average over 1000 random queries on \\\n",
    "this particular run\".format(numpy.round(gensim_time / annoy_time, 2))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "\n",
    "**This speedup factor is by no means constant** and will vary greatly from run to run and is particular to this data set, BLAS setup, Annoy parameters(as tree size increases speedup factor decreases), machine specifications, among other factors.\n",
    "\n",
    ">**Note**: Initialization time for the annoy indexer was not included in the times. The optimal knn algorithm for you to use will depend on how many queries you need to make and the size of the corpus. If you are making very few similarity queries, the time taken to initialize the annoy indexer will be longer than the time it would take the brute force method to retrieve results. If you are making many queries however, the time it takes to initialize the annoy indexer will be made up for by the incredibly fast retrieval times for queries once the indexer has been initialized\n",
    "\n",
    ">**Note** : Gensim's 'most_similar' method is using numpy operations in the form of dot product whereas Annoy's method isnt. If 'numpy' on your machine is using one of the BLAS libraries like ATLAS or LAPACK, it'll run on multiple cores(only if your machine has multicore support ). Check [SciPy Cookbook](http://scipy-cookbook.readthedocs.io/items/ParallelProgramming.html) for more details."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## What is Annoy?"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Annoy is an open source library to search for points in space that are close to a given query point. It also creates large read-only file-based data structures that are mmapped into memory so that many processes may share the same data. For our purpose, it is used to find similarity between words or documents in a vector space. [See the tutorial on similarity queries for more information on them](https://github.com/RaRe-Technologies/gensim/blob/develop/docs/notebooks/Similarity_Queries.ipynb)."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Getting Started"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "First thing to do is to install annoy, by running the following in the command line:\n",
{'fraction_non_alphanumeric': 0.14877731351462428, 'fraction_numerical': 0.02109733543393383, 'mean_word_length': 2.8933333333333335, 'pattern_counts': {'":': 138, '<': 3, '<?xml version=': 0, '>': 6, 'https://': 6, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '1989107', 'n_tokens_mistral': 5088, 'n_tokens_neox': 4789, 'n_words': 1435}