Word2Vec Tutorial

This tutorial follows a blog post written by the creator of gensim.

Preparing the Input

Starting from the beginning, gensim’s word2vec expects a sequence of sentences as its input. Each sentence a list of words (utf8 strings):


In [1]:
# import modules & set up logging
import gensim, logging
logging.basicConfig(format='%(asctime)s : %(levelname)s : %(message)s', level=logging.INFO)

In [2]:
sentences = [['first', 'sentence'], ['second', 'sentence']]
# train word2vec on the two sentences
model = gensim.models.Word2Vec(sentences, min_count=1)

Keeping the input as a Python built-in list is convenient, but can use up a lot of RAM when the input is large.

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…

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:


In [3]:
# create some toy data to use with the following example
import smart_open, os

if not os.path.exists('./data/'):
    os.makedirs('./data/')

filenames = ['./data/f1.txt', './data/f2.txt']

for i, fname in enumerate(filenames):
    with smart_open.smart_open(fname, 'w') as fout:
        for line in sentences[i]:
            fout.write(line + '\n')

In [4]:
class MySentences(object):
    def __init__(self, dirname):
        self.dirname = dirname
 
    def __iter__(self):
        for fname in os.listdir(self.dirname):
            for line in open(os.path.join(self.dirname, fname)):
                yield line.split()

In [5]:
sentences = MySentences('./data/') # a memory-friendly iterator
print(list(sentences))


[['first'], ['sentence'], ['second'], ['sentence']]

In [6]:
# generate the Word2Vec model
model = gensim.models.Word2Vec(sentences, min_count=1)
print(model)
print(model.vocab)


Word2Vec(vocab=3, size=100, alpha=0.025)
{'first': <gensim.models.word2vec.Vocab object at 0x10dbd7e48>, 'sentence': <gensim.models.word2vec.Vocab object at 0x10dbd7d30>, 'second': <gensim.models.word2vec.Vocab object at 0x10dbd7ba8>}

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.

Note to advanced users: calling Word2Vec(sentences) will run two passes over the sentences iterator.

  1. The first pass collects words and their frequencies to build an internal dictionary tree structure.
  2. The second pass trains the neural model.

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:


In [7]:
# build the same model, making the 2 steps explicit
new_model = gensim.models.Word2Vec(min_count=1)  # an empty model, no training
new_model.build_vocab(sentences)                 # can be a non-repeatable, 1-pass generator     
new_model.train(sentences)                       # can be a non-repeatable, 1-pass generator
print(new_model)
print(model.vocab)


Word2Vec(vocab=3, size=100, alpha=0.025)
{'first': <gensim.models.word2vec.Vocab object at 0x10dbd7e48>, 'sentence': <gensim.models.word2vec.Vocab object at 0x10dbd7d30>, 'second': <gensim.models.word2vec.Vocab object at 0x10dbd7ba8>}

More data would be nice

For the following examples, we'll use the Lee Corpus (which you already have if you've installed gensim):


In [8]:
# Set file names for train and test data
test_data_dir = '{}'.format(os.sep).join([gensim.__path__[0], 'test', 'test_data']) + os.sep
lee_train_file = test_data_dir + 'lee_background.cor'

In [9]:
class MyText(object):
    def __iter__(self):
        for line in open(lee_train_file):
            # assume there's one document per line, tokens separated by whitespace
            yield line.lower().split()

sentences = MyText()

print(sentences)


<__main__.MyText object at 0x10dbd7860>

Training

Word2Vec accepts several parameters that affect both training speed and quality.

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:


In [10]:
# default value of min_count=5
model = gensim.models.Word2Vec(sentences, min_count=10)

In [11]:
# default value of size=100
model = gensim.models.Word2Vec(sentences, size=200)

Bigger size values require more training data, but can lead to better (more accurate) models. Reasonable values are in the tens to hundreds.

The last of the major parameters (full list here) is for training parallelization, to speed up training:


In [12]:
# default value of workers=3 (tutorial says 1...)
model = gensim.models.Word2Vec(sentences, workers=4)

