Skip-gram word2vec

In this notebook, I'll lead you through using TensorFlow to implement the word2vec algorithm using the skip-gram architecture. By implementing this, you'll learn about embedding words for use in natural language processing. This will come in handy when dealing with things like machine translation.

Readings

Here are the resources I used to build this notebook. I suggest reading these either beforehand or while you're working on this material.

Word embeddings

When you're dealing with words in text, you end up with tens of thousands of classes to predict, one for each word. Trying to one-hot encode these words is massively inefficient, you'll have one element set to 1 and the other 50,000 set to 0. The matrix multiplication going into the first hidden layer will have almost all of the resulting values be zero. This a huge waste of computation.

To solve this problem and greatly increase the efficiency of our networks, we use what are called embeddings. Embeddings are just a fully connected layer like you've seen before. We call this layer the embedding layer and the weights are embedding weights. We skip the multiplication into the embedding layer by instead directly grabbing the hidden layer values from the weight matrix. We can do this because the multiplication of a one-hot encoded vector with a matrix returns the row of the matrix corresponding the index of the "on" input unit.

Instead of doing the matrix multiplication, we use the weight matrix as a lookup table. We encode the words as integers, for example "heart" is encoded as 958, "mind" as 18094. Then to get hidden layer values for "heart", you just take the 958th row of the embedding matrix. This process is called an embedding lookup and the number of hidden units is the embedding dimension.

There is nothing magical going on here. The embedding lookup table is just a weight matrix. The embedding layer is just a hidden layer. The lookup is just a shortcut for the matrix multiplication. The lookup table is trained just like any weight matrix as well.

Embeddings aren't only used for words of course. You can use them for any model where you have a massive number of classes. A particular type of model called Word2Vec uses the embedding layer to find vector representations of words that contain semantic meaning.

Word2Vec

The word2vec algorithm finds much more efficient representations by finding vectors that represent the words. These vectors also contain semantic information about the words. Words that show up in similar contexts, such as "black", "white", and "red" will have vectors near each other. There are two architectures for implementing word2vec, CBOW (Continuous Bag-Of-Words) and Skip-gram.

In this implementation, we'll be using the skip-gram architecture because it performs better than CBOW. Here, we pass in a word and try to predict the words surrounding it in the text. In this way, we can train the network to learn representations for words that show up in similar contexts.

First up, importing packages.


In [1]:
import time

import numpy as np
import tensorflow as tf

import utils

Load the text8 dataset, a file of cleaned up Wikipedia articles from Matt Mahoney. The next cell will download the data set to the data folder. Then you can extract it and delete the archive file to save storage space.


In [3]:
from urllib.request import urlretrieve
from os.path import isfile, isdir
from tqdm import tqdm
import zipfile

dataset_folder_path = 'data'
dataset_filename = 'text8.zip'
dataset_name = 'Text8 Dataset'

class DLProgress(tqdm):
    last_block = 0

    def hook(self, block_num=1, block_size=1, total_size=None):
        self.total = total_size
        self.update((block_num - self.last_block) * block_size)
        self.last_block = block_num

if not isfile(dataset_filename):
    with DLProgress(unit='B', unit_scale=True, miniters=1, desc=dataset_name) as pbar:
        urlretrieve(
            'http://mattmahoney.net/dc/text8.zip',
            dataset_filename,
            pbar.hook)

if not isdir(dataset_folder_path):
    with zipfile.ZipFile(dataset_filename) as zip_ref:
        zip_ref.extractall(dataset_folder_path)
        
with open('data/text8') as f:
    text = f.read()

Preprocessing

Here I'm fixing up the text to make training easier. This comes from the utils module I wrote. The preprocess function coverts any punctuation into tokens, so a period is changed to <PERIOD>. In this data set, there aren't any periods, but it will help in other NLP problems. I'm also removing all words that show up five or fewer times in the dataset. This will greatly reduce issues due to noise in the data and improve the quality of the vector representations. If you want to write your own functions for this stuff, go for it.


