Deep Learning

Assignment 5

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


In [1]:
# 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


e:\python36\lib\site-packages\h5py\__init__.py:36: FutureWarning: Conversion of the second argument of issubdtype from `float` to `np.floating` is deprecated. In future, it will be treated as `np.float64 == np.dtype(float).type`.
  from ._conv import register_converters as _register_converters

Download the data from the source website if necessary.


In [2]:
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 [3]:
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 [4]:
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]

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


In [5]:
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[:8]])

for num_skips, skip_window in [(2, 1), (4, 2)]:
    data_index = 0
    batch, labels = generate_batch(batch_size=8, 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(8)])


data: ['anarchism', 'originated', 'as', 'a', 'term', 'of', 'abuse', 'first']

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

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

Train a skip-gram model.


In [6]:
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(), tf.device('/cpu:0'):

  # 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, keepdims=True))
  normalized_embeddings = embeddings / norm
  valid_embeddings = tf.nn.embedding_lookup(
    normalized_embeddings, valid_dataset)
  similarity = tf.matmul(valid_embeddings, tf.transpose(normalized_embeddings))


WARNING:tensorflow:From e:\python36\lib\site-packages\tensorflow\python\ops\nn_impl.py:1310: softmax_cross_entropy_with_logits (from tensorflow.python.ops.nn_ops) is deprecated and will be removed in a future version.
Instructions for updating:

Future major versions of TensorFlow will allow gradients to flow
into the labels input on backprop by default.

See tf.nn.softmax_cross_entropy_with_logits_v2.


In [7]:
num_steps = 100001

with tf.Session(graph=graph) as session:
  tf.global_variables_initializer().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()