The workers parameter only has an effect if you have Cython installed. Without Cython, you’ll only be able to use one core because of the GIL (and word2vec training will be miserably slow).

Memory

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).

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.

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.

Evaluating

Word2Vec training is an unsupervised task, there’s no good way to objectively evaluate the result. Evaluation depends on your end application.

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. You can download a zip file here, and unzip it, to get the questions-words.txt file used below.

Gensim support the same evaluation set, in exactly the same format:


In [13]:
model.accuracy('questions-words.txt')


Out[13]:
[{'correct': [], 'incorrect': [], 'section': 'capital-common-countries'},
 {'correct': [], 'incorrect': [], 'section': 'capital-world'},
 {'correct': [], 'incorrect': [], 'section': 'currency'},
 {'correct': [], 'incorrect': [], 'section': 'city-in-state'},
 {'correct': [],
  'incorrect': [('he', 'she', 'his', 'her'), ('his', 'her', 'he', 'she')],
  'section': 'family'},
 {'correct': [], 'incorrect': [], 'section': 'gram1-adjective-to-adverb'},
 {'correct': [], 'incorrect': [], 'section': 'gram2-opposite'},
 {'correct': [],
  'incorrect': [('good', 'better', 'great', 'greater'),
   ('good', 'better', 'long', 'longer'),
   ('good', 'better', 'low', 'lower'),
   ('great', 'greater', 'long', 'longer'),
   ('great', 'greater', 'low', 'lower'),
   ('great', 'greater', 'good', 'better'),
   ('long', 'longer', 'low', 'lower'),
   ('long', 'longer', 'good', 'better'),
   ('long', 'longer', 'great', 'greater'),
   ('low', 'lower', 'good', 'better'),
   ('low', 'lower', 'great', 'greater'),
   ('low', 'lower', 'long', 'longer')],
  'section': 'gram3-comparative'},
 {'correct': [],
  'incorrect': [('big', 'biggest', 'good', 'best'),
   ('big', 'biggest', 'great', 'greatest'),
   ('big', 'biggest', 'large', 'largest'),
   ('good', 'best', 'great', 'greatest'),
   ('good', 'best', 'large', 'largest'),
   ('good', 'best', 'big', 'biggest'),
   ('great', 'greatest', 'large', 'largest'),
   ('great', 'greatest', 'big', 'biggest'),
   ('great', 'greatest', 'good', 'best'),
   ('large', 'largest', 'big', 'biggest'),
   ('large', 'largest', 'good', 'best'),
   ('large', 'largest', 'great', 'greatest')],
  'section': 'gram4-superlative'},
 {'correct': [],
  'incorrect': [('go', 'going', 'look', 'looking'),
   ('go', 'going', 'play', 'playing'),
   ('go', 'going', 'run', 'running'),
   ('go', 'going', 'say', 'saying'),
   ('look', 'looking', 'play', 'playing'),
   ('look', 'looking', 'run', 'running'),
   ('look', 'looking', 'say', 'saying'),
   ('look', 'looking', 'go', 'going'),
   ('play', 'playing', 'run', 'running'),
   ('play', 'playing', 'say', 'saying'),
   ('play', 'playing', 'go', 'going'),
   ('play', 'playing', 'look', 'looking'),
   ('run', 'running', 'say', 'saying'),
   ('run', 'running', 'go', 'going'),
   ('run', 'running', 'look', 'looking'),
   ('run', 'running', 'play', 'playing'),
   ('say', 'saying', 'go', 'going'),
   ('say', 'saying', 'look', 'looking'),
   ('say', 'saying', 'play', 'playing'),
   ('say', 'saying', 'run', 'running')],
  'section': 'gram5-present-participle'},
 {'correct': [],
  'incorrect': [('australia', 'australian', 'france', 'french'),
   ('australia', 'australian', 'india', 'indian'),
   ('australia', 'australian', 'israel', 'israeli'),
   ('australia', 'australian', 'switzerland', 'swiss'),
   ('france', 'french', 'india', 'indian'),
   ('france', 'french', 'israel', 'israeli'),
   ('france', 'french', 'switzerland', 'swiss'),
   ('france', 'french', 'australia', 'australian'),
   ('india', 'indian', 'israel', 'israeli'),
   ('india', 'indian', 'switzerland', 'swiss'),
   ('india', 'indian', 'australia', 'australian'),
   ('india', 'indian', 'france', 'french'),
   ('israel', 'israeli', 'switzerland', 'swiss'),
   ('israel', 'israeli', 'australia', 'australian'),
   ('israel', 'israeli', 'france', 'french'),
   ('israel', 'israeli', 'india', 'indian'),
   ('switzerland', 'swiss', 'australia', 'australian'),
   ('switzerland', 'swiss', 'france', 'french'),
   ('switzerland', 'swiss', 'india', 'indian'),
   ('switzerland', 'swiss', 'israel', 'israeli')],
  'section': 'gram6-nationality-adjective'},
 {'correct': [],
  'incorrect': [('going', 'went', 'paying', 'paid'),
   ('going', 'went', 'playing', 'played'),
   ('going', 'went', 'saying', 'said'),
   ('going', 'went', 'taking', 'took'),
   ('paying', 'paid', 'playing', 'played'),
   ('paying', 'paid', 'saying', 'said'),
   ('paying', 'paid', 'taking', 'took'),
   ('paying', 'paid', 'going', 'went'),
   ('playing', 'played', 'saying', 'said'),
   ('playing', 'played', 'taking', 'took'),
   ('playing', 'played', 'going', 'went'),
   ('playing', 'played', 'paying', 'paid'),
   ('saying', 'said', 'taking', 'took'),
   ('saying', 'said', 'going', 'went'),
   ('saying', 'said', 'paying', 'paid'),
   ('saying', 'said', 'playing', 'played'),
   ('taking', 'took', 'going', 'went'),
   ('taking', 'took', 'paying', 'paid'),
   ('taking', 'took', 'playing', 'played'),
   ('taking', 'took', 'saying', 'said')],
  'section': 'gram7-past-tense'},
 {'correct': [],
  'incorrect': [('building', 'buildings', 'car', 'cars'),
   ('building', 'buildings', 'child', 'children'),
   ('building', 'buildings', 'man', 'men'),
   ('car', 'cars', 'child', 'children'),
   ('car', 'cars', 'man', 'men'),
   ('car', 'cars', 'building', 'buildings'),
   ('child', 'children', 'man', 'men'),
   ('child', 'children', 'building', 'buildings'),
   ('child', 'children', 'car', 'cars'),
   ('man', 'men', 'building', 'buildings'),
   ('man', 'men', 'car', 'cars'),
   ('man', 'men', 'child', 'children')],
  'section': 'gram8-plural'},
 {'correct': [], 'incorrect': [], 'section': 'gram9-plural-verbs'},
 {'correct': [],
  'incorrect': [('he', 'she', 'his', 'her'),
   ('his', 'her', 'he', 'she'),
   ('good', 'better', 'great', 'greater'),
   ('good', 'better', 'long', 'longer'),
   ('good', 'better', 'low', 'lower'),
   ('great', 'greater', 'long', 'longer'),
   ('great', 'greater', 'low', 'lower'),
   ('great', 'greater', 'good', 'better'),
   ('long', 'longer', 'low', 'lower'),
   ('long', 'longer', 'good', 'better'),
   ('long', 'longer', 'great', 'greater'),
   ('low', 'lower', 'good', 'better'),
   ('low', 'lower', 'great', 'greater'),
   ('low', 'lower', 'long', 'longer'),
   ('big', 'biggest', 'good', 'best'),
   ('big', 'biggest', 'great', 'greatest'),
   ('big', 'biggest', 'large', 'largest'),
   ('good', 'best', 'great', 'greatest'),
   ('good', 'best', 'large', 'largest'),
   ('good', 'best', 'big', 'biggest'),
   ('great', 'greatest', 'large', 'largest'),
   ('great', 'greatest', 'big', 'biggest'),
   ('great', 'greatest', 'good', 'best'),
   ('large', 'largest', 'big', 'biggest'),
   ('large', 'largest', 'good', 'best'),
   ('large', 'largest', 'great', 'greatest'),
   ('go', 'going', 'look', 'looking'),
   ('go', 'going', 'play', 'playing'),
   ('go', 'going', 'run', 'running'),
   ('go', 'going', 'say', 'saying'),
   ('look', 'looking', 'play', 'playing'),
   ('look', 'looking', 'run', 'running'),
   ('look', 'looking', 'say', 'saying'),
   ('look', 'looking', 'go', 'going'),
   ('play', 'playing', 'run', 'running'),
   ('play', 'playing', 'say', 'saying'),
   ('play', 'playing', 'go', 'going'),
   ('play', 'playing', 'look', 'looking'),
   ('run', 'running', 'say', 'saying'),
   ('run', 'running', 'go', 'going'),
   ('run', 'running', 'look', 'looking'),
   ('run', 'running', 'play', 'playing'),
   ('say', 'saying', 'go', 'going'),
   ('say', 'saying', 'look', 'looking'),
   ('say', 'saying', 'play', 'playing'),
   ('say', 'saying', 'run', 'running'),
   ('australia', 'australian', 'france', 'french'),
   ('australia', 'australian', 'india', 'indian'),
   ('australia', 'australian', 'israel', 'israeli'),
   ('australia', 'australian', 'switzerland', 'swiss'),
   ('france', 'french', 'india', 'indian'),
   ('france', 'french', 'israel', 'israeli'),
   ('france', 'french', 'switzerland', 'swiss'),
   ('france', 'french', 'australia', 'australian'),
   ('india', 'indian', 'israel', 'israeli'),
   ('india', 'indian', 'switzerland', 'swiss'),
   ('india', 'indian', 'australia', 'australian'),
   ('india', 'indian', 'france', 'french'),
   ('israel', 'israeli', 'switzerland', 'swiss'),
   ('israel', 'israeli', 'australia', 'australian'),
   ('israel', 'israeli', 'france', 'french'),
   ('israel', 'israeli', 'india', 'indian'),
   ('switzerland', 'swiss', 'australia', 'australian'),
   ('switzerland', 'swiss', 'france', 'french'),
   ('switzerland', 'swiss', 'india', 'indian'),
   ('switzerland', 'swiss', 'israel', 'israeli'),
   ('going', 'went', 'paying', 'paid'),
   ('going', 'went', 'playing', 'played'),
   ('going', 'went', 'saying', 'said'),
   ('going', 'went', 'taking', 'took'),
   ('paying', 'paid', 'playing', 'played'),
   ('paying', 'paid', 'saying', 'said'),
   ('paying', 'paid', 'taking', 'took'),
   ('paying', 'paid', 'going', 'went'),
   ('playing', 'played', 'saying', 'said'),
   ('playing', 'played', 'taking', 'took'),
   ('playing', 'played', 'going', 'went'),
   ('playing', 'played', 'paying', 'paid'),
   ('saying', 'said', 'taking', 'took'),
   ('saying', 'said', 'going', 'went'),
   ('saying', 'said', 'paying', 'paid'),
   ('saying', 'said', 'playing', 'played'),
   ('taking', 'took', 'going', 'went'),
   ('taking', 'took', 'paying', 'paid'),
   ('taking', 'took', 'playing', 'played'),
   ('taking', 'took', 'saying', 'said'),
   ('building', 'buildings', 'car', 'cars'),
   ('building', 'buildings', 'child', 'children'),
   ('building', 'buildings', 'man', 'men'),
   ('car', 'cars', 'child', 'children'),
   ('car', 'cars', 'man', 'men'),
   ('car', 'cars', 'building', 'buildings'),
   ('child', 'children', 'man', 'men'),
   ('child', 'children', 'building', 'buildings'),
   ('child', 'children', 'car', 'cars'),
   ('man', 'men', 'building', 'buildings'),
   ('man', 'men', 'car', 'cars'),
   ('man', 'men', 'child', 'children')],
  'section': 'total'}]