In [4]:
words = utils.preprocess(text)
print(words[:30])


['anarchism', 'originated', 'as', 'a', 'term', 'of', 'abuse', 'first', 'used', 'against', 'early', 'working', 'class', 'radicals', 'including', 'the', 'diggers', 'of', 'the', 'english', 'revolution', 'and', 'the', 'sans', 'culottes', 'of', 'the', 'french', 'revolution', 'whilst']

In [5]:
print("Total words: {}".format(len(words)))
print("Unique words: {}".format(len(set(words))))


Total words: 16680599
Unique words: 63641

And here I'm creating dictionaries to covert words to integers and backwards, integers to words. The integers are assigned in descending frequency order, so the most frequent word ("the") is given the integer 0 and the next most frequent is 1 and so on. The words are converted to integers and stored in the list int_words.


In [6]:
vocab_to_int, int_to_vocab = utils.create_lookup_tables(words)
int_words = [vocab_to_int[word] for word in words]

Subsampling

Words that show up often such as "the", "of", and "for" don't provide much context to the nearby words. If we discard some of them, we can remove some of the noise from our data and in return get faster training and better representations. This process is called subsampling by Mikolov. For each word $w_i$ in the training set, we'll discard it with probability given by

$$ P(w_i) = 1 - \sqrt{\frac{t}{f(w_i)}} $$

where $t$ is a threshold parameter and $f(w_i)$ is the frequency of word $w_i$ in the total dataset.

I'm going to leave this up to you as an exercise. Check out my solution to see how I did it.

Exercise: Implement subsampling for the words in int_words. That is, go through int_words and discard each word given the probablility $P(w_i)$ shown above. Note that $P(w_i)$ is that probability that a word is discarded. Assign the subsampled data to train_words.


In [25]:
np.random.rand()


Out[25]:
0.9102303221110188

In [29]:
## Your code here
from collections import Counter
word_counter = Counter(int_words)
#Absolute frequency
WORD_THRESHOLD = 300
prob_dict = {}
for word in word_counter:
    prob = 1 - np.sqrt(WORD_THRESHOLD / word_counter[word])
    prob_dict[word] = prob

'''
np.random.rand restituisce valore tra 0 e 1 
prod_dict[word] rappresenta la probabilità che la data parola debba essere scartata
1 - prod_dict[word] invece la prob che la parola debba essere tenuta
Se la prob_dict[word] è alta (molto prob da scartare), 1 - prob_dict[word] sarà molto basso
di conseguenza sarà improbabile che np.random.rand() restituirà un valore che superi la soglia per essere ammesso nella lista
'''
train_words = []
for word in int_words:
    if np.random.rand() < (1 - prob_dict[word]):
        train_words.append(word)
len(train_words)


Out[29]:
5534974

Making batches

Now that our data is in good shape, we need to get it into the proper form to pass it into our network. With the skip-gram architecture, for each word in the text, we want to grab all the words in a window around that word, with size $C$.

From Mikolov et al.:

"Since the more distant words are usually less related to the current word than those close to it, we give less weight to the distant words by sampling less from those words in our training examples... If we choose $C = 5$, for each training word we will select randomly a number $R$ in range $< 1; C >$, and then use $R$ words from history and $R$ words from the future of the current word as correct labels."

Exercise: Implement a function get_target that receives a list of words, an index, and a window size, then returns a list of words in the window around the index. Make sure to use the algorithm described above, where you choose a random number of words from the window.


In [35]:
from random import randint
def get_target(words, idx, window_size=5):
    ''' Get a list of words in a window around an index. '''
    random_size = randint(1, window_size)
    #L'indice di start può essere negativo, se quello di fine supera la fine PYTHON prende comunque l'ultimo
    #Uso inline if
    start_idx = idx - random_size if idx - random_size > 0 else 0
    #Deve essere un set per evitare parole ripetute nel target.
    #La seconda parte deve incrementare l'indice di 1 per evitare di includere la parola stessa
    context = set(words[start_idx:random_size] + words[idx+1:(idx+1)+random_size])
    return context

