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

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 language and words, 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 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 [2]:
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 [3]:
words = utils.preprocess(text)
print(words[30:35])


['the', 'term', 'is', 'still', 'used']

In [4]:
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 [5]:
vocab_to_int, int_to_vocab = utils.create_lookup_tables(words)

In [6]:
print(vocab_to_int['the'])
print(int_to_vocab[3528])


0
blind

In [7]:
len(int_to_vocab)


Out[7]:
63641

In [8]:
int_words = [vocab_to_int[word] for word in words]

In [9]:
print(words[0:30])
print(int_words[0: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']
[5238, 3082, 11, 5, 194, 1, 3135, 45, 58, 155, 127, 741, 476, 10632, 133, 0, 27441, 1, 0, 102, 854, 2, 0, 15082, 61873, 1, 0, 150, 854, 3583]

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. This is more of a programming challenge, than about deep learning specifically. But, being able to prepare your data for your network is an important skill to have. 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 the probability that a word is discarded. Assign the subsampled data to train_words.


In [10]:
int_words.count(3528)


Out[10]:
489

In [11]:
import random as rnd
np.random.rand()


Out[11]:
0.35150989879073247

In [12]:
import random
from collections import Counter

## Your code here

train_words = []

words_counter = Counter(int_words)
total_number_words = len(int_words)
k = 0.00001
#freq = {word:count/tot_count for word,count in words_counter.items()}
prob_words = [1-np.sqrt(k/(words_counter[i]/total_number_words)) for i in range(len(vocab_to_int))]
for int_word in int_words:
    if prob_words[int_word] < random.random():
        train_words.append(int_word)

In [13]:
print(len(int_words))
print(len(train_words))


16680599
4626248

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 [14]:
def get_target(words, idx, window_size=1):
    ''' Get a list of words in a window around an index. '''
    list_words =[]
    # Your code here
    R = random.randint(1,window_size+1)
    start = idx - R if (idx - R) > 0 else 0
    end = idx + R
    set_words = set(words[start:idx] + words[idx+1:end+1] )
    #range_test = [start:idx] + [idx+1:end+1]

    #print(range_test, " with index = ", idx, " , R = " , R)


    return list(set_words)

In [15]:
def get_target_edited(words, idx, window_size=5):
    ''' Get a list of words in a window around an index. '''
    list_words =[]
    # Your code here
    R = random.randint(1,window_size)
    R_2 = R
    start = idx - R_2 if (idx - R_2) > 0 else 0
    end = idx + R_2
    idx_start = (idx - R if (idx - R) > 0 else 0) 
    idx_end = idx + R
    range_test = list(range(idx+1,idx_end+1))
    print(range_test, " with index = ", idx, " , R = " , R)
    print("words correct: ", words[start:idx] + words[idx+1:end+1])
    print("words incorrect: ", [words[i] for i in list(range(idx_start,idx))+list(range(idx+1,idx_end+1))])

    #print(idx_end+1, " with R : " ,R)
    
    return list(set([words[i] for i in list(range(idx_start,idx))+list(range(idx+1,idx_end+1))]))

In [16]:
get_target_edited(words,100)


[101, 102, 103, 104, 105]  with index =  100  , R =  5
words correct:  ['abolished', 'although', 'there', 'are', 'differing', 'of', 'what', 'this', 'means', 'anarchism']
words incorrect:  ['abolished', 'although', 'there', 'are', 'differing', 'of', 'what', 'this', 'means', 'anarchism']
Out[16]:
['there',
 'anarchism',
 'what',
 'are',
 'of',
 'differing',
 'abolished',
 'this',
 'although',
 'means']

In [17]:
get_target(words,100)


Out[17]:
['differing', 'of']

In [18]:
words[98:102]


Out[18]:
['are', 'differing', 'interpretations', 'of']

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 [19]:
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

Building the graph

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

The input words are passed in as one-hot encoded vectors. 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. This weight matrix is usually called the embedding matrix or embedding look-up table. 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 [20]:
train_graph = tf.Graph()
with train_graph.as_default():
    inputs = tf.placeholder(tf.int32, [None], name='inputs')
    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 neurons 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 one-hot encoded vectors for our inputs. When you do the matrix multiplication of the one-hot vector with the embedding matrix, you end up selecting only one row out of the entire matrix:

You don't actually need to do the matrix multiplication, you just need to select the row in the embedding matrix that corresponds to the input word. Then, the embedding matrix becomes a lookup table, you're looking up a vector the size of the hidden layer that represents the input word.

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. This TensorFlow tutorial will help if you get stuck.


In [21]:
n_vocab = len(int_to_vocab)
n_embedding =  200# Number of embedding features 
with train_graph.as_default():
    #tf.random_uniform((n_vocab, n_embedding), -1, 1)
    embedding = tf.Variable(tf.random_uniform([n_vocab,n_embedding],-1,1), name = 'embedding') # create embedding weight matrix here
    embed = tf.nn.embedding_lookup(embedding,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 [22]:
# Number of negative labels to sample
n_sampled = 100
with train_graph.as_default():
    softmax_w = tf.Variable(tf.random_normal([n_vocab,n_embedding],stddev=0.1))
    softmax_b = tf.Variable(tf.zeros(n_vocab,dtype=tf.float32))
    
    # Calculate the loss using negative sampling
    loss = tf.nn.sampled_softmax_loss(softmax_w, softmax_b, 
                                      labels,embed,n_sampled,
                                      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 [23]:
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 [ ]:
# If the checkpoints directory doesn't exist:
!mkdir checkpoints


mkdir: cannot create directory ‘checkpoints’: File exists

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 [ ]:
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()
                print("Epoch {}/{}".format(e, epochs),
                      "Iteration: {}".format(iteration),
                      "Avg. Training loss: {:.4f}".format(loss/100),
                      "{:.4f} sec/batch".format((end-start)/100))
                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: 100 Avg. Training loss: 5.7151 0.1991 sec/batch
Epoch 1/10 Iteration: 200 Avg. Training loss: 5.6888 0.1975 sec/batch
Epoch 1/10 Iteration: 300 Avg. Training loss: 5.5792 0.1978 sec/batch
Epoch 1/10 Iteration: 400 Avg. Training loss: 5.6401 0.1972 sec/batch
Epoch 1/10 Iteration: 500 Avg. Training loss: 5.5758 0.1983 sec/batch
Epoch 1/10 Iteration: 600 Avg. Training loss: 5.5985 0.1984 sec/batch
Epoch 1/10 Iteration: 700 Avg. Training loss: 5.5951 0.1969 sec/batch
Epoch 1/10 Iteration: 800 Avg. Training loss: 5.5832 0.1988 sec/batch
Epoch 1/10 Iteration: 900 Avg. Training loss: 5.5350 0.2008 sec/batch
Epoch 1/10 Iteration: 1000 Avg. Training loss: 5.4577 0.2011 sec/batch
Nearest to been: abet, comers, spire, brought, warfare, analogs, unpleasant, tenure,
Nearest to will: programmability, spontaneity, trebia, jennings, yaroslav, foote, preside, matthias,
Nearest to often: rude, stresses, levite, toughened, riot, hamadan, gie, cortina,
Nearest to such: lulu, downstairs, oesophagus, deepest, phenethylamines, fulcher, manos, disposable,
Nearest to time: dominican, veselin, sussex, appletalk, blackberry, smallpox, nehru, idris,
Nearest to used: htp, suva, ovaries, unsightly, ciboney, svinhufvud, dominicans, pathname,
Nearest to more: orthoclase, bitkeeper, qualifier, white, lives, moh, banff, berries,
Nearest to over: supercritical, revalued, craftsman, obsession, kie, ena, year, zayas,
Nearest to hold: killer, plotinus, kavina, almanack, tramiel, glitches, leaving, deficient,
Nearest to channel: barajas, pitaka, weizmann, epistolary, spanking, ptsd, clays, hamill,
Nearest to prince: cyrillic, dogmatically, turtles, streaming, rip, jacobs, dictionaries, durrell,
Nearest to square: biograph, frawley, express, nguema, solomon, roof, snuck, adderall,
Nearest to instance: proust, comprehensiveness, vivre, ending, drinks, toni, vivien, harm,
Nearest to gold: chekhov, labonte, analgesic, abortions, snaps, subjects, jaspers, lmann,
Nearest to mean: beauchamp, curta, evaporator, handed, afferent, cosmas, sceptics, buzzing,
Nearest to frac: dai, selznick, tennyson, prevails, debated, roussillon, benedetto, coots,
Epoch 1/10 Iteration: 1100 Avg. Training loss: 5.6019 0.2082 sec/batch
Epoch 1/10 Iteration: 1200 Avg. Training loss: 5.4553 0.2062 sec/batch
Epoch 1/10 Iteration: 1300 Avg. Training loss: 5.4149 0.2061 sec/batch
Epoch 1/10 Iteration: 1400 Avg. Training loss: 5.3233 0.2044 sec/batch
Epoch 1/10 Iteration: 1500 Avg. Training loss: 5.2414 0.2060 sec/batch
Epoch 1/10 Iteration: 1600 Avg. Training loss: 5.2330 0.2077 sec/batch
Epoch 1/10 Iteration: 1700 Avg. Training loss: 5.1839 0.2068 sec/batch
Epoch 1/10 Iteration: 1800 Avg. Training loss: 5.1089 0.2065 sec/batch
Epoch 1/10 Iteration: 1900 Avg. Training loss: 5.1002 0.2062 sec/batch
Epoch 1/10 Iteration: 2000 Avg. Training loss: 5.0840 0.2054 sec/batch
Nearest to been: brought, abet, warfare, unpleasant, spire, varieties, tenure, pikes,
Nearest to will: came, programmability, created, spontaneity, jennings, matthias, represented, trebia,
Nearest to often: stresses, riot, rude, bizarre, giuseppe, extremes, chiefly, toughened,
Nearest to such: lulu, oesophagus, continuity, downstairs, phenethylamines, deepest, disposable, casinos,
Nearest to time: dominican, due, veselin, intense, cartridges, sussex, provided, goodness,
Nearest to used: can, population, encouraged, boasts, salle, ciboney, maps, htp,
Nearest to more: lives, white, orthoclase, moh, bitkeeper, mutual, berries, qualifier,
Nearest to over: year, hall, supercritical, growth, vendor, revalued, craftsman, obsession,
Nearest to hold: leaving, plotinus, tramiel, killer, conducting, anubis, almanack, understand,
Nearest to channel: hamill, weizmann, pitaka, barajas, ptsd, epistolary, clays, humor,
Nearest to prince: cyrillic, streaming, dogmatically, turtles, jacobs, rip, dictionaries, durrell,
Nearest to square: express, roof, solomon, race, biograph, understanding, frawley, adderall,
Nearest to instance: ending, harm, comprehensiveness, drinks, plan, particularly, toni, proust,
Nearest to gold: chekhov, analgesic, labonte, subjects, lmann, jaspers, adjoining, electroshock,
Nearest to mean: curta, handed, implies, cosmas, productive, beauchamp, continue, delaware,
Nearest to frac: dai, prevails, tennyson, roussillon, debated, pole, selznick, benedetto,
Epoch 1/10 Iteration: 2100 Avg. Training loss: 4.9943 0.2111 sec/batch
Epoch 1/10 Iteration: 2200 Avg. Training loss: 4.9662 0.2072 sec/batch
Epoch 1/10 Iteration: 2300 Avg. Training loss: 4.9252 0.2056 sec/batch
Epoch 1/10 Iteration: 2400 Avg. Training loss: 4.9065 0.2091 sec/batch
Epoch 1/10 Iteration: 2500 Avg. Training loss: 4.9081 0.2082 sec/batch
Epoch 1/10 Iteration: 2600 Avg. Training loss: 4.8661 0.2086 sec/batch
Epoch 1/10 Iteration: 2700 Avg. Training loss: 4.8441 0.2091 sec/batch
Epoch 1/10 Iteration: 2800 Avg. Training loss: 4.8668 0.2082 sec/batch
Epoch 1/10 Iteration: 2900 Avg. Training loss: 4.8253 0.2089 sec/batch
Epoch 1/10 Iteration: 3000 Avg. Training loss: 4.8036 0.2099 sec/batch
Nearest to been: warfare, abet, brought, unpleasant, tenure, spire, comers, analogs,
Nearest to will: programmability, created, spontaneity, lingvo, preside, ranking, norman, came,
Nearest to often: riot, stresses, rude, giuseppe, bizarre, toughened, egypt, towns,
Nearest to such: continuity, downstairs, lulu, oesophagus, deepest, isostatic, casinos, stirling,
Nearest to time: dominican, intense, sussex, veselin, cartridges, due, adjustment, smallpox,
Nearest to used: can, subsidies, suva, population, encouraged, htp, ovaries, boasts,
Nearest to more: lives, orthoclase, white, bitkeeper, moh, qualifier, up, mutual,
Nearest to over: supercritical, year, revalued, obsession, craftsman, hall, vendor, ena,
Nearest to hold: killer, leaving, plotinus, reality, tramiel, anubis, conducting, therapists,
Nearest to channel: hamill, blacks, weizmann, ptsd, pitaka, broadcasting, epistolary, clays,
Nearest to prince: cyrillic, streaming, jacobs, construction, rip, spratly, dogmatically, durrell,
Nearest to square: express, roof, solomon, race, biograph, casey, advance, promoting,
Nearest to instance: ending, harm, comprehensiveness, toni, plan, proust, drinks, borrow,
Nearest to gold: chekhov, analgesic, subjects, broader, lmann, integrate, labonte, electroshock,
Nearest to mean: curta, beauchamp, implies, handed, coalitions, buzzing, importantly, evaporator,
Nearest to frac: prevails, dai, tennyson, roussillon, pole, guideline, technically, interrupted,
Epoch 1/10 Iteration: 3100 Avg. Training loss: 4.8248 0.2128 sec/batch
Epoch 1/10 Iteration: 3200 Avg. Training loss: 4.8099 0.2103 sec/batch
Epoch 1/10 Iteration: 3300 Avg. Training loss: 4.7661 0.2091 sec/batch
Epoch 1/10 Iteration: 3400 Avg. Training loss: 4.7392 0.2091 sec/batch
Epoch 1/10 Iteration: 3500 Avg. Training loss: 4.7856 0.2099 sec/batch
Epoch 1/10 Iteration: 3600 Avg. Training loss: 4.7208 0.2101 sec/batch
Epoch 1/10 Iteration: 3700 Avg. Training loss: 4.7501 0.2080 sec/batch
Epoch 1/10 Iteration: 3800 Avg. Training loss: 4.7558 0.2075 sec/batch
Epoch 1/10 Iteration: 3900 Avg. Training loss: 4.7682 0.2094 sec/batch
Epoch 1/10 Iteration: 4000 Avg. Training loss: 4.6860 0.2069 sec/batch
Nearest to been: warfare, abet, spire, analogs, comers, brought, unpleasant, tenure,
Nearest to will: programmability, lingvo, trebia, preside, terabytes, created, foote, represented,
Nearest to often: toughened, stresses, hamadan, cortina, rude, riot, egypt, sequencing,
Nearest to such: downstairs, deepest, lulu, oesophagus, continuity, phenethylamines, isostatic, roddy,
Nearest to time: dominican, intense, smallpox, veselin, sussex, cartridges, retrieving, adjustment,
Nearest to used: can, subsidies, suva, packaging, ovaries, htp, unsightly, abstractions,
Nearest to more: lives, orthoclase, bitkeeper, white, moh, qualifier, up, filed,
Nearest to over: supercritical, year, obsession, revalued, growth, oblast, craftsman, henceforth,
Nearest to hold: killer, leaving, plotinus, tramiel, anubis, reality, prefrontal, wives,
Nearest to channel: hamill, weizmann, broadcasting, epistolary, blacks, spanking, lemon, ptsd,
Nearest to prince: cyrillic, jacobs, streaming, spratly, rip, durrell, construction, turtles,
Nearest to square: roof, express, biograph, solomon, casey, snuck, nguema, race,
Nearest to instance: proust, harm, comprehensiveness, toni, asher, ending, worsened, videogames,
Nearest to gold: chekhov, analgesic, subjects, integrate, lmann, labonte, pardoned, broader,
Nearest to mean: beauchamp, coalitions, curta, specifying, implies, evaporator, presume, buzzing,
Nearest to frac: prevails, roussillon, dai, tennyson, pole, guideline, sempronius, nursery,
Epoch 1/10 Iteration: 4100 Avg. Training loss: 4.7056 0.2105 sec/batch
Epoch 1/10 Iteration: 4200 Avg. Training loss: 4.6937 0.2108 sec/batch
Epoch 1/10 Iteration: 4300 Avg. Training loss: 4.6632 0.2090 sec/batch
Epoch 1/10 Iteration: 4400 Avg. Training loss: 4.6476 0.2088 sec/batch
Epoch 1/10 Iteration: 4500 Avg. Training loss: 4.6623 0.2080 sec/batch
Epoch 1/10 Iteration: 4600 Avg. Training loss: 4.6450 0.2082 sec/batch
Epoch 2/10 Iteration: 4700 Avg. Training loss: 4.6011 0.1570 sec/batch
Epoch 2/10 Iteration: 4800 Avg. Training loss: 4.5848 0.2075 sec/batch
Epoch 2/10 Iteration: 4900 Avg. Training loss: 4.5443 0.2080 sec/batch
Epoch 2/10 Iteration: 5000 Avg. Training loss: 4.5555 0.2075 sec/batch
Nearest to been: warfare, abet, comers, analogs, brought, spire, tenure, unpleasant,
Nearest to will: programmability, lingvo, can, interpreted, represented, created, foote, terabytes,
Nearest to often: hamadan, cortina, toughened, stresses, sequencing, be, levite, suffice,
Nearest to such: downstairs, oesophagus, deepest, continuity, isostatic, phenethylamines, lulu, management,
Nearest to time: intense, dominican, sussex, blackberry, cartridges, idris, smallpox, lois,
Nearest to used: can, packaging, subsidies, abstractions, retirees, suva, ovaries, passers,
Nearest to more: lives, orthoclase, bitkeeper, up, moh, white, involve, filed,
Nearest to over: supercritical, revalued, year, growth, chartered, oblast, reims, ena,
Nearest to hold: killer, leaving, prefrontal, plotinus, anubis, tramiel, therapists, flutter,
Nearest to channel: broadcasting, hamill, weizmann, pitaka, epistolary, barajas, spanking, rackets,
Nearest to prince: cyrillic, spratly, jacobs, cricketer, durrell, streaming, rip, bartolomeo,
Nearest to square: roof, biograph, express, casey, nguema, solomon, snuck, xie,
Nearest to instance: proust, comprehensiveness, asher, harm, interprets, toni, perpetrated, worsened,
Nearest to gold: chekhov, analgesic, subjects, integrate, labonte, snaps, adjoining, evangelists,
Nearest to mean: beauchamp, evaporator, specifying, implies, coalitions, curta, orthopedic, buzzing,
Nearest to frac: prevails, roussillon, dai, guideline, tennyson, sempronius, pole, mordor,
Epoch 2/10 Iteration: 5100 Avg. Training loss: 4.5204 0.2106 sec/batch
Epoch 2/10 Iteration: 5200 Avg. Training loss: 4.5163 0.2091 sec/batch
Epoch 2/10 Iteration: 5300 Avg. Training loss: 4.4859 0.2109 sec/batch
Epoch 2/10 Iteration: 5400 Avg. Training loss: 4.5620 0.2090 sec/batch
Epoch 2/10 Iteration: 5500 Avg. Training loss: 4.5355 0.2093 sec/batch
Epoch 2/10 Iteration: 5600 Avg. Training loss: 4.5237 0.2082 sec/batch
Epoch 2/10 Iteration: 5700 Avg. Training loss: 4.4846 0.2102 sec/batch
Epoch 2/10 Iteration: 5800 Avg. Training loss: 4.4351 0.2081 sec/batch
Epoch 2/10 Iteration: 5900 Avg. Training loss: 4.4646 0.2098 sec/batch
Epoch 2/10 Iteration: 6000 Avg. Training loss: 4.4584 0.2096 sec/batch
Nearest to been: abet, warfare, brought, spire, comers, analogs, tenure, mehmet,
Nearest to will: programmability, lingvo, interpreted, can, represented, created, intersection, preside,
Nearest to often: hamadan, toughened, cortina, be, stresses, sequencing, ermengarde, levite,
Nearest to such: downstairs, oesophagus, deepest, isostatic, continuity, inflections, management, evolution,
Nearest to time: retrieving, cartridges, intense, appletalk, lois, adjustment, blackberry, veselin,
Nearest to used: can, abstractions, packaging, substances, ovaries, retirees, suva, plosive,
Nearest to more: lives, orthoclase, bitkeeper, involve, up, white, fir, cardan,
Nearest to over: supercritical, revalued, chartered, year, reims, henceforth, ena, oblast,
Nearest to hold: killer, leaving, prefrontal, therapists, glitches, wives, haemorrhage, plotinus,
Nearest to channel: broadcasting, hamill, weizmann, minter, rackets, epistolary, barajas, pollock,
Nearest to prince: cyrillic, spratly, jacobs, cricketer, durrell, bartolomeo, turtles, streaming,
Nearest to square: roof, biograph, imd, gardens, geographical, xie, nguema, valentinius,
Nearest to instance: proust, videogames, perpetrated, harm, comprehensiveness, blantyre, interprets, toni,
Nearest to gold: chekhov, analgesic, snaps, older, dordrecht, lmann, labonte, subjects,
Nearest to mean: beauchamp, evaporator, implies, specifying, orthopedic, curta, afferent, buzzing,
Nearest to frac: prevails, guideline, roussillon, sempronius, dai, terms, wavelength, tennyson,
Epoch 2/10 Iteration: 6100 Avg. Training loss: 4.4834 0.2137 sec/batch
Epoch 2/10 Iteration: 6200 Avg. Training loss: 4.4588 0.2121 sec/batch
Epoch 2/10 Iteration: 6300 Avg. Training loss: 4.4970 0.2094 sec/batch
Epoch 2/10 Iteration: 6400 Avg. Training loss: 4.4133 0.2082 sec/batch
Epoch 2/10 Iteration: 6500 Avg. Training loss: 4.4237 0.2069 sec/batch
Epoch 2/10 Iteration: 6600 Avg. Training loss: 4.4720 0.2090 sec/batch
Epoch 2/10 Iteration: 6700 Avg. Training loss: 4.4288 0.2096 sec/batch
Epoch 2/10 Iteration: 6800 Avg. Training loss: 4.4116 0.2097 sec/batch
Epoch 2/10 Iteration: 6900 Avg. Training loss: 4.4517 0.2088 sec/batch
Epoch 2/10 Iteration: 7000 Avg. Training loss: 4.4025 0.2089 sec/batch
Nearest to been: abet, brought, warfare, spire, unpleasant, comers, jurisdictions, analogs,
Nearest to will: programmability, lingvo, interpreted, can, represented, variable, intersection, preside,
Nearest to often: cortina, toughened, ermengarde, hamadan, sequencing, levite, rude, stresses,
Nearest to such: oesophagus, downstairs, inflections, roddy, casinos, continuity, management, deepest,
Nearest to time: lois, cartridges, storming, retrieving, intense, qpl, headroom, veselin,
Nearest to used: can, abstractions, packaging, substances, ovaries, htp, retirees, plosive,
Nearest to more: lives, orthoclase, involve, bitkeeper, up, analysed, computes, because,
Nearest to over: supercritical, year, revalued, chartered, growth, reims, henceforth, leans,
Nearest to hold: leaving, reality, killer, prefrontal, therapists, contacted, abjads, haemorrhage,
Nearest to channel: broadcasting, minter, hamill, rackets, weizmann, spanking, lana, seaway,
Nearest to prince: cricketer, cyrillic, spratly, jacobs, durrell, bartolomeo, charles, boycotts,
Nearest to square: roof, biograph, xie, gardens, nguema, imd, geographical, express,
Nearest to instance: harm, interprets, blantyre, comprehensiveness, perpetrated, predatory, worsened, asher,
Nearest to gold: chekhov, snaps, analgesic, labonte, menace, electroshock, dordrecht, lmann,
Nearest to mean: beauchamp, implies, orthopedic, evaporator, afferent, inverses, curta, specifying,
Nearest to frac: prevails, roussillon, guideline, wavelength, pole, sempronius, satisfies, infinite,
Epoch 2/10 Iteration: 7100 Avg. Training loss: 4.4011 0.2112 sec/batch
Epoch 2/10 Iteration: 7200 Avg. Training loss: 4.4175 0.2089 sec/batch
Epoch 2/10 Iteration: 7300 Avg. Training loss: 4.3852 0.2112 sec/batch

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)