This accuracy takes an optional parameter restrict_vocab which limits which test examples are to be considered.

Once again, good performance on this 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.

Storing and loading models

You can store/load models using the standard gensim methods:


In [14]:
model.save('/tmp/mymodel')
new_model = gensim.models.Word2Vec.load('/tmp/mymodel')

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.

In addition, you can load models created by the original C tool, both using its text and binary formats:

model = gensim.models.Word2Vec.load_word2vec_format('/tmp/vectors.txt', binary=False)
# using gzipped/bz2 input works too, no need to unzip:
model = gensim.models.Word2Vec.load_word2vec_format('/tmp/vectors.bin.gz', binary=True)

Online training / Resuming training

Advanced users can load a model and continue training it with more sentences:


In [15]:
model = gensim.models.Word2Vec.load('/tmp/mymodel')
more_sentences = ['Advanced', 'users', 'can', 'load', 'a', 'model', 'and', 'continue', 
                  'training', 'it', 'with', 'more', 'sentences']
model.train(more_sentences)


Out[15]:
36

You may need to tweak the total_words parameter to train(), depending on what learning rate decay you want to simulate.

Note that it’s not possible to resume training with models generated by the C tool, load_word2vec_format(). You can still use them for querying/similarity, but information vital for training (the vocab tree) is missing there.

