Deep Learning

Assignment 5

The goal of this assignment is to train a Word2Vec skip-gram model over Text8 data.


In [4]:
# These are all the modules we'll be using later. Make sure you can import them
# before proceeding further.
%matplotlib inline
from __future__ import print_function
import collections
import math
import numpy as np
import os
import random
import tensorflow as tf
import zipfile
from matplotlib import pylab
from six.moves import range
from six.moves.urllib.request import urlretrieve
from sklearn.manifold import TSNE

Download the data from the source website if necessary.


In [5]:
url = 'http://mattmahoney.net/dc/'

def maybe_download(filename, expected_bytes):
  """Download a file if not present, and make sure it's the right size."""
  if not os.path.exists(filename):
    filename, _ = urlretrieve(url + filename, filename)
  statinfo = os.stat(filename)
  if statinfo.st_size == expected_bytes:
    print('Found and verified %s' % filename)
  else:
    print(statinfo.st_size)
    raise Exception(
      'Failed to verify ' + filename + '. Can you get to it with a browser?')
  return filename

filename = maybe_download('text8.zip', 31344016)


Found and verified text8.zip

Read the data into a string.


In [6]:
def read_data(filename):
  """Extract the first file enclosed in a zip file as a list of words"""
  with zipfile.ZipFile(filename) as f:
    data = tf.compat.as_str(f.read(f.namelist()[0])).split()
  return data
  
words = read_data(filename)
print('Data size %d' % len(words))


Data size 17005207

Build the dictionary and replace rare words with UNK token.


In [7]:
vocabulary_size = 50000

def build_dataset(words):
  count = [['UNK', -1]]
  count.extend(collections.Counter(words).most_common(vocabulary_size - 1))
  dictionary = dict()
  for word, _ in count:
    dictionary[word] = len(dictionary)
  data = list()
  unk_count = 0
  for word in words:
    if word in dictionary:
      index = dictionary[word]
    else:
      index = 0  # dictionary['UNK']
      unk_count = unk_count + 1
    data.append(index)
  count[0][1] = unk_count
  reverse_dictionary = dict(zip(dictionary.values(), dictionary.keys())) 
  return data, count, dictionary, reverse_dictionary

data, count, dictionary, reverse_dictionary = build_dataset(words)
print('Most common words (+UNK)', count[:5])
print('Sample data', data[:10])
del words  # Hint to reduce memory.


Most common words (+UNK) [['UNK', 418391], ('the', 1061396), ('of', 593677), ('and', 416629), ('one', 411764)]
Sample data [5234, 3081, 12, 6, 195, 2, 3134, 46, 59, 156]

Let's display the internal variables to better understand their structure:


In [16]:
print(data[:10])
print(count[:10])


[5234, 3081, 12, 6, 195, 2, 3134, 46, 59, 156]
[['UNK', 418391], ('the', 1061396), ('of', 593677), ('and', 416629), ('one', 411764), ('in', 372201), ('a', 325873), ('to', 316376), ('zero', 264975), ('nine', 250430)]

Function to generate a training batch for the skip-gram model.


In [17]:
data_index = 0