Here's a function that returns batches for our network. The idea is that it grabs batch_size words from a words list. Then for each of those words, it gets the target words in the window. I haven't found a way to pass in a random number of target words and get it to work with the architecture, so I make one row per input-target pair. This is a generator function by the way, helps save memory.


In [36]:
def get_batches(words, batch_size, window_size=5):
    ''' Create a generator of word batches as a tuple (inputs, targets) '''
    
    n_batches = len(words)//batch_size
    
    # only full batches
    words = words[:n_batches*batch_size]
    
    for idx in range(0, len(words), batch_size):
        x, y = [], []
        batch = words[idx:idx+batch_size]
        for ii in range(len(batch)):
            batch_x = batch[ii]
            batch_y = get_target(batch, ii, window_size)
            y.extend(batch_y)
            x.extend([batch_x]*len(batch_y))
        yield x, y

In [41]:
text_x, test_y = next(get_batches(int_words, batch_size=128, window_size=5))
print(np.array(text_x).shape)
print(np.array(test_y).shape)


(382,)
(382,)

Building the graph

From Chris McCormick's blog, we can see the general structure of our network.

The input words are passed in as integers. This will go into a hidden layer of linear units, then into a softmax layer. We'll use the softmax layer to make a prediction like normal.

The idea here is to train the hidden layer weight matrix to find efficient representations for our words. We can discard the softmax layer becuase we don't really care about making predictions with this network. We just want the embedding matrix so we can use it in other networks we build from the dataset.

I'm going to have you build the graph in stages now. First off, creating the inputs and labels placeholders like normal.

Exercise: Assign inputs and labels using tf.placeholder. We're going to be passing in integers, so set the data types to tf.int32. The batches we're passing in will have varying sizes, so set the batch sizes to [None]. To make things work later, you'll need to set the second dimension of labels to None or 1.


In [42]:
train_graph = tf.Graph()
with train_graph.as_default():
    #Batch size may vary
    inputs = tf.placeholder(tf.int32, [None], name='inputs')
    #Batch size and window may vary
    labels = tf.placeholder(tf.int32, [None, None], name='labels')

Embedding

The embedding matrix has a size of the number of words by the number of units in the hidden layer. So, if you have 10,000 words and 300 hidden units, the matrix will have size $10,000 \times 300$. Remember that we're using tokenized data for our inputs, usually as integers, where the number of tokens is the number of words in our vocabulary.

Exercise: Tensorflow provides a convenient function tf.nn.embedding_lookup that does this lookup for us. You pass in the embedding matrix and a tensor of integers, then it returns rows in the matrix corresponding to those integers. Below, set the number of embedding features you'll use (200 is a good start), create the embedding matrix variable, and use tf.nn.embedding_lookup to get the embedding tensors. For the embedding matrix, I suggest you initialize it with a uniform random numbers between -1 and 1 using tf.random_uniform.


In [43]:
n_vocab = len(int_to_vocab)
n_embedding = 300 # Number of embedding features 
with train_graph.as_default():
    embedding = tf.Variable(tf.truncated_normal((n_vocab, n_embedding),stddev=0.1))# create embedding weight matrix here
    #Lookup in embedding di inputs
    embed = tf.nn.embedding_lookup(params=embedding, ids=inputs)# use tf.nn.embedding_lookup to get the hidden layer output

Negative sampling

For every example we give the network, we train it using the output from the softmax layer. That means for each input, we're making very small changes to millions of weights even though we only have one true example. This makes training the network very inefficient. We can approximate the loss from the softmax layer by only updating a small subset of all the weights at once. We'll update the weights for the correct label, but only a small number of incorrect labels. This is called "negative sampling". Tensorflow has a convenient function to do this, tf.nn.sampled_softmax_loss.

Exercise: Below, create weights and biases for the softmax layer. Then, use tf.nn.sampled_softmax_loss to calculate the loss. Be sure to read the documentation to figure out how it works.