Using the model

Word2Vec supports several word similarity tasks out of the box:


In [16]:
model.most_similar(positive=['human', 'crime'], negative=['party'], topn=1)


Out[16]:
[('helicopter', 0.9949122071266174)]

In [17]:
model.doesnt_match("input is lunch he sentence cat".split())


Out[17]:
'sentence'

In [18]:
print(model.similarity('human', 'party'))
print(model.similarity('tree', 'murder'))


0.998915674307
0.996301608444

If you need the raw output vectors in your application, you can access these either on a word-by-word basis:


In [19]:
model['tree']  # raw NumPy vector of a word


Out[19]:
array([-0.02622301,  0.01679552, -0.05975026,  0.05937562,  0.00395481,
        0.01808251, -0.037967  , -0.02600464, -0.08010514,  0.0598273 ,
        0.02424216,  0.02164505,  0.0238757 , -0.00206093, -0.05059185,
       -0.0298525 , -0.0542967 ,  0.05837619,  0.01768288,  0.00365469,
       -0.04358177, -0.05000986, -0.06324442, -0.00651763, -0.02177013,
        0.03044847, -0.06225781,  0.0365306 , -0.04124436, -0.02011027,
       -0.0035524 ,  0.02235252,  0.02310976,  0.04918316,  0.05526228,
       -0.03340416,  0.01913262,  0.04928191, -0.08076385, -0.01703318,
       -0.05735664,  0.0237379 ,  0.06574482, -0.05232739, -0.0481467 ,
       -0.04408929, -0.0091858 ,  0.0348591 ,  0.01225438, -0.01833322,
       -0.03986658, -0.03545917,  0.00323616, -0.03138189, -0.04872144,
       -0.00579548,  0.0151679 ,  0.05251733, -0.03962361,  0.0248026 ,
        0.09740256,  0.00694422,  0.0224501 ,  0.01853447,  0.01327971,
        0.01537449, -0.03463763,  0.05694218, -0.01249354, -0.00574434,
        0.02620831, -0.02854559,  0.05720489,  0.00525994,  0.02468183,
       -0.04436401,  0.05477333, -0.05540074,  0.00678445, -0.0316931 ,
       -0.08551864,  0.02775949, -0.09449005, -0.04240174, -0.08187556,
       -0.0467745 ,  0.0162636 ,  0.00628368,  0.00774509, -0.0251303 ,
       -0.00208557,  0.06682073,  0.02089637,  0.01217838,  0.03029196,
       -0.01084006,  0.02253795,  0.05120053, -0.03026446,  0.02492383], dtype=float32)

…or en-masse as a 2D NumPy matrix from model.syn0.

Outro

There is a Bonus App on the original blog post, which runs word2vec on the Google News dataset, of about 100 billion words.

Full word2vec API docs here; get gensim here. Original C toolkit and word2vec papers by Google here.