def generate_batch(batch_size, num_skips, skip_window):
  global data_index
  assert batch_size % num_skips == 0
  assert num_skips <= 2 * skip_window
  batch = np.ndarray(shape=(batch_size), dtype=np.int32)
  labels = np.ndarray(shape=(batch_size, 1), dtype=np.int32)
  span = 2 * skip_window + 1 # [ skip_window target skip_window ]
  buffer = collections.deque(maxlen=span)
  for _ in range(span):
    buffer.append(data[data_index])
    data_index = (data_index + 1) % len(data)
  for i in range(batch_size // num_skips):
    target = skip_window  # target label at the center of the buffer
    targets_to_avoid = [ skip_window ]
    for j in range(num_skips):
      while target in targets_to_avoid:
        target = random.randint(0, span - 1)
      targets_to_avoid.append(target)
      batch[i * num_skips + j] = buffer[skip_window]
      labels[i * num_skips + j, 0] = buffer[target]
    buffer.append(data[data_index])
    data_index = (data_index + 1) % len(data)
  return batch, labels

print('data:', [reverse_dictionary[di] for di in data[:32]])

for num_skips, skip_window in [(2, 1), (4, 2)]:
    data_index = 0
    batch, labels = generate_batch(batch_size=16, num_skips=num_skips, skip_window=skip_window)
    print('\nwith num_skips = %d and skip_window = %d:' % (num_skips, skip_window))
    print('    batch:', [reverse_dictionary[bi] for bi in batch])
    print('    labels:', [reverse_dictionary[li] for li in labels.reshape(16)])
    
for num_skips, skip_window in [(2, 1), (4, 2)]:
    data_index = 1
    batch, labels = generate_batch(batch_size=16, num_skips=num_skips, skip_window=skip_window)
    print('\nwith num_skips = %d and skip_window = %d:' % (num_skips, skip_window))
    print('    batch:', [reverse_dictionary[bi] for bi in batch])
    print('    labels:', [reverse_dictionary[li] for li in labels.reshape(16)])


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

with num_skips = 2 and skip_window = 1:
    batch: ['originated', 'originated', 'as', 'as', 'a', 'a', 'term', 'term', 'of', 'of', 'abuse', 'abuse', 'first', 'first', 'used', 'used']
    labels: ['anarchism', 'as', 'a', 'originated', 'as', 'term', 'of', 'a', 'term', 'abuse', 'first', 'of', 'used', 'abuse', 'first', 'against']

with num_skips = 4 and skip_window = 2:
    batch: ['as', 'as', 'as', 'as', 'a', 'a', 'a', 'a', 'term', 'term', 'term', 'term', 'of', 'of', 'of', 'of']
    labels: ['originated', 'anarchism', 'a', 'term', 'as', 'of', 'originated', 'term', 'abuse', 'of', 'a', 'as', 'a', 'first', 'term', 'abuse']

with num_skips = 2 and skip_window = 1:
    batch: ['as', 'as', 'a', 'a', 'term', 'term', 'of', 'of', 'abuse', 'abuse', 'first', 'first', 'used', 'used', 'against', 'against']
    labels: ['a', 'originated', 'as', 'term', 'a', 'of', 'term', 'abuse', 'first', 'of', 'used', 'abuse', 'against', 'first', 'used', 'early']

with num_skips = 4 and skip_window = 2:
    batch: ['a', 'a', 'a', 'a', 'term', 'term', 'term', 'term', 'of', 'of', 'of', 'of', 'abuse', 'abuse', 'abuse', 'abuse']
    labels: ['term', 'as', 'originated', 'of', 'a', 'as', 'abuse', 'of', 'abuse', 'a', 'term', 'first', 'first', 'term', 'of', 'used']

Note: the labels is a sliding random value of the word surrounding the words of the batch.

It is not obvious with the output above, but all the data are based on index, and not the word directly.


In [11]:
print(batch)
print(labels)


[   6    6    6    6  195  195  195  195    2    2    2    2 3134 3134 3134
 3134]
[[   2]
 [  12]
 [3081]
 [ 195]
 [  12]
 [   2]
 [3134]
 [   6]
 [ 195]
 [3134]
 [  46]
 [   6]
 [   2]
 [  59]
 [ 195]
 [  46]]

Train a skip-gram model.


In [19]:
batch_size = 128
embedding_size = 128 # Dimension of the embedding vector.
skip_window = 1 # How many words to consider left and right.
num_skips = 2 # How many times to reuse an input to generate a label.
# We pick a random validation set to sample nearest neighbors. here we limit the
# validation samples to the words that have a low numeric ID, which by
# construction are also the most frequent. 
valid_size = 16 # Random set of words to evaluate similarity on.
valid_window = 100 # Only pick dev samples in the head of the distribution.
valid_examples = np.array(random.sample(range(valid_window), valid_size))
num_sampled = 64 # Number of negative examples to sample.

graph = tf.Graph()

with graph.as_default():

  # Input data.
  train_dataset = tf.placeholder(tf.int32, shape=[batch_size])
  train_labels = tf.placeholder(tf.int32, shape=[batch_size, 1])
  valid_dataset = tf.constant(valid_examples, dtype=tf.int32)
  
  # Variables.
  embeddings = tf.Variable(
    tf.random_uniform([vocabulary_size, embedding_size], -1.0, 1.0))
  softmax_weights = tf.Variable(
    tf.truncated_normal([vocabulary_size, embedding_size],
                         stddev=1.0 / math.sqrt(embedding_size)))
  softmax_biases = tf.Variable(tf.zeros([vocabulary_size]))
  
  # Model.
  # Look up embeddings for inputs.
  embed = tf.nn.embedding_lookup(embeddings, train_dataset)
  # Compute the softmax loss, using a sample of the negative labels each time.
  loss = tf.reduce_mean(
    tf.nn.sampled_softmax_loss(weights=softmax_weights, biases=softmax_biases, inputs=embed,
                               labels=train_labels, num_sampled=num_sampled, num_classes=vocabulary_size))

  # Optimizer.
  # Note: The optimizer will optimize the softmax_weights AND the embeddings.
  # This is because the embeddings are defined as a variable quantity and the
  # optimizer's `minimize` method will by default modify all variable quantities 
  # that contribute to the tensor it is passed.
  # See docs on `tf.train.Optimizer.minimize()` for more details.
  optimizer = tf.train.AdagradOptimizer(1.0).minimize(loss)
  
  # Compute the similarity between minibatch examples and all embeddings.
  # We use the cosine distance:
  norm = tf.sqrt(tf.reduce_sum(tf.square(embeddings), 1, keep_dims=True))
  normalized_embeddings = embeddings / norm
  valid_embeddings = tf.nn.embedding_lookup(
    normalized_embeddings, valid_dataset)
  similarity = tf.matmul(valid_embeddings, tf.transpose(normalized_embeddings))

In [20]:
num_steps = 100001

with tf.Session(graph=graph) as session:
  tf.initialize_all_variables().run()
  print('Initialized')
  average_loss = 0
  for step in range(num_steps):
    batch_data, batch_labels = generate_batch(
      batch_size, num_skips, skip_window)
    feed_dict = {train_dataset : batch_data, train_labels : batch_labels}
    _, l = session.run([optimizer, loss], feed_dict=feed_dict)
    average_loss += l
    if step % 2000 == 0:
      if step > 0:
        average_loss = average_loss / 2000
      # The average loss is an estimate of the loss over the last 2000 batches.
      print('Average loss at step %d: %f' % (step, average_loss))
      average_loss = 0
    # note that this is expensive (~20% slowdown if computed every 500 steps)
    if step % 10000 == 0:
      sim = similarity.eval()
      for i in range(valid_size):
        valid_word = reverse_dictionary[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 = reverse_dictionary[nearest[k]]
          log = '%s %s,' % (log, close_word)
        print(log)
  final_embeddings = normalized_embeddings.eval()


WARNING:tensorflow:From C:\Users\rjenc\Anaconda3\envs\gpu_fun\lib\site-packages\tensorflow\python\util\tf_should_use.py:170: initialize_all_variables (from tensorflow.python.ops.variables) is deprecated and will be removed after 2017-03-02.
Instructions for updating:
Use `tf.global_variables_initializer` instead.
Initialized
Average loss at step 0: 8.132468
Nearest to but: modus, honesty, pmod, dissatisfied, gpcrs, measured, proleptic, mlp,
Nearest to on: helix, accords, rhetoric, jimmie, spacing, cup, primaries, reworked,
Nearest to b: redskins, safari, stained, mcgovern, personalized, fj, valign, irregulars,
Nearest to who: tanenbaum, theater, proteases, sampling, deformity, tuttle, carrying, hooker,
Nearest to up: hulme, ungodly, sportswriter, introduced, westerly, alto, accumulating, gilliam,
Nearest to years: unbreakable, lovejoy, overflow, car, worthless, latinus, tabular, organum,
Nearest to known: enhancing, thereabouts, ambiguities, rangoon, suffice, dostoevsky, lawful, esk,
Nearest to zero: mcp, aphids, alans, mommu, shab, belief, conclusion, isu,
Nearest to a: attendant, veteran, anglicans, either, inhaled, communicated, vous, malaria,
Nearest to american: spilled, seedless, adversary, rockville, sveriges, hinds, believer, gn,
Nearest to nine: karnataka, bert, histology, funded, federer, woodpeckers, swords, explosive,
Nearest to at: leech, woodlands, sought, pubescent, frivolous, unwillingness, fiqh, insufficiency,
Nearest to an: abercorn, retarded, bit, cards, enumerable, wheelock, caveats, townes,
Nearest to time: negative, xiith, conflicting, alternatives, books, mescaline, artistry, mitre,
Nearest to often: generalizations, albret, prepares, packs, gothenburg, haldane, poisoning, rogue,
Nearest to first: hippie, maneuvering, buyers, motile, quirky, bruce, types, adolescents,
Average loss at step 2000: 4.372934
Average loss at step 4000: 3.864436
Average loss at step 6000: 3.787821
Average loss at step 8000: 3.689752
Average loss at step 10000: 3.620859
Nearest to but: and, xii, stuka, which, whores, is, druidry, however,
Nearest to on: in, at, commoner, integral, bsod, of, chemotherapeutic, jimmie,
Nearest to b: safari, southey, relegated, redskins, denied, georgy, mcgovern, recede,
Nearest to who: he, and, proteases, also, quadrangle, often, they, theater,
Nearest to up: treehouse, severe, discordian, contractor, introduced, pronunciation, chaffee, lockport,
Nearest to years: remind, shortly, rumi, lovejoy, reasons, overflow, unbreakable, eiffel,
Nearest to known: well, comerica, used, batasuna, cataracts, lymphoma, junior, mallard,
Nearest to zero: nine, eight, five, seven, six, four, three, two,
Nearest to a: the, restless, its, this, vous, foundered, rd, embellishment,
Nearest to american: seedless, believer, spilled, hinds, adversary, sveriges, jewish, megabytes,
Nearest to nine: eight, six, five, seven, zero, four, three, two,
Nearest to at: on, in, carniola, bmx, stanbul, intercept, dignity, dc,
Nearest to an: bit, shale, the, topographical, chromosomal, townes, genomic, massively,
Nearest to time: negative, qatar, books, pontiac, artistry, alternatives, xiith, common,
Nearest to often: davies, who, widely, gothenburg, albret, dso, conditioning, that,
Nearest to first: cinder, quirky, principalities, deficiencies, montenegro, bruce, pleiades, wives,
Average loss at step 12000: 3.606384
Average loss at step 14000: 3.575816
Average loss at step 16000: 3.412007
Average loss at step 18000: 3.462041
Average loss at step 20000: 3.538648
Nearest to but: which, however, and, that, submarine, was, is, or,
Nearest to on: in, at, taboos, jimmie, upon, dbu, chemotherapeutic, under,
Nearest to b: d, topographical, bournemouth, french, preconditions, ballots, demo, visuals,
Nearest to who: he, which, they, often, she, also, and, minimizing,
Nearest to up: down, contractor, reborn, discordian, guatemalan, severe, pronunciation, treehouse,
Nearest to years: remind, carrie, shortly, rumi, fathoms, lovejoy, reasons, daffodils,
Nearest to known: used, such, comerica, well, cataracts, transports, batasuna, mentioned,
Nearest to zero: five, six, seven, three, two, four, eight, nine,
Nearest to a: the, attendant, this, another, regulates, any, restless, vous,
Nearest to american: british, australian, goering, english, seedless, nrc, tradeoffs, hinds,
Nearest to nine: eight, six, seven, four, five, three, zero, two,
Nearest to at: in, on, from, is, when, carniola, around, by,
Nearest to an: bit, the, shale, topographical, airmen, bluish, turkish, chromosomal,
Nearest to time: negative, year, browsers, adhere, way, faulkner, bedrock, qatar,
Nearest to often: sometimes, who, widely, bouchard, davies, also, detonate, there,
Nearest to first: quirky, montenegro, pasting, reflecting, pleiades, next, loves, wives,
Average loss at step 22000: 3.502513
Average loss at step 24000: 3.492212
Average loss at step 26000: 3.481406
Average loss at step 28000: 3.479030
Average loss at step 30000: 3.502576
Nearest to but: however, although, which, and, that, when, did, or,
Nearest to on: in, upon, at, maquis, within, through, under, bsod,
Nearest to b: d, ulam, ballots, freethought, elsevier, lexicology, geralt, recede,
Nearest to who: he, they, which, she, often, already, and, tzow,
Nearest to up: down, him, them, accentuated, dagon, guatemalan, gilliam, vere,
Nearest to years: days, remind, carrie, shortly, fathoms, rumi, daffodils, fusion,
Nearest to known: used, such, well, comerica, regarded, cataracts, escapement, served,
Nearest to zero: five, eight, seven, four, six, three, nine, two,
Nearest to a: any, another, anglicans, every, the, kx, tijuana, vous,
Nearest to american: british, english, australian, french, german, and, indian, russian,
Nearest to nine: eight, seven, six, five, four, three, zero, two,
Nearest to at: in, when, on, carniola, during, under, around, entire,
Nearest to an: topographical, townes, shale, purportedly, bit, chromosomal, turkish, rietveld,
Nearest to time: year, way, astra, zeta, negative, adhere, bedrock, organisation,
Nearest to often: sometimes, widely, generally, usually, who, actually, there, still,
Nearest to first: second, last, pasting, next, contested, same, federal, wives,
Average loss at step 32000: 3.504553
Average loss at step 34000: 3.495423
Average loss at step 36000: 3.454296
Average loss at step 38000: 3.301446
Average loss at step 40000: 3.428337
Nearest to but: however, and, although, which, though, or, while, ratzinger,
Nearest to on: upon, at, in, commoner, stupidity, madge, niven, within,
Nearest to b: d, c, UNK, kaifu, f, buson, sequencing, malabar,
Nearest to who: which, often, he, also, tzow, she, they, that,
Nearest to up: down, him, them, out, mctell, hooked, gustavus, vere,
Nearest to years: days, remind, decades, carrie, times, shortly, reasons, fathoms,
Nearest to known: used, such, regarded, comerica, well, escapement, served, considered,
Nearest to zero: seven, five, nine, eight, six, four, three, two,
Nearest to a: the, any, restless, another, or, attendant, this, vous,
Nearest to american: english, british, australian, classicist, russian, cooking, including, german,
Nearest to nine: eight, seven, six, five, zero, four, three, two,
Nearest to at: on, in, when, during, mcclory, hmmwv, carniola, for,
Nearest to an: shale, caveats, topographical, nter, chromosomal, enveloping, degli, townes,
Nearest to time: way, year, astra, browsers, eldest, skins, virtually, introductory,
Nearest to often: sometimes, usually, widely, generally, also, who, which, there,
Nearest to first: second, last, next, coalesced, pasting, fourth, reflecting, wives,
Average loss at step 42000: 3.437009
Average loss at step 44000: 3.449925
Average loss at step 46000: 3.452897
Average loss at step 48000: 3.351451
Average loss at step 50000: 3.386526
Nearest to but: however, although, though, when, and, ratzinger, which, while,
Nearest to on: upon, in, stupidity, through, madge, condiments, famagusta, at,
Nearest to b: d, f, c, sequencing, abuser, kaifu, lexicology, cactus,
Nearest to who: he, which, often, they, she, there, tzow, also,
Nearest to up: down, them, out, him, off, hooked, gustavus, mctell,
Nearest to years: days, decades, remind, shortly, carrie, lovejoy, months, times,
Nearest to known: used, regarded, such, defined, comerica, viennese, served, considered,
Nearest to zero: seven, five, eight, six, four, three, nine, two,
Nearest to a: another, the, any, vous, pfp, paltrow, restless, embellishment,
Nearest to american: australian, british, english, castlevania, russian, codon, german, cooking,
Nearest to nine: eight, seven, six, four, three, five, zero, two,
Nearest to at: during, from, in, rush, on, around, bolder, prenatal,
Nearest to an: chromosomal, purportedly, townes, topographical, caveats, the, enveloping, degli,
Nearest to time: way, year, virtually, astra, extent, skins, eldest, assumptions,
Nearest to often: sometimes, usually, generally, widely, still, also, actually, commonly,
Nearest to first: second, next, last, coalesced, nextstep, third, wives, reflecting,
Average loss at step 52000: 3.444302
Average loss at step 54000: 3.427107
Average loss at step 56000: 3.440113
Average loss at step 58000: 3.392397
Average loss at step 60000: 3.391310
Nearest to but: however, although, and, though, see, when, ratzinger, taxing,
Nearest to on: upon, through, in, within, regarding, at, under, chemotherapeutic,
Nearest to b: d, c, f, r, abuser, buson, m, p,
Nearest to who: he, which, subsequently, often, they, already, tzow, she,
Nearest to up: down, out, them, off, him, back, sefer, hooked,
Nearest to years: days, decades, times, shortly, remind, centuries, months, reasons,
Nearest to known: used, regarded, such, defined, well, viennese, comerica, considered,
Nearest to zero: five, eight, six, four, seven, nine, three, two,
Nearest to a: another, the, any, every, epimorphism, vous, this, no,
Nearest to american: british, australian, english, cooking, castlevania, russian, codon, european,
Nearest to nine: eight, six, four, five, seven, three, zero, two,
Nearest to at: in, during, on, around, entire, corran, barrows, horch,
Nearest to an: topographical, shale, purportedly, degli, townes, caveats, massively, enveloping,
Nearest to time: way, year, period, eridu, browsers, virtually, extent, discounts,
Nearest to often: sometimes, usually, generally, widely, commonly, now, also, typically,
Nearest to first: last, second, next, third, originally, nextstep, only, same,
Average loss at step 62000: 3.235406
Average loss at step 64000: 3.252940
Average loss at step 66000: 3.405504
Average loss at step 68000: 3.395798
Average loss at step 70000: 3.359778
Nearest to but: however, although, though, ratzinger, while, and, that, which,
Nearest to on: upon, through, in, at, stupidity, within, regarding, molybdenum,
Nearest to b: d, f, r, buson, isc, abuser, h, recede,
Nearest to who: he, often, which, they, tzow, denise, she, subsequently,
Nearest to up: down, out, off, them, him, back, gustavus, neuroscientists,
Nearest to years: days, decades, months, centuries, times, weeks, remind, hours,
Nearest to known: used, regarded, such, defined, seen, considered, comerica, viennese,
Nearest to zero: five, eight, six, four, seven, nine, three, two,
Nearest to a: the, another, this, vous, any, penderecki, discussions, every,
Nearest to american: british, australian, english, ump, cooking, castlevania, codon, german,
Nearest to nine: eight, six, seven, five, four, three, zero, two,
Nearest to at: during, on, in, around, after, bmx, rush, onto,
Nearest to an: topographical, purportedly, the, rietveld, fasciculata, chromosomal, townes, corroborated,
Nearest to time: year, virtually, way, issue, season, extent, eridu, place,
Nearest to often: sometimes, usually, generally, commonly, widely, now, still, also,
Nearest to first: second, last, next, third, same, contested, coalesced, originally,
Average loss at step 72000: 3.375537
Average loss at step 74000: 3.347756
Average loss at step 76000: 3.317222
Average loss at step 78000: 3.348459
Average loss at step 80000: 3.373289
Nearest to but: however, although, though, while, and, ratzinger, which, or,
Nearest to on: upon, in, through, at, stupidity, under, stunning, recognise,
Nearest to b: d, f, c, r, abuser, isc, cactus, recede,
Nearest to who: often, he, subsequently, which, they, tzow, denise, never,
Nearest to up: down, out, off, them, him, back, gustavus, ramifications,
Nearest to years: days, decades, months, times, centuries, weeks, hours, year,
Nearest to known: used, regarded, defined, seen, such, acyclic, described, considered,
Nearest to zero: seven, five, six, eight, four, nine, three, two,
Nearest to a: another, the, tijuana, oaxaca, reportage, vous, biosphere, paltrow,
Nearest to american: british, australian, canadian, english, german, ump, cooking, russian,
Nearest to nine: eight, seven, six, five, four, three, zero, two,
Nearest to at: in, during, around, on, after, before, near, buccaneer,
Nearest to an: topographical, townes, rietveld, purportedly, chromosomal, magnetopause, settling, prevalent,
Nearest to time: year, way, extent, day, season, burma, assumptions, success,
Nearest to often: sometimes, usually, generally, commonly, widely, still, frequently, now,
Nearest to first: second, last, next, third, same, coalesced, wives, fourth,
Average loss at step 82000: 3.410494
Average loss at step 84000: 3.409711
Average loss at step 86000: 3.390185
Average loss at step 88000: 3.358791
Average loss at step 90000: 3.364637
Nearest to but: however, although, and, though, while, they, taxing, he,
Nearest to on: upon, through, at, under, in, stupidity, regarding, within,
Nearest to b: d, r, f, c, isc, malabar, hilaire, l,
Nearest to who: he, often, already, tzow, subsequently, also, which, they,
Nearest to up: down, off, out, them, back, him, gustavus, sefer,
Nearest to years: days, decades, months, centuries, year, weeks, hours, times,
Nearest to known: used, regarded, such, defined, seen, described, acyclic, cgpm,
Nearest to zero: seven, five, eight, six, four, nine, three, two,
Nearest to a: another, every, vous, any, the, commandos, reportage, valued,
Nearest to american: british, australian, english, french, canadian, german, russian, actors,
Nearest to nine: eight, seven, six, five, four, three, zero, two,
Nearest to at: during, near, on, around, in, fath, under, after,
Nearest to an: topographical, rietveld, caveats, chromosomal, townes, the, settling, airmen,
Nearest to time: year, success, season, burma, feared, astra, assumptions, night,
Nearest to often: sometimes, usually, generally, commonly, frequently, still, now, widely,
Nearest to first: last, second, next, previous, third, millimetres, colonial, originally,
Average loss at step 92000: 3.400345
Average loss at step 94000: 3.252060
Average loss at step 96000: 3.357813
Average loss at step 98000: 3.242191
Average loss at step 100000: 3.357622
Nearest to but: however, although, though, and, while, when, ratzinger, where,
Nearest to on: upon, through, within, in, at, under, into, stupidity,
Nearest to b: d, hilaire, recede, riemannian, pharaohs, abuser, retroviral, bournemouth,
Nearest to who: he, often, which, already, never, subsequently, also, microwaves,
Nearest to up: off, down, out, them, him, back, me, together,
Nearest to years: days, decades, months, centuries, year, weeks, times, hours,
Nearest to known: used, such, regarded, defined, described, seen, acyclic, available,
Nearest to zero: five, eight, four, seven, nine, six, three, two,
Nearest to a: another, the, any, vous, paltrow, discussions, coms, every,
Nearest to american: british, australian, canadian, french, english, italian, codon, german,
Nearest to nine: eight, seven, six, four, five, zero, three, two,
Nearest to at: during, barrows, on, after, tasked, around, buccaneer, carniola,
Nearest to an: caveats, topographical, rietveld, airmen, another, townes, nter, shale,
Nearest to time: year, way, event, feared, season, skins, success, assumptions,
Nearest to often: sometimes, usually, generally, commonly, typically, frequently, now, widely,
Nearest to first: second, last, next, fourth, third, previous, contested, same,

This is what an embedding looks like:


In [21]:
print(final_embeddings[0])


[  1.09369189e-01  -7.36378133e-02  -2.46062130e-01  -3.28664444e-02
   6.18233569e-02  -7.53385797e-02   3.19211558e-02   3.16312090e-02
   3.07562738e-03  -8.82591233e-02  -5.73923215e-02   9.65127870e-02
  -1.65879205e-01  -4.37431596e-02  -6.96987137e-02   2.52826605e-02
  -4.44233492e-02   1.32144004e-01  -2.39200089e-02   9.89301503e-03
   1.23112455e-01  -1.05729857e-02  -3.92384790e-02  -1.00651747e-02
  -6.49655908e-02  -3.42456214e-02  -1.25654235e-01   4.65727178e-03
  -3.27397138e-02  -3.54577154e-02   2.71719098e-02  -8.59990269e-02
   9.75978673e-02   6.54290430e-03  -7.91275036e-03   8.09110552e-02
   1.34141222e-01   1.20134436e-01   1.97317712e-02   1.58120282e-02
   8.73187780e-02   3.16656455e-02  -7.67222419e-02   1.46617964e-01
   4.02647629e-02  -2.20604390e-01   3.94025594e-02   5.61992303e-02
  -1.20315447e-01   2.12002486e-01   1.47194922e-01   6.79306313e-02
  -7.03351349e-02  -6.61698580e-02   1.42909680e-02   4.09306958e-02
  -5.11064418e-02  -3.15857194e-02  -2.01271340e-01   5.71369380e-02
  -1.44919446e-02   8.00840929e-03   6.86414586e-03   4.82652225e-02
  -2.80749630e-02  -8.83530974e-02   7.20187649e-02  -5.46098389e-02
   2.30299141e-02  -1.41317964e-01  -1.00636952e-01  -4.48009297e-02
  -6.46330193e-02   1.17436849e-01   1.48724252e-02   2.16636294e-03
   9.24799070e-02   8.38565305e-02  -1.59048112e-04   6.17773389e-04
   6.99966699e-02   3.90099660e-02  -2.69031357e-02  -7.10396469e-03
   1.13989070e-01   1.09556057e-01  -7.47421244e-03   1.23379610e-01
  -3.48183364e-02   7.75517942e-03   3.82899754e-02   7.58093372e-02
   1.61338031e-01  -1.60677344e-01  -2.09988281e-02   5.55569641e-02
   1.27678201e-01  -9.64843184e-02  -6.54294342e-02   1.16076469e-01
  -2.01007023e-01   3.57606336e-02  -1.45186216e-01   2.02828497e-02
  -5.86495688e-03   1.97546229e-01   1.04381971e-01  -8.14666972e-03
  -8.67910907e-02  -2.53632739e-02   1.11815572e-01   1.81348585e-02
   3.06969453e-02  -7.20592439e-02   1.21640302e-02  -9.68695283e-02
   8.07318985e-02  -1.27331465e-02  -1.17523864e-01   1.01669833e-01
  -5.30792959e-02  -2.15053577e-02  -8.56435001e-02  -1.13091819e-01
   1.14980295e-01   1.78032428e-01   2.19567679e-02   1.04342267e-01]

All the values are abstract, there is practical meaning of the them. Moreover, the final embeddings are normalized as you can see here:


In [22]:
print(np.sum(np.square(final_embeddings[0])))


1.0

In [23]:
num_points = 400

tsne = TSNE(perplexity=30, n_components=2, init='pca', n_iter=5000)
two_d_embeddings = tsne.fit_transform(final_embeddings[1:num_points+1, :])

In [24]:
def plot(embeddings, labels):
  assert embeddings.shape[0] >= len(labels), 'More labels than embeddings'
  pylab.figure(figsize=(15,15))  # in inches
  for i, label in enumerate(labels):
    x, y = embeddings[i,:]
    pylab.scatter(x, y)
    pylab.annotate(label, xy=(x, y), xytext=(5, 2), textcoords='offset points',
                   ha='right', va='bottom')
  pylab.show()

words = [reverse_dictionary[i] for i in range(1, num_points+1)]
plot(two_d_embeddings, words)



Problem

An alternative to skip-gram is another Word2Vec model called CBOW (Continuous Bag of Words). In the CBOW model, instead of predicting a context word from a word vector, you predict a word from the sum of all the word vectors in its context. Implement and evaluate a CBOW model trained on the text8 dataset.