Initialized
Average loss at step 0: 7.950670
Nearest to had: mellon, hinayana, manager, sbc, subfamily, sticking, bounces, consonant,
Nearest to which: benitez, buddhism, optimates, fabric, domestically, unsurprisingly, upside, conduct,
Nearest to used: beheaded, nigsberg, isolates, participants, appropriately, alert, soundtracks, lactation,
Nearest to in: rad, insuring, purposefully, prominently, conditions, rave, alastair, anybody,
Nearest to to: valhalla, actinidia, sparking, mentioning, skillful, solomon, honeycomb, planetarium,
Nearest to an: badly, throws, married, edie, beliefs, mari, experimented, greenwich,
Nearest to as: jack, duodenum, klaus, zquez, spell, brains, promote, rims,
Nearest to these: solipsism, rump, prussians, idolized, trevor, months, sainsbury, regulator,
Nearest to new: quasar, vestiges, gander, gregg, electorates, nouvelle, system, besht,
Nearest to four: jujutsu, sources, hardened, ebionites, schoenberg, beets, zariski, canceled,
Nearest to only: downward, mariam, priest, fill, midwife, exact, jr, acadia,
Nearest to five: musicianship, archetype, redistricting, crippled, malcolm, luckily, melee, astrophysicist,
Nearest to three: toro, bara, mackerel, hawai, milligan, determine, broadway, selector,
Nearest to b: billionaire, improperly, disbandment, thinkpad, shaggy, portfolio, activity, rideau,
Nearest to can: bewitched, isaiah, brasilia, aluminium, squarepants, folklore, purchases, saville,
Nearest to up: megabit, binet, complaints, subjectivity, bowmen, bosniaks, sarin, mangaverse,
Average loss at step 2000: 4.370172
Average loss at step 4000: 3.866268
Average loss at step 6000: 3.789163
Average loss at step 8000: 3.690444
Average loss at step 10000: 3.614099
Nearest to had: have, has, was, mellon, sbc, fibs, fanny, territory,
Nearest to which: that, also, this, it, what, benitez, who, mishap,
Nearest to used: khalid, ankles, appropriately, produced, kojiki, inaccuracy, extinguished, grimes,
Nearest to in: on, of, from, at, cytokinesis, eolian, with, judaean,
Nearest to to: can, eftpos, not, volunteer, lojban, sparking, actinidia, blown,
Nearest to an: the, throws, andhra, madras, populate, securing, unspeakable, cochrane,
Nearest to as: engels, vivaldi, emery, by, imply, adverb, telepathic, without,
Nearest to these: colophon, solipsism, sainsbury, many, its, reacts, qf, months,
Nearest to new: modern, fun, gregg, hp, besht, ctrl, quasar, backfield,
Nearest to four: six, seven, three, five, eight, two, nine, zero,
Nearest to only: mariam, priest, midwife, jr, downward, behaviorism, champ, duma,
Nearest to five: six, seven, eight, three, four, nine, two, zero,
Nearest to three: seven, eight, six, four, five, two, nine, zero,
Nearest to b: billionaire, d, ballparks, bernoulli, verdict, shaggy, disbandment, abstraction,
Nearest to can: may, will, could, bewitched, plagued, folklore, to, would,
Nearest to up: complaints, binet, bowmen, conceding, tramlink, sweetheart, either, duane,
Average loss at step 12000: 3.612087
Average loss at step 14000: 3.573888
Average loss at step 16000: 3.405214
Average loss at step 18000: 3.460062
Average loss at step 20000: 3.537940
Nearest to had: have, has, was, were, sault, mellon, ever, fanny,
Nearest to which: that, this, but, what, also, who, mishap, there,
Nearest to used: produced, written, appropriately, ankles, excommunicated, known, found, counterfeiting,
Nearest to in: at, on, from, during, around, under, for, with,
Nearest to to: would, can, will, eftpos, actinidia, not, could, may,
Nearest to an: the, cochrane, andhra, throws, greenwich, buoyant, collectives, populate,
Nearest to as: adverb, engels, intervenes, without, in, underlines, for, imply,
Nearest to these: many, some, colophon, other, all, which, solipsism, are,
Nearest to new: modern, micrometres, hp, rudimentary, cronenberg, fun, gregg, ncia,
Nearest to four: eight, six, three, seven, five, two, nine, zero,
Nearest to only: champ, exaggerate, priest, reznor, jr, tunnelling, fill, delaware,
Nearest to five: seven, four, six, three, eight, two, zero, nine,
Nearest to three: four, six, seven, five, two, eight, zero, nine,
Nearest to b: d, bernoulli, chasm, estrangement, ballparks, icon, cray, shaggy,
Nearest to can: may, will, would, could, should, might, must, to,
Nearest to up: complaints, conceding, sweetheart, binet, vegetation, bowmen, either, duane,
Average loss at step 22000: 3.501229
Average loss at step 24000: 3.489131
Average loss at step 26000: 3.483361
Average loss at step 28000: 3.479378
Average loss at step 30000: 3.505414
Nearest to had: have, has, was, were, having, ever, since, been,
Nearest to which: this, that, what, also, who, but, it, mishap,
Nearest to used: known, written, referred, produced, found, ankles, sucre, hexen,
Nearest to in: at, during, on, from, around, between, of, under,
Nearest to to: would, will, can, could, and, may, eftpos, dismay,
Nearest to an: throws, idiosyncrasies, andhra, pamela, buoyant, populate, suppose, cochrane,
Nearest to as: under, telepathic, emery, drawer, normal, coordinating, carriage, pyrrhus,
Nearest to these: some, many, such, are, all, other, several, their,
Nearest to new: relay, modern, ncia, micrometres, whistler, prophet, guernsey, backfield,
Nearest to four: seven, five, six, eight, three, nine, two, zero,
Nearest to only: exaggerate, reznor, tunnelling, ova, prenatal, serine, champ, decapitated,
Nearest to five: eight, four, six, seven, three, zero, nine, two,
Nearest to three: four, five, seven, eight, six, two, nine, zero,
Nearest to b: d, actor, luiz, bernoulli, cray, estrangement, flakes, ballparks,
Nearest to can: may, will, would, could, should, must, might, cannot,
Nearest to up: complaints, him, back, conceding, them, bowmen, sweetheart, binet,
Average loss at step 32000: 3.502854
Average loss at step 34000: 3.496013
Average loss at step 36000: 3.450800
Average loss at step 38000: 3.300322
Average loss at step 40000: 3.424708
Nearest to had: has, have, was, were, having, ever, since, sault,
Nearest to which: that, this, what, also, who, often, it, but,
Nearest to used: known, referred, found, written, produced, confined, considered, ankles,
Nearest to in: during, of, for, at, from, bd, efficient, above,
Nearest to to: could, will, would, actinidia, for, endosperm, can, shone,
Nearest to an: exceptions, populate, throws, pamela, madras, cochrane, denoted, buoyant,
Nearest to as: when, hesiod, statistician, antiderivative, overlapped, revealed, unskilled, tuamotu,
Nearest to these: many, some, several, such, are, they, were, various,
Nearest to new: modern, prophet, fun, rudimentary, ncia, whistler, gregg, lightness,
Nearest to four: six, seven, three, five, eight, two, nine, one,
Nearest to only: prenatal, reznor, tunnelling, disorderly, serine, champ, xxx, midwife,
Nearest to five: seven, six, four, three, eight, zero, two, nine,
Nearest to three: two, four, five, six, seven, eight, one, nine,
Nearest to b: d, actor, kabir, chaosium, UNK, bernoulli, f, playhouse,
Nearest to can: may, will, could, would, should, must, might, cannot,
Nearest to up: complaints, back, them, him, conceding, out, enjoyment, down,
Average loss at step 42000: 3.436035
Average loss at step 44000: 3.452395
Average loss at step 46000: 3.448286
Average loss at step 48000: 3.352533
Average loss at step 50000: 3.387031
Nearest to had: has, have, was, were, having, since, sault, would,
Nearest to which: this, that, also, what, often, who, anschluss, however,
Nearest to used: known, referred, written, considered, found, described, produced, confined,
Nearest to in: during, on, of, from, within, since, under, at,
Nearest to to: would, eftpos, could, can, recycle, actinidia, will, may,
Nearest to an: throws, fet, collaboration, exceptions, sideshow, musicals, stick, collectives,
Nearest to as: engels, when, terminally, telepathic, algirdas, manipulates, became, lyra,
Nearest to these: many, some, such, several, various, those, are, there,
Nearest to new: modern, islamic, prophet, meleon, incite, ncia, rudimentary, relay,
Nearest to four: six, seven, five, three, eight, nine, two, zero,
Nearest to only: xxx, first, delaware, reznor, either, escapes, oppositional, sizeable,
Nearest to five: four, six, seven, eight, three, zero, two, nine,
Nearest to three: six, four, seven, two, five, eight, nine, zero,
Nearest to b: d, eta, chaosium, r, cecil, f, c, caine,
Nearest to can: could, may, would, will, must, should, might, cannot,
Nearest to up: back, out, them, complaints, down, off, him, conceding,
Average loss at step 52000: 3.439952
Average loss at step 54000: 3.429624
Average loss at step 56000: 3.437563
Average loss at step 58000: 3.397456
Average loss at step 60000: 3.390205
Nearest to had: has, have, was, were, having, sault, been, could,
Nearest to which: that, this, what, who, it, also, however, mishap,
Nearest to used: known, written, referred, described, considered, produced, seen, designed,
Nearest to in: within, during, of, including, on, from, at, between,
Nearest to to: will, can, might, may, must, lojban, eftpos, would,
Nearest to an: collaboration, throws, fet, suppose, treats, sideshow, populate, unintended,
Nearest to as: lyra, copa, when, accommodate, carriage, liqueurs, extremely, terminally,
Nearest to these: many, several, some, those, various, such, there, are,
Nearest to new: modern, rudimentary, meleon, relay, incite, prophet, islamic, ctrl,
Nearest to four: six, five, eight, three, seven, nine, two, zero,
Nearest to only: first, usually, either, elohim, necessarily, conspiratorial, selected, escapes,
Nearest to five: six, four, three, eight, seven, zero, nine, two,
Nearest to three: five, four, six, two, eight, seven, nine, one,
Nearest to b: d, r, p, f, c, m, bernoulli, caine,
Nearest to can: may, could, would, will, must, should, might, cannot,
Nearest to up: out, off, back, him, down, complaints, them, casinos,
Average loss at step 62000: 3.241996
Average loss at step 64000: 3.257161
Average loss at step 66000: 3.401069
Average loss at step 68000: 3.397161
Average loss at step 70000: 3.358641
Nearest to had: have, has, was, were, having, been, cutler, since,
Nearest to which: that, this, also, what, these, but, brigadists, mishap,
Nearest to used: written, known, referred, designed, found, described, involved, required,
Nearest to in: within, during, on, from, through, since, ebook, for,
Nearest to to: can, would, for, might, eftpos, will, could, rewind,
Nearest to an: throws, fet, collaboration, ionosphere, the, sideshow, recumbent, tca,
Nearest to as: when, hua, carriage, is, peanuts, subjunctive, grizzly, wider,
Nearest to these: many, such, some, several, those, are, various, the,
Nearest to new: relay, rudimentary, incite, meleon, modern, pastrana, pneumonia, guerre,
Nearest to four: five, six, three, seven, eight, two, nine, zero,
Nearest to only: nothing, still, either, help, elohim, dacia, hit, first,
Nearest to five: four, six, eight, seven, three, zero, nine, two,
Nearest to three: four, six, two, five, seven, eight, nine, zero,
Nearest to b: d, f, r, p, n, cecil, z, y,
Nearest to can: could, may, would, will, should, must, cannot, might,
Nearest to up: off, out, back, them, complaints, down, him, casinos,
Average loss at step 72000: 3.374311
Average loss at step 74000: 3.349052
Average loss at step 76000: 3.313569
Average loss at step 78000: 3.348117
Average loss at step 80000: 3.378719
Nearest to had: has, have, were, was, having, been, became, began,
Nearest to which: this, that, also, usually, brigadists, what, these, often,
Nearest to used: known, written, referred, described, available, required, responsible, designed,
Nearest to in: within, during, on, until, at, ebook, around, between,
Nearest to to: must, guadeloupe, will, might, should, would, intensification, actinidia,
Nearest to an: fet, collaboration, ionosphere, cochrane, exceptions, buoyant, sideshow, gasolines,
Nearest to as: telepathic, groton, liqueurs, skyline, laden, like, monogram, lesser,
Nearest to these: several, those, many, such, various, some, both, are,
Nearest to new: modern, meleon, farc, relay, rudimentary, pastrana, ctrl, micrometres,
Nearest to four: five, six, seven, eight, three, nine, two, zero,
Nearest to only: either, exaggerate, elohim, xxx, thorndike, reznor, still, proven,
Nearest to five: six, four, seven, eight, three, nine, zero, two,
Nearest to three: six, five, four, seven, two, eight, nine, zero,
Nearest to b: d, r, p, kabir, playhouse, f, astrophysicist, eta,
Nearest to can: could, may, will, would, must, should, cannot, might,
Nearest to up: out, off, them, down, back, complaints, him, phnom,
Average loss at step 82000: 3.410866
Average loss at step 84000: 3.407166
Average loss at step 86000: 3.392641
Average loss at step 88000: 3.354710
Average loss at step 90000: 3.367091
Nearest to had: has, have, was, having, were, since, been, began,
Nearest to which: that, this, what, also, usually, these, hypercard, often,
Nearest to used: known, referred, written, considered, designed, required, described, available,
Nearest to in: within, during, under, ebook, with, tracer, of, including,
Nearest to to: sparking, would, actinidia, guadeloupe, micronesian, towards, could, lojban,
Nearest to an: fet, sideshow, another, collectives, cochrane, tca, gasolines, ionosphere,
Nearest to as: outta, befitting, tswana, carriage, pindar, thank, including, striking,
Nearest to these: many, several, some, those, are, such, instead, both,
Nearest to new: modern, pastrana, different, rudimentary, meleon, relay, pneumonia, micrometres,
Nearest to four: five, seven, three, six, eight, two, nine, one,
Nearest to only: xxx, either, exaggerate, no, even, meteorites, elohim, still,
Nearest to five: four, seven, eight, six, three, nine, zero, two,
Nearest to three: four, five, two, seven, eight, six, nine, zero,
Nearest to b: d, r, y, p, c, caine, unconsciously, eta,
Nearest to can: could, will, may, must, would, should, cannot, might,
Nearest to up: out, off, down, back, them, complaints, him, casinos,
Average loss at step 92000: 3.401739
Average loss at step 94000: 3.257126
Average loss at step 96000: 3.357606
Average loss at step 98000: 3.241895
Average loss at step 100000: 3.356264
Nearest to had: has, have, having, was, were, since, could, ever,
Nearest to which: that, this, what, usually, these, also, often, still,
Nearest to used: referred, written, known, considered, found, required, designed, responsible,
Nearest to in: within, during, on, until, from, across, at, throughout,
Nearest to to: will, could, would, must, guadeloupe, should, might, can,
Nearest to an: another, collaboration, cochrane, sideshow, fet, gasolines, tca, collectives,
Nearest to as: like, westphalian, algirdas, pindar, tswana, liqueurs, when, groton,
Nearest to these: several, many, some, those, were, all, which, various,
Nearest to new: modern, pastrana, different, sobieski, relay, micrometres, twiggy, meleon,
Nearest to four: six, seven, eight, five, three, two, nine, zero,
Nearest to only: elohim, still, either, whitaker, xxx, meteorites, butchers, even,
Nearest to five: six, seven, four, eight, zero, nine, three, two,
Nearest to three: four, two, six, five, eight, seven, nine, one,
Nearest to b: d, eta, mo, caine, politician, merle, bernoulli, substituents,
Nearest to can: could, may, will, would, must, should, cannot, might,
Nearest to up: out, off, back, them, down, him, complaints, phnom,

In [8]:
num_points = 400

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

In [9]:
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)


5_word2vec_prob1_skipgram.py results

Source 5_word2vec_prob1_skipgram.py

Sample Data

Data size 17005207
Most common words (+UNK) [['UNK', 418391], ('the', 1061396), ('of', 593677), ('and', 416629), ('one', 411764)]
Sample words ['anarchism', 'originated', 'as', 'a', 'term', 'of', 'abuse', 'first', 'used', 'against']
Sample data [5234, 3081, 12, 6, 195, 2, 3134, 46, 59, 156]
Sample dictionary keys {'UNK': 0, 'the': 1, 'of': 2, 'and': 3, 'one': 4, 'in': 5, 'a': 6, 'to': 7, 'zero': 8, 'nine': 9}
Sample reverse_dictionary {0: 'UNK', 1: 'the', 2: 'of', 3: 'and', 4: 'one', 5: 'in', 6: 'a', 7: 'to', 8: 'zero', 9: 'nine'}

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.