{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "# Word2Vec Tutorial\n", "\n", "In case you missed the buzz, word2vec is a widely featured as a member of the “new wave” of machine learning algorithms based on neural networks, commonly referred to as \"deep learning\" (though word2vec itself is rather shallow). Using large amounts of unannotated plain text, word2vec learns relationships between words automatically. The output are vectors, one vector per word, with remarkable linear relationships that allow us to do things like vec(“king”) – vec(“man”) + vec(“woman”) =~ vec(“queen”), or vec(“Montreal Canadiens”) – vec(“Montreal”) + vec(“Toronto”) resembles the vector for “Toronto Maple Leafs”.\n", "\n", "Word2vec is very useful in [automatic text tagging](https://github.com/RaRe-Technologies/movie-plots-by-genre), recommender systems and machine translation.\n", "\n", "Check out an [online word2vec demo](http://radimrehurek.com/2014/02/word2vec-tutorial/#app) where you can try this vector algebra for yourself. That demo runs `word2vec` on the Google News dataset, of **about 100 billion words**.\n", "\n", "## This tutorial\n", "\n", "In this tutorial you will learn how to train and evaluate word2vec models on your business data.\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Preparing the Input\n", "Starting from the beginning, gensim’s `word2vec` expects a sequence of sentences as its input. Each sentence a list of words (utf8 strings):" ] }, { "cell_type": "code", "execution_count": 1, "metadata": {}, "outputs": [], "source": [ "# import modules & set up logging\n", "import gensim, logging\n", "logging.basicConfig(format='%(asctime)s : %(levelname)s : %(message)s', level=logging.INFO)" ] }, { "cell_type": "code", "execution_count": 2, "metadata": {}, "outputs": [ { "name": "stderr", "output_type": "stream", "text": [ "2017-05-07 14:19:35,470 : INFO : collecting all words and their counts\n", "2017-05-07 14:19:35,473 : INFO : PROGRESS: at sentence #0, processed 0 words, keeping 0 word types\n", "2017-05-07 14:19:35,474 : INFO : collected 3 word types from a corpus of 4 raw words and 2 sentences\n", "2017-05-07 14:19:35,476 : INFO : Loading a fresh vocabulary\n", "2017-05-07 14:19:35,477 : INFO : min_count=1 retains 3 unique words (100% of original 3, drops 0)\n", "2017-05-07 14:19:35,478 : INFO : min_count=1 leaves 4 word corpus (100% of original 4, drops 0)\n", "2017-05-07 14:19:35,480 : INFO : deleting the raw counts dictionary of 3 items\n", "2017-05-07 14:19:35,481 : INFO : sample=0.001 downsamples 3 most-common words\n", "2017-05-07 14:19:35,483 : INFO : downsampling leaves estimated 0 word corpus (5.7% of prior 4)\n", "2017-05-07 14:19:35,484 : INFO : estimated required memory for 3 words and 100 dimensions: 3900 bytes\n", "2017-05-07 14:19:35,485 : INFO : resetting layer weights\n", "2017-05-07 14:19:35,487 : INFO : training model with 3 workers on 3 vocabulary and 100 features, using sg=0 hs=0 sample=0.001 negative=5 window=5\n", "2017-05-07 14:19:35,490 : INFO : worker thread finished; awaiting finish of 2 more threads\n", "2017-05-07 14:19:35,490 : INFO : worker thread finished; awaiting finish of 1 more threads\n", "2017-05-07 14:19:35,492 : INFO : worker thread finished; awaiting finish of 0 more threads\n", "2017-05-07 14:19:35,494 : INFO : training on 20 raw words (0 effective words) took 0.0s, 0 effective words/s\n", "2017-05-07 14:19:35,497 : WARNING : under 10 jobs per worker: consider setting a smaller `batch_words' for smoother alpha decay\n" ] } ], "source": [ "sentences = [['first', 'sentence'], ['second', 'sentence']]\n", "# train word2vec on the two sentences\n", "model = gensim.models.Word2Vec(sentences, min_count=1)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Keeping the input as a Python built-in list is convenient, but can use up a lot of RAM when the input is large.\n", "\n", "Gensim only requires that the input must provide sentences sequentially, when iterated over. No need to keep everything in RAM: we can provide one sentence, process it, forget it, load another sentence…\n", "\n", "For example, if our input is strewn across several files on disk, with one sentence per line, then instead of loading everything into an in-memory list, we can process the input file by file, line by line:" ] }, { "cell_type": "code", "execution_count": 3, "metadata": { "collapsed": true }, "outputs": [], "source": [ "# create some toy data to use with the following example\n", "import smart_open, os\n", "\n", "if not os.path.exists('./data/'):\n", " os.makedirs('./data/')\n", "\n", "filenames = ['./data/f1.txt', './data/f2.txt']\n", "\n", "for i, fname in enumerate(filenames):\n", " with smart_open.smart_open(fname, 'w') as fout:\n", " for line in sentences[i]:\n", " fout.write(line + '\\n')" ] }, { "cell_type": "code", "execution_count": 4, "metadata": { "collapsed": true }, "outputs": [], "source": [ "class MySentences(object):\n", " def __init__(self, dirname):\n", " self.dirname = dirname\n", " \n", " def __iter__(self):\n", " for fname in os.listdir(self.dirname):\n", " for line in open(os.path.join(self.dirname, fname)):\n", " yield line.split()" ] }, { "cell_type": "code", "execution_count": 5, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "[['first'], ['sentence'], ['second'], ['sentence']]\n" ] } ], "source": [ "sentences = MySentences('./data/') # a memory-friendly iterator\n", "print(list(sentences))" ] }, { "cell_type": "code", "execution_count": 6, "metadata": {}, "outputs": [ { "name": "stderr", "output_type": "stream", "text": [ "2017-05-07 14:19:35,568 : INFO : collecting all words and their counts\n", "2017-05-07 14:19:35,574 : INFO : PROGRESS: at sentence #0, processed 0 words, keeping 0 word types\n", "2017-05-07 14:19:35,578 : INFO : collected 3 word types from a corpus of 4 raw words and 4 sentences\n", "2017-05-07 14:19:35,579 : INFO : Loading a fresh vocabulary\n", "2017-05-07 14:19:35,582 : INFO : min_count=1 retains 3 unique words (100% of original 3, drops 0)\n", "2017-05-07 14:19:35,587 : INFO : min_count=1 leaves 4 word corpus (100% of original 4, drops 0)\n", "2017-05-07 14:19:35,588 : INFO : deleting the raw counts dictionary of 3 items\n", "2017-05-07 14:19:35,589 : INFO : sample=0.001 downsamples 3 most-common words\n", "2017-05-07 14:19:35,590 : INFO : downsampling leaves estimated 0 word corpus (5.7% of prior 4)\n", "2017-05-07 14:19:35,594 : INFO : estimated required memory for 3 words and 100 dimensions: 3900 bytes\n", "2017-05-07 14:19:35,595 : INFO : resetting layer weights\n", "2017-05-07 14:19:35,598 : INFO : training model with 3 workers on 3 vocabulary and 100 features, using sg=0 hs=0 sample=0.001 negative=5 window=5\n", "2017-05-07 14:19:35,603 : INFO : worker thread finished; awaiting finish of 2 more threads\n", "2017-05-07 14:19:35,605 : INFO : worker thread finished; awaiting finish of 1 more threads\n", "2017-05-07 14:19:35,606 : INFO : worker thread finished; awaiting finish of 0 more threads\n", "2017-05-07 14:19:35,607 : INFO : training on 20 raw words (0 effective words) took 0.0s, 0 effective words/s\n", "2017-05-07 14:19:35,609 : WARNING : under 10 jobs per worker: consider setting a smaller `batch_words' for smoother alpha decay\n" ] } ], "source": [ "# generate the Word2Vec model\n", "model = gensim.models.Word2Vec(sentences, min_count=1)" ] }, { "cell_type": "code", "execution_count": 7, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Word2Vec(vocab=3, size=100, alpha=0.025)\n", "{'second': , 'first': , 'sentence': }\n" ] } ], "source": [ "print(model)\n", "print(model.wv.vocab)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Say we want to further preprocess the words from the files — convert to unicode, lowercase, remove numbers, extract named entities… All of this can be done inside the `MySentences` iterator and `word2vec` doesn’t need to know. All that is required is that the input yields one sentence (list of utf8 words) after another.\n", "\n", "**Note to advanced users:** calling `Word2Vec(sentences, iter=1)` will run **two** passes over the sentences iterator. In general it runs `iter+1` passes. By the way, the default value is `iter=5` to comply with Google's word2vec in C language. \n", " 1. The first pass collects words and their frequencies to build an internal dictionary tree structure. \n", " 2. The second pass trains the neural model.\n", "\n", "These two passes can also be initiated manually, in case your input stream is non-repeatable (you can only afford one pass), and you’re able to initialize the vocabulary some other way:" ] }, { "cell_type": "code", "execution_count": 8, "metadata": {}, "outputs": [ { "name": "stderr", "output_type": "stream", "text": [ "2017-05-07 14:19:35,636 : INFO : collecting all words and their counts\n", "2017-05-07 14:19:35,638 : INFO : PROGRESS: at sentence #0, processed 0 words, keeping 0 word types\n", "2017-05-07 14:19:35,640 : INFO : collected 3 word types from a corpus of 4 raw words and 4 sentences\n", "2017-05-07 14:19:35,641 : INFO : Loading a fresh vocabulary\n", "2017-05-07 14:19:35,644 : INFO : min_count=1 retains 3 unique words (100% of original 3, drops 0)\n", "2017-05-07 14:19:35,645 : INFO : min_count=1 leaves 4 word corpus (100% of original 4, drops 0)\n", "2017-05-07 14:19:35,646 : INFO : deleting the raw counts dictionary of 3 items\n", "2017-05-07 14:19:35,647 : INFO : sample=0.001 downsamples 3 most-common words\n", "2017-05-07 14:19:35,649 : INFO : downsampling leaves estimated 0 word corpus (5.7% of prior 4)\n", "2017-05-07 14:19:35,650 : INFO : estimated required memory for 3 words and 100 dimensions: 3900 bytes\n", "2017-05-07 14:19:35,651 : INFO : resetting layer weights\n", "2017-05-07 14:19:35,653 : INFO : training model with 3 workers on 3 vocabulary and 100 features, using sg=0 hs=0 sample=0.001 negative=5 window=5\n", "2017-05-07 14:19:35,656 : INFO : worker thread finished; awaiting finish of 2 more threads\n", "2017-05-07 14:19:35,657 : INFO : worker thread finished; awaiting finish of 1 more threads\n", "2017-05-07 14:19:35,658 : INFO : worker thread finished; awaiting finish of 0 more threads\n", "2017-05-07 14:19:35,660 : INFO : training on 20 raw words (0 effective words) took 0.0s, 0 effective words/s\n", "2017-05-07 14:19:35,662 : WARNING : under 10 jobs per worker: consider setting a smaller `batch_words' for smoother alpha decay\n" ] }, { "data": { "text/plain": [ "0" ] }, "execution_count": 8, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# build the same model, making the 2 steps explicit\n", "new_model = gensim.models.Word2Vec(min_count=1) # an empty model, no training\n", "new_model.build_vocab(sentences) # can be a non-repeatable, 1-pass generator \n", "new_model.train(sentences, total_examples=new_model.corpus_count, epochs=new_model.iter) \n", "# can be a non-repeatable, 1-pass generator" ] }, { "cell_type": "code", "execution_count": 9, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Word2Vec(vocab=3, size=100, alpha=0.025)\n", "{'second': , 'first': , 'sentence': }\n" ] } ], "source": [ "print(new_model)\n", "print(model.wv.vocab)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## More data would be nice\n", "For the following examples, we'll use the [Lee Corpus](https://github.com/RaRe-Technologies/gensim/blob/develop/gensim/test/test_data/lee_background.cor) (which you already have if you've installed gensim):" ] }, { "cell_type": "code", "execution_count": 10, "metadata": { "collapsed": true }, "outputs": [], "source": [ "# 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'" ] }, { "cell_type": "code", "execution_count": 11, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "<__main__.MyText object at 0x106c65b50>\n" ] } ], "source": [ "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 line.lower().split()\n", "\n", "sentences = MyText()\n", "\n", "print(sentences)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Training\n", "`Word2Vec` accepts several parameters that affect both training speed and quality.\n", "\n", "One of them is for pruning the internal dictionary. Words that appear only once or twice in a billion-word corpus are probably uninteresting typos and garbage. In addition, there’s not enough data to make any meaningful training on those words, so it’s best to ignore them:" ] }, { "cell_type": "code", "execution_count": 12, "metadata": {}, "outputs": [ { "name": "stderr", "output_type": "stream", "text": [ "2017-05-07 14:19:35,718 : INFO : collecting all words and their counts\n", "2017-05-07 14:19:35,721 : INFO : PROGRESS: at sentence #0, processed 0 words, keeping 0 word types\n", "2017-05-07 14:19:35,765 : INFO : collected 10186 word types from a corpus of 59890 raw words and 300 sentences\n", "2017-05-07 14:19:35,766 : INFO : Loading a fresh vocabulary\n", "2017-05-07 14:19:35,787 : INFO : min_count=10 retains 806 unique words (7% of original 10186, drops 9380)\n", "2017-05-07 14:19:35,789 : INFO : min_count=10 leaves 40964 word corpus (68% of original 59890, drops 18926)\n", "2017-05-07 14:19:35,795 : INFO : deleting the raw counts dictionary of 10186 items\n", "2017-05-07 14:19:35,799 : INFO : sample=0.001 downsamples 54 most-common words\n", "2017-05-07 14:19:35,802 : INFO : downsampling leaves estimated 26224 word corpus (64.0% of prior 40964)\n", "2017-05-07 14:19:35,804 : INFO : estimated required memory for 806 words and 100 dimensions: 1047800 bytes\n", "2017-05-07 14:19:35,812 : INFO : resetting layer weights\n", "2017-05-07 14:19:35,834 : INFO : training model with 3 workers on 806 vocabulary and 100 features, using sg=0 hs=0 sample=0.001 negative=5 window=5\n", "2017-05-07 14:19:36,106 : INFO : worker thread finished; awaiting finish of 2 more threads\n", "2017-05-07 14:19:36,110 : INFO : worker thread finished; awaiting finish of 1 more threads\n", "2017-05-07 14:19:36,112 : INFO : worker thread finished; awaiting finish of 0 more threads\n", "2017-05-07 14:19:36,113 : INFO : training on 299450 raw words (131202 effective words) took 0.3s, 478707 effective words/s\n" ] } ], "source": [ "# default value of min_count=5\n", "model = gensim.models.Word2Vec(sentences, min_count=10)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "`size` is the number of dimensions (N) of the N-dimensional space that gensim Word2Vec maps the words onto.\n", "\n", "Bigger size values require more training data, but can lead to better (more accurate) models. Reasonable values are in the tens to hundreds." ] }, { "cell_type": "code", "execution_count": 13, "metadata": {}, "outputs": [ { "name": "stderr", "output_type": "stream", "text": [ "2017-05-07 14:19:36,122 : INFO : collecting all words and their counts\n", "2017-05-07 14:19:36,125 : INFO : PROGRESS: at sentence #0, processed 0 words, keeping 0 word types\n", "2017-05-07 14:19:36,159 : INFO : collected 10186 word types from a corpus of 59890 raw words and 300 sentences\n", "2017-05-07 14:19:36,161 : INFO : Loading a fresh vocabulary\n", "2017-05-07 14:19:36,173 : INFO : min_count=5 retains 1723 unique words (16% of original 10186, drops 8463)\n", "2017-05-07 14:19:36,175 : INFO : min_count=5 leaves 46858 word corpus (78% of original 59890, drops 13032)\n", "2017-05-07 14:19:36,186 : INFO : deleting the raw counts dictionary of 10186 items\n", "2017-05-07 14:19:36,188 : INFO : sample=0.001 downsamples 49 most-common words\n", "2017-05-07 14:19:36,190 : INFO : downsampling leaves estimated 32849 word corpus (70.1% of prior 46858)\n", "2017-05-07 14:19:36,193 : INFO : estimated required memory for 1723 words and 200 dimensions: 3618300 bytes\n", "2017-05-07 14:19:36,207 : INFO : resetting layer weights\n", "2017-05-07 14:19:36,246 : INFO : training model with 3 workers on 1723 vocabulary and 200 features, using sg=0 hs=0 sample=0.001 negative=5 window=5\n", "2017-05-07 14:19:36,485 : INFO : worker thread finished; awaiting finish of 2 more threads\n", "2017-05-07 14:19:36,486 : INFO : worker thread finished; awaiting finish of 1 more threads\n", "2017-05-07 14:19:36,490 : INFO : worker thread finished; awaiting finish of 0 more threads\n", "2017-05-07 14:19:36,491 : INFO : training on 299450 raw words (164316 effective words) took 0.2s, 686188 effective words/s\n" ] } ], "source": [ "# default value of size=100\n", "model = gensim.models.Word2Vec(sentences, size=200)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "The last of the major parameters (full list [here](http://radimrehurek.com/gensim/models/word2vec.html#gensim.models.word2vec.Word2Vec)) is for training parallelization, to speed up training:" ] }, { "cell_type": "code", "execution_count": 14, "metadata": {}, "outputs": [ { "name": "stderr", "output_type": "stream", "text": [ "2017-05-07 14:19:36,501 : INFO : collecting all words and their counts\n", "2017-05-07 14:19:36,503 : INFO : PROGRESS: at sentence #0, processed 0 words, keeping 0 word types\n", "2017-05-07 14:19:36,542 : INFO : collected 10186 word types from a corpus of 59890 raw words and 300 sentences\n", "2017-05-07 14:19:36,545 : INFO : Loading a fresh vocabulary\n", "2017-05-07 14:19:36,561 : INFO : min_count=5 retains 1723 unique words (16% of original 10186, drops 8463)\n", "2017-05-07 14:19:36,564 : INFO : min_count=5 leaves 46858 word corpus (78% of original 59890, drops 13032)\n", "2017-05-07 14:19:36,574 : INFO : deleting the raw counts dictionary of 10186 items\n", "2017-05-07 14:19:36,580 : INFO : sample=0.001 downsamples 49 most-common words\n", "2017-05-07 14:19:36,582 : INFO : downsampling leaves estimated 32849 word corpus (70.1% of prior 46858)\n", "2017-05-07 14:19:36,583 : INFO : estimated required memory for 1723 words and 100 dimensions: 2239900 bytes\n", "2017-05-07 14:19:36,598 : INFO : resetting layer weights\n", "2017-05-07 14:19:36,631 : INFO : training model with 4 workers on 1723 vocabulary and 100 features, using sg=0 hs=0 sample=0.001 negative=5 window=5\n", "2017-05-07 14:19:36,792 : INFO : worker thread finished; awaiting finish of 3 more threads\n", "2017-05-07 14:19:36,794 : INFO : worker thread finished; awaiting finish of 2 more threads\n", "2017-05-07 14:19:36,795 : INFO : worker thread finished; awaiting finish of 1 more threads\n", "2017-05-07 14:19:36,801 : INFO : worker thread finished; awaiting finish of 0 more threads\n", "2017-05-07 14:19:36,802 : INFO : training on 299450 raw words (164316 effective words) took 0.2s, 979062 effective words/s\n", "2017-05-07 14:19:36,805 : WARNING : under 10 jobs per worker: consider setting a smaller `batch_words' for smoother alpha decay\n" ] } ], "source": [ "# default value of workers=3 (tutorial says 1...)\n", "model = gensim.models.Word2Vec(sentences, workers=4)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "The `workers` parameter only has an effect if you have [Cython](http://cython.org/) installed. Without Cython, you’ll only be able to use one core because of the [GIL](https://wiki.python.org/moin/GlobalInterpreterLock) (and `word2vec` training will be [miserably slow](http://rare-technologies.com/word2vec-in-python-part-two-optimizing/))." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Memory\n", "At its core, `word2vec` model parameters are stored as matrices (NumPy arrays). Each array is **#vocabulary** (controlled by min_count parameter) times **#size** (size parameter) of floats (single precision aka 4 bytes).\n", "\n", "Three such matrices are held in RAM (work is underway to reduce that number to two, or even one). So if your input contains 100,000 unique words, and you asked for layer `size=200`, the model will require approx. `100,000*200*4*3 bytes = ~229MB`.\n", "\n", "There’s a little extra memory needed for storing the vocabulary tree (100,000 words would take a few megabytes), but unless your words are extremely loooong strings, memory footprint will be dominated by the three matrices above." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Evaluating\n", "`Word2Vec` training is an unsupervised task, there’s no good way to objectively evaluate the result. Evaluation depends on your end application.\n", "\n", "Google have released their testing set of about 20,000 syntactic and semantic test examples, following the “A is to B as C is to D” task. It is provided in the 'datasets' folder.\n", "\n", "For example a syntactic analogy of comparative type is bad:worse;good:?. There are total of 9 types of syntactic comparisons in the dataset like plural nouns and nouns of opposite meaning.\n", "\n", "The semantic questions contain five types of semantic analogies, such as capital cities (Paris:France;Tokyo:?) or family members (brother:sister;dad:?). " ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Gensim supports the same evaluation set, in exactly the same format:" ] }, { "cell_type": "code", "execution_count": 15, "metadata": {}, "outputs": [ { "name": "stderr", "output_type": "stream", "text": [ "2017-05-07 14:19:36,892 : INFO : precomputing L2-norms of word weight vectors\n", "2017-05-07 14:19:36,896 : INFO : family: 0.0% (0/2)\n", "2017-05-07 14:19:36,924 : INFO : gram3-comparative: 0.0% (0/12)\n", "2017-05-07 14:19:36,935 : INFO : gram4-superlative: 0.0% (0/12)\n", "2017-05-07 14:19:36,949 : INFO : gram5-present-participle: 5.0% (1/20)\n", "2017-05-07 14:19:36,967 : INFO : gram6-nationality-adjective: 0.0% (0/20)\n", "2017-05-07 14:19:36,983 : INFO : gram7-past-tense: 0.0% (0/20)\n", "2017-05-07 14:19:36,998 : INFO : gram8-plural: 0.0% (0/12)\n", "2017-05-07 14:19:37,006 : INFO : total: 1.0% (1/98)\n" ] }, { "data": { "text/plain": [ "[{'correct': [], 'incorrect': [], 'section': u'capital-common-countries'},\n", " {'correct': [], 'incorrect': [], 'section': u'capital-world'},\n", " {'correct': [], 'incorrect': [], 'section': u'currency'},\n", " {'correct': [], 'incorrect': [], 'section': u'city-in-state'},\n", " {'correct': [],\n", " 'incorrect': [(u'HE', u'SHE', u'HIS', u'HER'),\n", " (u'HIS', u'HER', u'HE', u'SHE')],\n", " 'section': u'family'},\n", " {'correct': [], 'incorrect': [], 'section': u'gram1-adjective-to-adverb'},\n", " {'correct': [], 'incorrect': [], 'section': u'gram2-opposite'},\n", " {'correct': [],\n", " 'incorrect': [(u'GOOD', u'BETTER', u'GREAT', u'GREATER'),\n", " (u'GOOD', u'BETTER', u'LONG', u'LONGER'),\n", " (u'GOOD', u'BETTER', u'LOW', u'LOWER'),\n", " (u'GREAT', u'GREATER', u'LONG', u'LONGER'),\n", " (u'GREAT', u'GREATER', u'LOW', u'LOWER'),\n", " (u'GREAT', u'GREATER', u'GOOD', u'BETTER'),\n", " (u'LONG', u'LONGER', u'LOW', u'LOWER'),\n", " (u'LONG', u'LONGER', u'GOOD', u'BETTER'),\n", " (u'LONG', u'LONGER', u'GREAT', u'GREATER'),\n", " (u'LOW', u'LOWER', u'GOOD', u'BETTER'),\n", " (u'LOW', u'LOWER', u'GREAT', u'GREATER'),\n", " (u'LOW', u'LOWER', u'LONG', u'LONGER')],\n", " 'section': u'gram3-comparative'},\n", " {'correct': [],\n", " 'incorrect': [(u'BIG', u'BIGGEST', u'GOOD', u'BEST'),\n", " (u'BIG', u'BIGGEST', u'GREAT', u'GREATEST'),\n", " (u'BIG', u'BIGGEST', u'LARGE', u'LARGEST'),\n", " (u'GOOD', u'BEST', u'GREAT', u'GREATEST'),\n", " (u'GOOD', u'BEST', u'LARGE', u'LARGEST'),\n", " (u'GOOD', u'BEST', u'BIG', u'BIGGEST'),\n", " (u'GREAT', u'GREATEST', u'LARGE', u'LARGEST'),\n", " (u'GREAT', u'GREATEST', u'BIG', u'BIGGEST'),\n", " (u'GREAT', u'GREATEST', u'GOOD', u'BEST'),\n", " (u'LARGE', u'LARGEST', u'BIG', u'BIGGEST'),\n", " (u'LARGE', u'LARGEST', u'GOOD', u'BEST'),\n", " (u'LARGE', u'LARGEST', u'GREAT', u'GREATEST')],\n", " 'section': u'gram4-superlative'},\n", " {'correct': [(u'LOOK', u'LOOKING', u'SAY', u'SAYING')],\n", " 'incorrect': [(u'GO', u'GOING', u'LOOK', u'LOOKING'),\n", " (u'GO', u'GOING', u'PLAY', u'PLAYING'),\n", " (u'GO', u'GOING', u'RUN', u'RUNNING'),\n", " (u'GO', u'GOING', u'SAY', u'SAYING'),\n", " (u'LOOK', u'LOOKING', u'PLAY', u'PLAYING'),\n", " (u'LOOK', u'LOOKING', u'RUN', u'RUNNING'),\n", " (u'LOOK', u'LOOKING', u'GO', u'GOING'),\n", " (u'PLAY', u'PLAYING', u'RUN', u'RUNNING'),\n", " (u'PLAY', u'PLAYING', u'SAY', u'SAYING'),\n", " (u'PLAY', u'PLAYING', u'GO', u'GOING'),\n", " (u'PLAY', u'PLAYING', u'LOOK', u'LOOKING'),\n", " (u'RUN', u'RUNNING', u'SAY', u'SAYING'),\n", " (u'RUN', u'RUNNING', u'GO', u'GOING'),\n", " (u'RUN', u'RUNNING', u'LOOK', u'LOOKING'),\n", " (u'RUN', u'RUNNING', u'PLAY', u'PLAYING'),\n", " (u'SAY', u'SAYING', u'GO', u'GOING'),\n", " (u'SAY', u'SAYING', u'LOOK', u'LOOKING'),\n", " (u'SAY', u'SAYING', u'PLAY', u'PLAYING'),\n", " (u'SAY', u'SAYING', u'RUN', u'RUNNING')],\n", " 'section': u'gram5-present-participle'},\n", " {'correct': [],\n", " 'incorrect': [(u'AUSTRALIA', u'AUSTRALIAN', u'FRANCE', u'FRENCH'),\n", " (u'AUSTRALIA', u'AUSTRALIAN', u'INDIA', u'INDIAN'),\n", " (u'AUSTRALIA', u'AUSTRALIAN', u'ISRAEL', u'ISRAELI'),\n", " (u'AUSTRALIA', u'AUSTRALIAN', u'SWITZERLAND', u'SWISS'),\n", " (u'FRANCE', u'FRENCH', u'INDIA', u'INDIAN'),\n", " (u'FRANCE', u'FRENCH', u'ISRAEL', u'ISRAELI'),\n", " (u'FRANCE', u'FRENCH', u'SWITZERLAND', u'SWISS'),\n", " (u'FRANCE', u'FRENCH', u'AUSTRALIA', u'AUSTRALIAN'),\n", " (u'INDIA', u'INDIAN', u'ISRAEL', u'ISRAELI'),\n", " (u'INDIA', u'INDIAN', u'SWITZERLAND', u'SWISS'),\n", " (u'INDIA', u'INDIAN', u'AUSTRALIA', u'AUSTRALIAN'),\n", " (u'INDIA', u'INDIAN', u'FRANCE', u'FRENCH'),\n", " (u'ISRAEL', u'ISRAELI', u'SWITZERLAND', u'SWISS'),\n", " (u'ISRAEL', u'ISRAELI', u'AUSTRALIA', u'AUSTRALIAN'),\n", " (u'ISRAEL', u'ISRAELI', u'FRANCE', u'FRENCH'),\n", " (u'ISRAEL', u'ISRAELI', u'INDIA', u'INDIAN'),\n", " (u'SWITZERLAND', u'SWISS', u'AUSTRALIA', u'AUSTRALIAN'),\n", " (u'SWITZERLAND', u'SWISS', u'FRANCE', u'FRENCH'),\n", " (u'SWITZERLAND', u'SWISS', u'INDIA', u'INDIAN'),\n", " (u'SWITZERLAND', u'SWISS', u'ISRAEL', u'ISRAELI')],\n", " 'section': u'gram6-nationality-adjective'},\n", " {'correct': [],\n", " 'incorrect': [(u'GOING', u'WENT', u'PAYING', u'PAID'),\n", " (u'GOING', u'WENT', u'PLAYING', u'PLAYED'),\n", " (u'GOING', u'WENT', u'SAYING', u'SAID'),\n", " (u'GOING', u'WENT', u'TAKING', u'TOOK'),\n", " (u'PAYING', u'PAID', u'PLAYING', u'PLAYED'),\n", " (u'PAYING', u'PAID', u'SAYING', u'SAID'),\n", " (u'PAYING', u'PAID', u'TAKING', u'TOOK'),\n", " (u'PAYING', u'PAID', u'GOING', u'WENT'),\n", " (u'PLAYING', u'PLAYED', u'SAYING', u'SAID'),\n", " (u'PLAYING', u'PLAYED', u'TAKING', u'TOOK'),\n", " (u'PLAYING', u'PLAYED', u'GOING', u'WENT'),\n", " (u'PLAYING', u'PLAYED', u'PAYING', u'PAID'),\n", " (u'SAYING', u'SAID', u'TAKING', u'TOOK'),\n", " (u'SAYING', u'SAID', u'GOING', u'WENT'),\n", " (u'SAYING', u'SAID', u'PAYING', u'PAID'),\n", " (u'SAYING', u'SAID', u'PLAYING', u'PLAYED'),\n", " (u'TAKING', u'TOOK', u'GOING', u'WENT'),\n", " (u'TAKING', u'TOOK', u'PAYING', u'PAID'),\n", " (u'TAKING', u'TOOK', u'PLAYING', u'PLAYED'),\n", " (u'TAKING', u'TOOK', u'SAYING', u'SAID')],\n", " 'section': u'gram7-past-tense'},\n", " {'correct': [],\n", " 'incorrect': [(u'BUILDING', u'BUILDINGS', u'CAR', u'CARS'),\n", " (u'BUILDING', u'BUILDINGS', u'CHILD', u'CHILDREN'),\n", " (u'BUILDING', u'BUILDINGS', u'MAN', u'MEN'),\n", " (u'CAR', u'CARS', u'CHILD', u'CHILDREN'),\n", " (u'CAR', u'CARS', u'MAN', u'MEN'),\n", " (u'CAR', u'CARS', u'BUILDING', u'BUILDINGS'),\n", " (u'CHILD', u'CHILDREN', u'MAN', u'MEN'),\n", " (u'CHILD', u'CHILDREN', u'BUILDING', u'BUILDINGS'),\n", " (u'CHILD', u'CHILDREN', u'CAR', u'CARS'),\n", " (u'MAN', u'MEN', u'BUILDING', u'BUILDINGS'),\n", " (u'MAN', u'MEN', u'CAR', u'CARS'),\n", " (u'MAN', u'MEN', u'CHILD', u'CHILDREN')],\n", " 'section': u'gram8-plural'},\n", " {'correct': [], 'incorrect': [], 'section': u'gram9-plural-verbs'},\n", " {'correct': [(u'LOOK', u'LOOKING', u'SAY', u'SAYING')],\n", " 'incorrect': [(u'HE', u'SHE', u'HIS', u'HER'),\n", " (u'HIS', u'HER', u'HE', u'SHE'),\n", " (u'GOOD', u'BETTER', u'GREAT', u'GREATER'),\n", " (u'GOOD', u'BETTER', u'LONG', u'LONGER'),\n", " (u'GOOD', u'BETTER', u'LOW', u'LOWER'),\n", " (u'GREAT', u'GREATER', u'LONG', u'LONGER'),\n", " (u'GREAT', u'GREATER', u'LOW', u'LOWER'),\n", " (u'GREAT', u'GREATER', u'GOOD', u'BETTER'),\n", " (u'LONG', u'LONGER', u'LOW', u'LOWER'),\n", " (u'LONG', u'LONGER', u'GOOD', u'BETTER'),\n", " (u'LONG', u'LONGER', u'GREAT', u'GREATER'),\n", " (u'LOW', u'LOWER', u'GOOD', u'BETTER'),\n", " (u'LOW', u'LOWER', u'GREAT', u'GREATER'),\n", " (u'LOW', u'LOWER', u'LONG', u'LONGER'),\n", " (u'BIG', u'BIGGEST', u'GOOD', u'BEST'),\n", " (u'BIG', u'BIGGEST', u'GREAT', u'GREATEST'),\n", " (u'BIG', u'BIGGEST', u'LARGE', u'LARGEST'),\n", " (u'GOOD', u'BEST', u'GREAT', u'GREATEST'),\n", " (u'GOOD', u'BEST', u'LARGE', u'LARGEST'),\n", " (u'GOOD', u'BEST', u'BIG', u'BIGGEST'),\n", " (u'GREAT', u'GREATEST', u'LARGE', u'LARGEST'),\n", " (u'GREAT', u'GREATEST', u'BIG', u'BIGGEST'),\n", " (u'GREAT', u'GREATEST', u'GOOD', u'BEST'),\n", " (u'LARGE', u'LARGEST', u'BIG', u'BIGGEST'),\n", " (u'LARGE', u'LARGEST', u'GOOD', u'BEST'),\n", " (u'LARGE', u'LARGEST', u'GREAT', u'GREATEST'),\n", " (u'GO', u'GOING', u'LOOK', u'LOOKING'),\n", " (u'GO', u'GOING', u'PLAY', u'PLAYING'),\n", " (u'GO', u'GOING', u'RUN', u'RUNNING'),\n", " (u'GO', u'GOING', u'SAY', u'SAYING'),\n", " (u'LOOK', u'LOOKING', u'PLAY', u'PLAYING'),\n", " (u'LOOK', u'LOOKING', u'RUN', u'RUNNING'),\n", " (u'LOOK', u'LOOKING', u'GO', u'GOING'),\n", " (u'PLAY', u'PLAYING', u'RUN', u'RUNNING'),\n", " (u'PLAY', u'PLAYING', u'SAY', u'SAYING'),\n", " (u'PLAY', u'PLAYING', u'GO', u'GOING'),\n", " (u'PLAY', u'PLAYING', u'LOOK', u'LOOKING'),\n", " (u'RUN', u'RUNNING', u'SAY', u'SAYING'),\n", " (u'RUN', u'RUNNING', u'GO', u'GOING'),\n", " (u'RUN', u'RUNNING', u'LOOK', u'LOOKING'),\n", " (u'RUN', u'RUNNING', u'PLAY', u'PLAYING'),\n", " (u'SAY', u'SAYING', u'GO', u'GOING'),\n", " (u'SAY', u'SAYING', u'LOOK', u'LOOKING'),\n", " (u'SAY', u'SAYING', u'PLAY', u'PLAYING'),\n", " (u'SAY', u'SAYING', u'RUN', u'RUNNING'),\n", " (u'AUSTRALIA', u'AUSTRALIAN', u'FRANCE', u'FRENCH'),\n", " (u'AUSTRALIA', u'AUSTRALIAN', u'INDIA', u'INDIAN'),\n", " (u'AUSTRALIA', u'AUSTRALIAN', u'ISRAEL', u'ISRAELI'),\n", " (u'AUSTRALIA', u'AUSTRALIAN', u'SWITZERLAND', u'SWISS'),\n", " (u'FRANCE', u'FRENCH', u'INDIA', u'INDIAN'),\n", " (u'FRANCE', u'FRENCH', u'ISRAEL', u'ISRAELI'),\n", " (u'FRANCE', u'FRENCH', u'SWITZERLAND', u'SWISS'),\n", " (u'FRANCE', u'FRENCH', u'AUSTRALIA', u'AUSTRALIAN'),\n", " (u'INDIA', u'INDIAN', u'ISRAEL', u'ISRAELI'),\n", " (u'INDIA', u'INDIAN', u'SWITZERLAND', u'SWISS'),\n", " (u'INDIA', u'INDIAN', u'AUSTRALIA', u'AUSTRALIAN'),\n", " (u'INDIA', u'INDIAN', u'FRANCE', u'FRENCH'),\n", " (u'ISRAEL', u'ISRAELI', u'SWITZERLAND', u'SWISS'),\n", " (u'ISRAEL', u'ISRAELI', u'AUSTRALIA', u'AUSTRALIAN'),\n", " (u'ISRAEL', u'ISRAELI', u'FRANCE', u'FRENCH'),\n", " (u'ISRAEL', u'ISRAELI', u'INDIA', u'INDIAN'),\n", " (u'SWITZERLAND', u'SWISS', u'AUSTRALIA', u'AUSTRALIAN'),\n", " (u'SWITZERLAND', u'SWISS', u'FRANCE', u'FRENCH'),\n", " (u'SWITZERLAND', u'SWISS', u'INDIA', u'INDIAN'),\n", " (u'SWITZERLAND', u'SWISS', u'ISRAEL', u'ISRAELI'),\n", " (u'GOING', u'WENT', u'PAYING', u'PAID'),\n", " (u'GOING', u'WENT', u'PLAYING', u'PLAYED'),\n", " (u'GOING', u'WENT', u'SAYING', u'SAID'),\n", " (u'GOING', u'WENT', u'TAKING', u'TOOK'),\n", " (u'PAYING', u'PAID', u'PLAYING', u'PLAYED'),\n", " (u'PAYING', u'PAID', u'SAYING', u'SAID'),\n", " (u'PAYING', u'PAID', u'TAKING', u'TOOK'),\n", " (u'PAYING', u'PAID', u'GOING', u'WENT'),\n", " (u'PLAYING', u'PLAYED', u'SAYING', u'SAID'),\n", " (u'PLAYING', u'PLAYED', u'TAKING', u'TOOK'),\n", " (u'PLAYING', u'PLAYED', u'GOING', u'WENT'),\n", " (u'PLAYING', u'PLAYED', u'PAYING', u'PAID'),\n", " (u'SAYING', u'SAID', u'TAKING', u'TOOK'),\n", " (u'SAYING', u'SAID', u'GOING', u'WENT'),\n", " (u'SAYING', u'SAID', u'PAYING', u'PAID'),\n", " (u'SAYING', u'SAID', u'PLAYING', u'PLAYED'),\n", " (u'TAKING', u'TOOK', u'GOING', u'WENT'),\n", " (u'TAKING', u'TOOK', u'PAYING', u'PAID'),\n", " (u'TAKING', u'TOOK', u'PLAYING', u'PLAYED'),\n", " (u'TAKING', u'TOOK', u'SAYING', u'SAID'),\n", " (u'BUILDING', u'BUILDINGS', u'CAR', u'CARS'),\n", " (u'BUILDING', u'BUILDINGS', u'CHILD', u'CHILDREN'),\n", " (u'BUILDING', u'BUILDINGS', u'MAN', u'MEN'),\n", " (u'CAR', u'CARS', u'CHILD', u'CHILDREN'),\n", " (u'CAR', u'CARS', u'MAN', u'MEN'),\n", " (u'CAR', u'CARS', u'BUILDING', u'BUILDINGS'),\n", " (u'CHILD', u'CHILDREN', u'MAN', u'MEN'),\n", " (u'CHILD', u'CHILDREN', u'BUILDING', u'BUILDINGS'),\n", " (u'CHILD', u'CHILDREN', u'CAR', u'CARS'),\n", " (u'MAN', u'MEN', u'BUILDING', u'BUILDINGS'),\n", " (u'MAN', u'MEN', u'CAR', u'CARS'),\n", " (u'MAN', u'MEN', u'CHILD', u'CHILDREN')],\n", " 'section': 'total'}]" ] }, "execution_count": 15, "metadata": {}, "output_type": "execute_result" } ], "source": [ "model.accuracy('./datasets/questions-words.txt')" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "This `accuracy` takes an \n", "[optional parameter](http://radimrehurek.com/gensim/models/word2vec.html#gensim.models.word2vec.Word2Vec.accuracy) `restrict_vocab` \n", "which limits which test examples are to be considered.\n", "\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "In the December 2016 release of Gensim we added a better way to evaluate semantic similarity.\n", "\n", "By default it uses an academic dataset WS-353 but one can create a dataset specific to your business based on it. It contains word pairs together with human-assigned similarity judgments. It measures the relatedness or co-occurrence of two words. For example, 'coast' and 'shore' are very similar as they appear in the same context. At the same time 'clothes' and 'closet' are less similar because they are related but not interchangeable." ] }, { "cell_type": "code", "execution_count": 16, "metadata": {}, "outputs": [ { "name": "stderr", "output_type": "stream", "text": [ "2017-05-07 14:19:37,057 : INFO : Pearson correlation coefficient against /usr/local/lib/python2.7/site-packages/gensim/test/test_data/wordsim353.tsv: 0.0819\n", "2017-05-07 14:19:37,058 : INFO : Spearman rank-order correlation coefficient against /usr/local/lib/python2.7/site-packages/gensim/test/test_data/wordsim353.tsv: 0.0825\n", "2017-05-07 14:19:37,060 : INFO : Pairs with unknown words ratio: 85.6%\n" ] }, { "data": { "text/plain": [ "((0.081883159986411394, 0.5678461885290379),\n", " SpearmanrResult(correlation=0.082498020328092989, pvalue=0.56493264964360379),\n", " 85.55240793201133)" ] }, "execution_count": 16, "metadata": {}, "output_type": "execute_result" } ], "source": [ "model.evaluate_word_pairs(test_data_dir +'wordsim353.tsv')" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Once again, **good performance on Google's or WS-353 test set doesn’t mean word2vec will work well in your application, or vice versa**. It’s always best to evaluate directly on your intended task. For an example of how to use word2vec in a classifier pipeline, see this [tutorial](https://github.com/RaRe-Technologies/movie-plots-by-genre)." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Storing and loading models\n", "You can store/load models using the standard gensim methods:" ] }, { "cell_type": "code", "execution_count": 17, "metadata": {}, "outputs": [ { "name": "stderr", "output_type": "stream", "text": [ "2017-05-07 14:19:37,075 : INFO : saving Word2Vec object under /var/folders/4t/xx08nfg15lj77zlfjz69314r0000gn/T/tmpZEHE9Wgensim_temp, separately None\n", "2017-05-07 14:19:37,078 : INFO : not storing attribute syn0norm\n", "2017-05-07 14:19:37,079 : INFO : not storing attribute cum_table\n", "2017-05-07 14:19:37,101 : INFO : saved /var/folders/4t/xx08nfg15lj77zlfjz69314r0000gn/T/tmpZEHE9Wgensim_temp\n" ] } ], "source": [ "from tempfile import mkstemp\n", "\n", "fs, temp_path = mkstemp(\"gensim_temp\") # creates a temp file\n", "\n", "model.save(temp_path) # save the model" ] }, { "cell_type": "code", "execution_count": 18, "metadata": {}, "outputs": [ { "name": "stderr", "output_type": "stream", "text": [ "2017-05-07 14:19:37,107 : INFO : loading Word2Vec object from /var/folders/4t/xx08nfg15lj77zlfjz69314r0000gn/T/tmpZEHE9Wgensim_temp\n", "2017-05-07 14:19:37,118 : INFO : loading wv recursively from /var/folders/4t/xx08nfg15lj77zlfjz69314r0000gn/T/tmpZEHE9Wgensim_temp.wv.* with mmap=None\n", "2017-05-07 14:19:37,119 : INFO : setting ignored attribute syn0norm to None\n", "2017-05-07 14:19:37,120 : INFO : setting ignored attribute cum_table to None\n", "2017-05-07 14:19:37,121 : INFO : loaded /var/folders/4t/xx08nfg15lj77zlfjz69314r0000gn/T/tmpZEHE9Wgensim_temp\n" ] } ], "source": [ "new_model = gensim.models.Word2Vec.load(temp_path) # open the model" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "which uses pickle internally, optionally `mmap`‘ing the model’s internal large NumPy matrices into virtual memory directly from disk files, for inter-process memory sharing.\n", "\n", "In addition, you can load models created by the original C tool, both using its text and binary formats:\n", "```\n", " model = gensim.models.KeyedVectors.load_word2vec_format('/tmp/vectors.txt', binary=False)\n", " # using gzipped/bz2 input works too, no need to unzip:\n", " model = gensim.models.KeyedVectors.load_word2vec_format('/tmp/vectors.bin.gz', binary=True)\n", "```" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Online training / Resuming training\n", "Advanced users can load a model and continue training it with more sentences and [new vocabulary words](https://github.com/RaRe-Technologies/gensim/blob/develop/docs/notebooks/online_w2v_tutorial.ipynb):" ] }, { "cell_type": "code", "execution_count": 19, "metadata": {}, "outputs": [ { "name": "stderr", "output_type": "stream", "text": [ "2017-05-07 14:19:37,137 : INFO : loading Word2Vec object from /var/folders/4t/xx08nfg15lj77zlfjz69314r0000gn/T/tmpZEHE9Wgensim_temp\n", "2017-05-07 14:19:37,146 : INFO : loading wv recursively from /var/folders/4t/xx08nfg15lj77zlfjz69314r0000gn/T/tmpZEHE9Wgensim_temp.wv.* with mmap=None\n", "2017-05-07 14:19:37,147 : INFO : setting ignored attribute syn0norm to None\n", "2017-05-07 14:19:37,149 : INFO : setting ignored attribute cum_table to None\n", "2017-05-07 14:19:37,150 : INFO : loaded /var/folders/4t/xx08nfg15lj77zlfjz69314r0000gn/T/tmpZEHE9Wgensim_temp\n", "2017-05-07 14:19:37,155 : INFO : collecting all words and their counts\n", "2017-05-07 14:19:37,156 : INFO : PROGRESS: at sentence #0, processed 0 words, keeping 0 word types\n", "2017-05-07 14:19:37,157 : INFO : collected 13 word types from a corpus of 13 raw words and 1 sentences\n", "2017-05-07 14:19:37,158 : INFO : Updating model with new vocabulary\n", "2017-05-07 14:19:37,159 : INFO : New added 0 unique words (0% of original 13)\n", " and increased the count of 0 pre-existing words (0% of original 13)\n", "2017-05-07 14:19:37,161 : INFO : deleting the raw counts dictionary of 13 items\n", "2017-05-07 14:19:37,162 : INFO : sample=0.001 downsamples 0 most-common words\n", "2017-05-07 14:19:37,163 : INFO : downsampling leaves estimated 0 word corpus (0.0% of prior 0)\n", "2017-05-07 14:19:37,164 : INFO : estimated required memory for 1723 words and 100 dimensions: 2239900 bytes\n", "2017-05-07 14:19:37,170 : INFO : updating layer weights\n", "2017-05-07 14:19:37,172 : INFO : training model with 4 workers on 1723 vocabulary and 100 features, using sg=0 hs=0 sample=0.001 negative=5 window=5\n", "2017-05-07 14:19:37,174 : INFO : worker thread finished; awaiting finish of 3 more threads\n", "2017-05-07 14:19:37,176 : INFO : worker thread finished; awaiting finish of 2 more threads\n", "2017-05-07 14:19:37,178 : INFO : worker thread finished; awaiting finish of 1 more threads\n", "2017-05-07 14:19:37,179 : INFO : worker thread finished; awaiting finish of 0 more threads\n", "2017-05-07 14:19:37,180 : INFO : training on 65 raw words (28 effective words) took 0.0s, 4209 effective words/s\n", "2017-05-07 14:19:37,182 : WARNING : under 10 jobs per worker: consider setting a smaller `batch_words' for smoother alpha decay\n" ] } ], "source": [ "model = gensim.models.Word2Vec.load(temp_path)\n", "more_sentences = [['Advanced', 'users', 'can', 'load', 'a', 'model', 'and', 'continue', \n", " 'training', 'it', 'with', 'more', 'sentences']]\n", "model.build_vocab(more_sentences, update=True)\n", "model.train(more_sentences, total_examples=model.corpus_count, epochs=model.iter)\n", "\n", "# cleaning up temp\n", "os.close(fs)\n", "os.remove(temp_path)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "You may need to tweak the `total_words` parameter to `train()`, depending on what learning rate decay you want to simulate.\n", "\n", "Note that it’s not possible to resume training with models generated by the C tool, `KeyedVectors.load_word2vec_format()`. You can still use them for querying/similarity, but information vital for training (the vocab tree) is missing there.\n", "\n", "## Using the model\n", "`Word2Vec` supports several word similarity tasks out of the box:" ] }, { "cell_type": "code", "execution_count": 20, "metadata": {}, "outputs": [ { "name": "stderr", "output_type": "stream", "text": [ "2017-05-07 14:19:37,190 : INFO : precomputing L2-norms of word weight vectors\n" ] }, { "data": { "text/plain": [ "[('longer', 0.9884582161903381)]" ] }, "execution_count": 20, "metadata": {}, "output_type": "execute_result" } ], "source": [ "model.most_similar(positive=['human', 'crime'], negative=['party'], topn=1)" ] }, { "cell_type": "code", "execution_count": 21, "metadata": {}, "outputs": [ { "name": "stderr", "output_type": "stream", "text": [ "2017-05-07 14:19:37,202 : WARNING : vectors for words set(['lunch', 'input', 'cat']) are not present in the model, ignoring these words\n" ] }, { "data": { "text/plain": [ "'sentence'" ] }, "execution_count": 21, "metadata": {}, "output_type": "execute_result" } ], "source": [ "model.doesnt_match(\"input is lunch he sentence cat\".split())" ] }, { "cell_type": "code", "execution_count": 22, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "0.999186470298\n", "0.995724529077\n" ] } ], "source": [ "print(model.similarity('human', 'party'))\n", "print(model.similarity('tree', 'murder'))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "You can get the probability distribution for the center word given the context words as input:" ] }, { "cell_type": "code", "execution_count": 23, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "[('more', 0.001048518), ('continue', 0.00090946292), ('can', 0.00090134487), ('training', 0.00088478095), ('it', 0.00077986595), ('australia', 0.0007500046), ('there', 0.00074296352), ('government', 0.00074113585), ('could', 0.00073843176), ('or', 0.00073749834)]\n" ] } ], "source": [ "print(model.predict_output_word(['emergency','beacon','received']))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "The results here don't look good because the training corpus is very small. To get meaningful results one needs to train on 500k+ words." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "If you need the raw output vectors in your application, you can access these either on a word-by-word basis:" ] }, { "cell_type": "code", "execution_count": 24, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "array([ 0.00349002, 0.02440139, -0.02936695, -0.00849617, -0.03318483,\n", " -0.0382478 , 0.00597728, -0.09292595, -0.01093712, -0.02097394,\n", " 0.02088499, -0.0280605 , -0.07108893, -0.02044513, -0.02337479,\n", " 0.04878484, -0.03198365, -0.00347298, 0.02429976, -0.02761379,\n", " -0.06878174, -0.00695439, 0.06986855, 0.05134906, 0.03044886,\n", " 0.01195826, -0.00513146, 0.02122262, -0.01519287, 0.00502698,\n", " 0.00088907, 0.07702309, 0.01296635, -0.00185401, 0.02448723,\n", " 0.02151101, -0.04088883, 0.01947908, 0.01428026, -0.07242644,\n", " -0.08013999, 0.00214788, -0.04682875, -0.02618166, 0.03343621,\n", " -0.05884593, 0.03833489, 0.00581573, -0.01099163, 0.04513358,\n", " 0.01407813, 0.00823141, -0.03918071, 0.0107606 , 0.01743653,\n", " -0.01885621, 0.06017725, -0.03312737, 0.02473382, -0.03686444,\n", " -0.03306546, -0.05434534, 0.01816491, -0.0386038 , -0.01055549,\n", " -0.06602577, -0.08695736, 0.04147927, 0.05510609, -0.00292372,\n", " -0.00839636, 0.00660775, -0.04910387, 0.01182455, -0.05183903,\n", " -0.05662465, 0.03827399, -0.01096484, 0.05027501, 0.04410599,\n", " -0.02027577, 0.03782682, -0.01756338, 0.00167882, 0.01706443,\n", " 0.00842514, -0.09443056, -0.0869148 , 0.06825797, -0.02385623,\n", " -0.06005816, -0.04784475, -0.05084028, -0.00288582, -0.02646183,\n", " -0.0288031 , -0.0257737 , 0.02252337, -0.05444728, 0.00016777], dtype=float32)" ] }, "execution_count": 24, "metadata": {}, "output_type": "execute_result" } ], "source": [ "model['tree'] # raw NumPy vector of a word" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "…or en-masse as a 2D NumPy matrix from `model.wv.syn0`.\n", "\n", "## Conclusion\n", "\n", "In this tutorial we learned how to train word2vec models on your custom data and also how to evaluate it. Hope that you too will find this popular tool useful in your Machine Learning tasks!\n", "\n", "## Links\n", "\n", "\n", "Full `word2vec` API docs [here](http://radimrehurek.com/gensim/models/word2vec.html); get [gensim](http://radimrehurek.com/gensim/) here. Original C toolkit and `word2vec` papers by Google [here](https://code.google.com/archive/p/word2vec/)." ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": true }, "outputs": [], "source": [] } ], "metadata": { "anaconda-cloud": {}, "kernelspec": { "display_name": "Python 2", "language": "python", "name": "python2" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 2 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython2", "version": "2.7.13" } }, "nbformat": 4, "nbformat_minor": 1 }