In [44]:
# Number of negative labels to sample
n_sampled = 100
with train_graph.as_default():
    #Guarda doc sampled_softmax_loss, i weights devono essere nella forma [num_classes, dim]
    softmax_w = tf.Variable(tf.truncated_normal((n_vocab, n_embedding),stddev=0.01))# create softmax weight matrix here
    #I label sono sempre i vocaboli attorno
    softmax_b = tf.Variable(tf.zeros(n_vocab))# create softmax biases here
    
    # Calculate the loss using negative sampling
    loss = tf.nn.sampled_softmax_loss(weights=softmax_w,
                                      biases=softmax_b,
                                      labels=labels,
                                      inputs=embed,
                                      num_sampled=n_sampled,
                                      num_classes=n_vocab)
    
    cost = tf.reduce_mean(loss)
    optimizer = tf.train.AdamOptimizer().minimize(cost)

Validation

This code is from Thushan Ganegedara's implementation. Here we're going to choose a few common words and few uncommon words. Then, we'll print out the closest words to them. It's a nice way to check that our embedding table is grouping together words with similar semantic meanings.


In [46]:
import random
with train_graph.as_default():
    ## From Thushan Ganegedara's implementation
    valid_size = 16 # Random set of words to evaluate similarity on.
    valid_window = 100
    # pick 8 samples from (0,100) and (1000,1100) each ranges. lower id implies more frequent 
    valid_examples = np.array(random.sample(range(valid_window), valid_size//2))
    valid_examples = np.append(valid_examples, 
                               random.sample(range(1000,1000+valid_window), valid_size//2))

    valid_dataset = tf.constant(valid_examples, dtype=tf.int32)
    
    # We use the cosine distance:
    norm = tf.sqrt(tf.reduce_sum(tf.square(embedding), 1, keep_dims=True))
    normalized_embedding = embedding / norm
    valid_embedding = tf.nn.embedding_lookup(normalized_embedding, valid_dataset)
    similarity = tf.matmul(valid_embedding, tf.transpose(normalized_embedding))

In [47]:
# If the checkpoints directory doesn't exist:
!mkdir checkpoints

Training

Below is the code to train the network. Every 100 batches it reports the training loss. Every 1000 batches, it'll print out the validation words.


In [50]:
for i in range(1000):
    sys.stdout.write("\r" + str(i))
    sys.stdout.flush()


999

In [53]:
import sys
epochs = 10
batch_size = 1000
window_size = 10

with train_graph.as_default():
    saver = tf.train.Saver()

with tf.Session(graph=train_graph) as sess:
    iteration = 1
    loss = 0
    sess.run(tf.global_variables_initializer())

    for e in range(1, epochs+1):
        batches = get_batches(train_words, batch_size, window_size)
        start = time.time()
        for x, y in batches:
            
            feed = {inputs: x,
                    labels: np.array(y)[:, None]}
            train_loss, _ = sess.run([cost, optimizer], feed_dict=feed)
            
            loss += train_loss
            
            if iteration % 100 == 0: 
                end = time.time()
                sys.stdout.write("\rEpoch {}/{} ".format(e, epochs) + 
                      "Iteration: {} ".format(iteration) + 
                      "Avg. Training loss: {:.4f} ".format(loss/100) + 
                      "{:.4f} sec/batch".format((end-start)/100))
                sys.stdout.flush()
                loss = 0
                start = time.time()
            
            if iteration % 1000 == 0:
                ## From Thushan Ganegedara's implementation
                # note that this is expensive (~20% slowdown if computed every 500 steps)
                sim = similarity.eval()
                for i in range(valid_size):
                    valid_word = int_to_vocab[valid_examples[i]]
                    top_k = 8 # number of nearest neighbors
                    nearest = (-sim[i, :]).argsort()[1:top_k+1]
                    log = 'Nearest to %s:' % valid_word
                    for k in range(top_k):
                        close_word = int_to_vocab[nearest[k]]
                        log = '%s %s,' % (log, close_word)
                    print(log)
            
            iteration += 1
    save_path = saver.save(sess, "checkpoints/text8.ckpt")
    embed_mat = sess.run(normalized_embedding)


Epoch 1/10 Iteration: 1000 Avg. Training loss: 4.8019 0.3627 sec/batchNearest to of: and, the, in, from, on, as, are, their,
Nearest to i: me, life, aside, nor, earth, means, said, thus,
Nearest to and: of, which, in, an, the, are, no, take,
Nearest to by: in, the, as, at, their, from, of, however,
Nearest to seven: nine, eight, six, one, three, five, four, zero,
Nearest to after: first, viii, th, british, france, membership, returned, people,
Nearest to s: life, led, role, about, august, thus, least, xiv,
Nearest to be: this, or, it, that, more, have, are, has,
Nearest to shows: manner, whatever, security, properly, deployed, greater, usage, primarily,
Nearest to recorded: moderate, yankee, treaty, spain, descent, issued, mandate, actual,
Nearest to woman: revived, largely, recovery, chambers, children, thinking, derived, crete,
Nearest to alternative: liable, prototype, session, integers, reviewed, appear, clark, supernatural,
Nearest to additional: pace, tend, problematic, data, adult, fewer, examination, storage,
Nearest to smith: apple, nash, numbering, relics, spain, singles, acknowledge, exercise,
Nearest to primarily: interact, palestine, nato, represents, duration, left, right, intense,
Nearest to marriage: contest, highways, sovereignty, median, undoubtedly, admitted, israeli, devastated,
Epoch 1/10 Iteration: 2000 Avg. Training loss: 4.6811 0.3675 sec/batchNearest to of: and, in, the, from, people, as, least, name,
Nearest to i: me, you, said, life, my, nor, we, divine,
Nearest to and: of, in, the, an, its, to, by, at,
Nearest to by: in, the, and, of, as, from, at, were,
Nearest to seven: six, eight, nine, one, isbn, three, five, four,
Nearest to after: france, named, was, army, returned, ii, first, he,
Nearest to s: life, and, in, of, least, was, reading, led,
Nearest to be: this, or, cannot, should, that, not, can, if,
Nearest to shows: emphasis, makes, usage, protection, something, forming, believes, purposes,
Nearest to recorded: migrated, captain, yankee, manfred, during, britain, founding, reading,
Nearest to woman: children, wife, recently, malthus, london, fall, teacher, saw,
Nearest to alternative: here, fundamental, paper, scope, or, truth, adds, names,
Nearest to additional: storage, system, pure, data, require, reduce, specified, problematic,
Nearest to smith: jr, journal, press, hogan, hearted, amadeus, born, neil,
Nearest to primarily: represents, resulting, interact, duration, readily, types, accurate, forming,
Nearest to marriage: bishop, adopted, catholics, divorce, father, admitted, children, celebrated,
Epoch 1/10 Iteration: 3000 Avg. Training loss: 4.5391 0.3706 sec/batchNearest to of: and, in, the, from, as, by, history, accepted,
Nearest to i: me, you, we, v, my, know, if, said,
Nearest to and: of, in, the, to, as, by, an, its,
Nearest to by: in, the, as, and, of, to, having, from,
Nearest to seven: six, eight, nine, three, one, five, four, statesman,
Nearest to after: returned, army, him, was, named, invasion, rebellion, during,
Nearest to s: and, role, life, a, in, story, career, on,
Nearest to be: this, cannot, it, or, should, can, not, but,
Nearest to shows: fiction, for, humorously, schoenberg, recurring, cathodes, emphasis, phine,
Nearest to recorded: songs, burton, late, buffett, terror, manfred, concert, yankee,
Nearest to woman: children, wife, married, who, whom, died, her, father,
Nearest to alternative: content, specification, implicit, documentation, odd, selection, frame, non,
Nearest to additional: storage, require, data, obtains, specified, system, material, reduce,
Nearest to smith: jr, james, born, journalist, thomas, dan, publisher, screenwriter,
Nearest to primarily: resulting, opined, subdivide, scatters, readily, accelerate, providing, penetrating,
Nearest to marriage: father, wife, whom, daughter, throne, married, she, emperor,
Epoch 1/10 Iteration: 3500 Avg. Training loss: 4.5374 0.3956 sec/batch
---------------------------------------------------------------------------
KeyboardInterrupt                         Traceback (most recent call last)
<ipython-input-53-5e77dc089ce2> in <module>()
     19             feed = {inputs: x,
     20                     labels: np.array(y)[:, None]}
---> 21             train_loss, _ = sess.run([cost, optimizer], feed_dict=feed)
     22 
     23             loss += train_loss

~/anaconda/envs/deepEnv/lib/python3.5/site-packages/tensorflow/python/client/session.py in run(self, fetches, feed_dict, options, run_metadata)
    787     try:
    788       result = self._run(None, fetches, feed_dict, options_ptr,
--> 789                          run_metadata_ptr)
    790       if run_metadata:
    791         proto_data = tf_session.TF_GetBuffer(run_metadata_ptr)

~/anaconda/envs/deepEnv/lib/python3.5/site-packages/tensorflow/python/client/session.py in _run(self, handle, fetches, feed_dict, options, run_metadata)
    995     if final_fetches or final_targets:
    996       results = self._do_run(handle, final_targets, final_fetches,
--> 997                              feed_dict_string, options, run_metadata)
    998     else:
    999       results = []

~/anaconda/envs/deepEnv/lib/python3.5/site-packages/tensorflow/python/client/session.py in _do_run(self, handle, target_list, fetch_list, feed_dict, options, run_metadata)
   1130     if handle is None:
   1131       return self._do_call(_run_fn, self._session, feed_dict, fetch_list,
-> 1132                            target_list, options, run_metadata)
   1133     else:
   1134       return self._do_call(_prun_fn, self._session, handle, feed_dict,

~/anaconda/envs/deepEnv/lib/python3.5/site-packages/tensorflow/python/client/session.py in _do_call(self, fn, *args)
   1137   def _do_call(self, fn, *args):
   1138     try:
-> 1139       return fn(*args)
   1140     except errors.OpError as e:
   1141       message = compat.as_text(e.message)

~/anaconda/envs/deepEnv/lib/python3.5/site-packages/tensorflow/python/client/session.py in _run_fn(session, feed_dict, fetch_list, target_list, options, run_metadata)
   1119         return tf_session.TF_Run(session, options,
   1120                                  feed_dict, fetch_list, target_list,
-> 1121                                  status, run_metadata)
   1122 
   1123     def _prun_fn(session, handle, feed_dict, fetch_list):

KeyboardInterrupt: 

Restore the trained network if you need to:


In [ ]:
with train_graph.as_default():
    saver = tf.train.Saver()

with tf.Session(graph=train_graph) as sess:
    saver.restore(sess, tf.train.latest_checkpoint('checkpoints'))
    embed_mat = sess.run(embedding)

Visualizing the word vectors

Below we'll use T-SNE to visualize how our high-dimensional word vectors cluster together. T-SNE is used to project these vectors into two dimensions while preserving local stucture. Check out this post from Christopher Olah to learn more about T-SNE and other ways to visualize high-dimensional data.


In [ ]:
%matplotlib inline
%config InlineBackend.figure_format = 'retina'

import matplotlib.pyplot as plt
from sklearn.manifold import TSNE

In [ ]:
viz_words = 500
tsne = TSNE()
embed_tsne = tsne.fit_transform(embed_mat[:viz_words, :])

In [ ]:
fig, ax = plt.subplots(figsize=(14, 14))
for idx in range(viz_words):
    plt.scatter(*embed_tsne[idx, :], color='steelblue')
    plt.annotate(int_to_vocab[idx], (embed_tsne[idx, 0], embed_tsne[idx, 1]), alpha=0.7)