Deep Learning - TSNE



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


/Users/user/anaconda/envs/tensorflow/lib/python2.7/site-packages/matplotlib/font_manager.py:273: UserWarning: Matplotlib is building the font cache using fc-list. This may take a moment.
  warnings.warn('Matplotlib is building the font cache using fc-list. This may take a moment.')

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

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

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 [5239, 3084, 12, 6, 195, 2, 3137, 46, 59, 156]

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', 'originated', 'a', 'term', 'as', 'of', 'a']

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

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(softmax_weights, softmax_biases, embed,
                               train_labels, num_sampled, 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 [11]:
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()


Initialized
Average loss at step 0: 7.182359
Nearest to that: zilog, dominating, breakdown, milken, meer, imposing, maoist, yorker,
Nearest to world: niklaus, employed, sherbrooke, wipes, thermoelectric, dory, ay, original,
Nearest to while: slot, critic, fracturing, erdrich, rapidity, riddles, scorer, exponential,
Nearest to i: monarchist, smuts, portable, polidori, aloes, pledged, belisarius, electra,
Nearest to up: externalization, chs, diabetes, slur, yorkist, anytime, cyanide, lehigh,
Nearest to be: fractured, carne, alternatively, flexible, cretan, integrin, enabling, coeur,
Nearest to known: bryant, scam, plethora, falling, vindicated, critic, produces, coat,
Nearest to had: spur, interpolation, hatching, fibre, chosenness, suspension, leucippus, accommodation,
Nearest to as: swimmers, intercourse, cage, procedures, hamad, goggles, alleys, serie,
Nearest to five: pepe, sram, septic, walther, bucket, amphitheatre, flint, clarinetists,
Nearest to first: nara, chadian, foreshadowed, premium, ced, convoy, meow, lancers,
Nearest to of: rpg, transitivity, equipping, homozygous, fulfilment, demonstrating, secures, cryptozoology,
Nearest to by: paolo, jeff, unsurpassed, advertise, fertilisation, consolidation, livestock, grub,
Nearest to at: hurry, gadget, ate, happenings, unintelligible, competitiveness, plugins, submits,
Nearest to its: swinburne, screenshots, riverview, moses, ramzi, pathfinder, shelton, pseudopods,
Nearest to however: missionary, psychosocial, logo, pollute, juliet, hyenas, ach, norms,
Average loss at step 2000: 4.349140
Average loss at step 4000: 3.866727
Average loss at step 6000: 3.789125
Average loss at step 8000: 3.682475
Average loss at step 10000: 3.610805
Nearest to that: what, which, catenary, initially, it, spacey, launched, renegades,
Nearest to world: niklaus, original, sherbrooke, employed, lebrun, lothair, confrontational, during,
Nearest to while: slot, through, cupid, obituary, riddles, taking, exponential, critic,
Nearest to i: they, intuitionism, aloes, battlecruiser, ahmet, essence, wren, electra,
Nearest to up: externalization, diabetes, slur, reunified, fiennes, chs, bolton, yorkist,
Nearest to be: have, was, is, by, become, enabling, directive, stillborn,
Nearest to known: scam, vindicated, bryant, banchan, exist, nchez, smoky, such,
Nearest to had: has, have, was, were, hatching, became, dancing, autistic,
Nearest to as: serie, aiming, ucr, inc, by, cooking, ric, algemeen,
Nearest to five: six, nine, seven, eight, three, four, zero, two,
Nearest to first: nara, gassing, same, second, ced, last, daleks, microorganism,
Nearest to of: in, second, equipping, secures, sabina, for, walkie, lol,
Nearest to by: was, on, be, with, at, as, lemons, boron,
Nearest to at: nola, by, in, during, of, eat, voters, gadget,
Nearest to its: the, his, their, ramzi, allotment, pathfinder, swinburne, candidacy,
Nearest to however: logo, pollute, referees, psychosocial, ach, whose, homages, riordan,
Average loss at step 12000: 3.603191
Average loss at step 14000: 3.568690
Average loss at step 16000: 3.410434
Average loss at step 18000: 3.455742
Average loss at step 20000: 3.537034
Nearest to that: which, but, what, catenary, when, mulligan, accusation, launched,
Nearest to world: lebrun, original, lothair, sherbrooke, niklaus, ibsen, laszlo, regimens,
Nearest to while: slot, through, critic, reproduce, obituary, cupid, rounds, riddles,
Nearest to i: hypothermia, unicellular, teimanim, ii, monolith, repent, battlecruiser, mojito,
Nearest to up: him, slur, externalization, reunified, diabetes, fiennes, them, bolton,
Nearest to be: have, is, by, been, was, enabling, were, become,
Nearest to known: used, vindicated, scam, such, banchan, carlist, interchange, bryant,
Nearest to had: has, have, was, were, became, disarm, prejudices, shrub,
Nearest to as: serie, ric, electromechanical, gumby, incompatibility, inc, acceptance, lowlands,
Nearest to five: four, six, three, two, zero, seven, eight, nine,
Nearest to first: second, nara, last, same, gassing, daleks, ced, grampus,
Nearest to of: for, asuras, condominiums, at, sabina, jail, abolitionist, merriam,
Nearest to by: with, be, in, for, were, was, at, across,
Nearest to at: in, on, from, eat, liberties, during, and, is,
Nearest to its: their, his, the, our, allotment, ethereal, kenyon, swinburne,
Nearest to however: but, logo, whitish, labeled, iverson, aeolus, repeatedly, when,
Average loss at step 22000: 3.504483
Average loss at step 24000: 3.492695
Average loss at step 26000: 3.481749
Average loss at step 28000: 3.481588
Average loss at step 30000: 3.503363
Nearest to that: which, what, this, zilog, catenary, but, shallower, appel,
Nearest to world: lebrun, lothair, niklaus, original, dory, ibsen, laszlo, league,
Nearest to while: slot, through, but, though, although, reproduce, usta, is,
Nearest to i: unicellular, ii, iii, sasl, repent, hymnal, camcorders, mimeograph,
Nearest to up: him, them, slur, diabetes, noticeably, chs, bolton, man,
Nearest to be: been, macros, have, enabling, were, is, behold, refer,
Nearest to known: used, such, written, scam, possible, vindicated, banchan, carlist,
Nearest to had: has, have, was, were, is, before, became, would,
Nearest to as: serie, ric, incompatibility, gumby, by, with, inc, behold,
Nearest to five: four, seven, six, three, eight, zero, two, nine,
Nearest to first: second, last, same, nara, gassing, syndicalists, nepotism, parties,
Nearest to of: in, and, from, jutes, for, predecessor, collation, competent,
Nearest to by: were, in, with, apec, dilated, instruction, alpina, curiosity,
Nearest to at: in, during, johore, eat, pythagoreans, liberties, gnu, respite,
Nearest to its: their, his, the, bingo, our, kenyon, curry, ethereal,
Nearest to however: but, logo, when, although, would, therefore, regiments, and,
Average loss at step 32000: 3.503823
Average loss at step 34000: 3.490536
Average loss at step 36000: 3.451427
Average loss at step 38000: 3.301047
Average loss at step 40000: 3.427026
Nearest to that: which, what, this, where, however, renegades, catenary, when,
Nearest to world: lothair, farr, laszlo, league, undertook, dory, lebrun, civil,
Nearest to while: although, though, are, lordship, through, when, were, obituary,
Nearest to i: ii, we, he, you, meagre, lemnos, battlecruiser, mater,
Nearest to up: him, them, out, back, slur, fandom, regard, man,
Nearest to be: have, been, refer, were, being, macros, become, kajang,
Nearest to known: used, such, possible, scam, regarded, carlist, hennessy, lenin,
Nearest to had: has, have, was, were, became, began, rimet, penfield,
Nearest to as: when, gumby, incompatibility, suffices, quadrants, manuel, untreated, ts,
Nearest to five: seven, six, four, three, eight, two, zero, nine,
Nearest to first: second, last, same, nara, nepotism, next, best, speeding,
Nearest to of: in, sells, for, merriam, borg, from, exe, dale,
Nearest to by: alpina, dalton, dispersive, ramgoolam, be, with, dilated, paolo,
Nearest to at: during, in, peckinpah, quark, on, liberties, eclipsing, timorese,
Nearest to its: their, his, the, our, her, cheese, pye, kenyon,
Nearest to however: but, although, would, quijote, that, hardly, regiments, though,
Average loss at step 42000: 3.435784
Average loss at step 44000: 3.454770
Average loss at step 46000: 3.454720
Average loss at step 48000: 3.350677
Average loss at step 50000: 3.382323
Nearest to that: which, however, what, where, zilog, reunification, shallower, but,
Nearest to world: civil, laszlo, undertook, mulligan, lothair, lebrun, sport, floor,
Nearest to while: although, when, though, and, after, however, but, where,
Nearest to i: we, ii, lippincott, lemnos, he, t, extremist, you,
Nearest to up: him, them, out, off, back, down, rydberg, fandom,
Nearest to be: have, been, was, refer, were, being, is, become,
Nearest to known: used, possible, such, regarded, written, carlist, scam, hennessy,
Nearest to had: has, have, was, were, having, penfield, artois, since,
Nearest to as: sermon, catching, specificity, incompatibility, artcyclopedia, is, when, burg,
Nearest to five: four, six, seven, eight, three, nine, two, zero,
Nearest to first: second, last, same, next, nepotism, original, third, nara,
Nearest to of: in, and, gleichschaltung, for, including, bangui, vernacular, ichij,
Nearest to by: was, with, attenuated, baluchistan, burgundian, pallas, alpina, reminding,
Nearest to at: during, lifestyle, pythagoreans, timorese, insurgencies, in, vytautas, on,
Nearest to its: their, his, the, our, her, whose, exploitative, herbicides,
Nearest to however: but, although, that, though, while, when, and, hardly,
Average loss at step 52000: 3.434542
Average loss at step 54000: 3.425755
Average loss at step 56000: 3.439364
Average loss at step 58000: 3.394515
Average loss at step 60000: 3.395599
Nearest to that: which, what, however, this, renegades, there, shallower, where,
Nearest to world: civil, mulligan, laszlo, dory, abbotsford, lebrun, bosniaks, floor,
Nearest to while: although, when, though, after, identifiers, lehigh, if, lordship,
Nearest to i: we, ii, lippincott, you, they, t, lemnos, magnate,
Nearest to up: out, him, them, off, down, back, tamil, together,
Nearest to be: been, refer, was, have, become, kajang, is, macros,
Nearest to known: used, possible, such, written, regarded, carlist, called, described,
Nearest to had: has, have, was, were, having, been, transcribing, ve,
Nearest to as: artcyclopedia, gumby, ric, denouncing, hulme, became, in, panhandle,
Nearest to five: four, six, three, eight, seven, zero, nine, two,
Nearest to first: second, last, same, best, third, next, fourth, original,
Nearest to of: in, for, augustan, same, luce, although, dimmu, physical,
Nearest to by: with, alpina, without, dispersive, cairn, activate, baluchistan, was,
Nearest to at: dollar, insurgencies, during, namco, in, timorese, exe, troposphere,
Nearest to its: their, his, the, her, our, whose, instants, vulgar,
Nearest to however: but, although, though, that, highwayman, when, which, there,
Average loss at step 62000: 3.241005
Average loss at step 64000: 3.261436
Average loss at step 66000: 3.406607
Average loss at step 68000: 3.394912
Average loss at step 70000: 3.356614
Nearest to that: which, what, however, but, this, where, carnivores, shallower,
Nearest to world: abbotsford, mulligan, bosniaks, laszlo, floor, civil, lebrun, sun,
Nearest to while: although, where, though, when, including, and, however, if,
Nearest to i: we, ii, g, lippincott, you, mimeograph, moller, kulak,
Nearest to up: them, off, out, him, down, back, tamil, rydberg,
Nearest to be: been, is, refer, were, being, become, have, are,
Nearest to known: used, such, possible, regarded, written, defined, described, seen,
Nearest to had: has, have, was, were, having, been, penfield, began,
Nearest to as: burkert, before, cardiomyopathy, by, when, in, expand, artcyclopedia,
Nearest to five: four, six, three, seven, eight, nine, zero, two,
Nearest to first: second, last, same, next, original, best, fourth, synthesizing,
Nearest to of: including, augustan, barbecue, firstborn, in, amphibian, shia, nicely,
Nearest to by: through, using, from, baluchistan, in, be, alpina, dowager,
Nearest to at: during, namco, on, heh, lifestyle, in, after, transplanted,
Nearest to its: their, his, her, our, the, ashcroft, whose, vulgar,
Nearest to however: but, although, though, when, that, while, where, highwayman,
Average loss at step 72000: 3.372038
Average loss at step 74000: 3.348384
Average loss at step 76000: 3.310601
Average loss at step 78000: 3.347736
Average loss at step 80000: 3.375984
Nearest to that: which, however, where, what, renegades, but, zilog, shallower,
Nearest to world: bosniaks, laszlo, sun, mulligan, lebrun, country, floor, abbotsford,
Nearest to while: although, though, when, after, but, and, however, or,
Nearest to i: we, ii, g, you, t, lippincott, fianc, kabbalists,
Nearest to up: out, off, him, them, down, back, tamil, together,
Nearest to be: been, have, being, refer, become, macros, remain, were,
Nearest to known: used, regarded, such, possible, defined, described, written, called,
Nearest to had: have, has, was, were, having, began, been, artois,
Nearest to as: untreated, when, selenium, bins, like, arbitrarily, encompasses, ediacaran,
Nearest to five: six, four, seven, eight, three, nine, two, zero,
Nearest to first: second, last, third, same, next, best, final, fourth,
Nearest to of: pikes, including, during, entire, following, diner, collation, original,
Nearest to by: when, through, alpina, using, without, baluchistan, curiosity, after,
Nearest to at: in, during, on, namco, peckinpah, ovaries, alonso, exe,
Nearest to its: their, his, her, our, the, your, my, whose,
Nearest to however: although, but, that, though, highwayman, while, when, where,
Average loss at step 82000: 3.408579
Average loss at step 84000: 3.410099
Average loss at step 86000: 3.388013
Average loss at step 88000: 3.349884
Average loss at step 90000: 3.368032
Nearest to that: which, however, what, renegades, where, piloting, but, dominating,
Nearest to world: lebrun, bosniaks, mulligan, floor, lawful, civil, abbotsford, ruling,
Nearest to while: although, when, though, after, before, but, where, were,
Nearest to i: g, we, ii, you, t, iv, betty, lippincott,
Nearest to up: off, out, them, him, back, down, together, tamil,
Nearest to be: been, refer, become, being, was, is, have, remain,
Nearest to known: used, such, regarded, possible, described, seen, opposed, defined,
Nearest to had: has, have, was, were, having, began, continued, been,
Nearest to as: whip, havelock, gumby, denouncing, macron, artcyclopedia, brookline, serie,
Nearest to five: four, seven, eight, three, six, two, nine, zero,
Nearest to first: second, last, same, original, next, fourth, third, best,
Nearest to of: in, including, for, vernacular, barbecue, pikes, asuras, same,
Nearest to by: without, through, with, under, when, alpina, from, for,
Nearest to at: during, under, on, pythagoreans, without, troposphere, once, johore,
Nearest to its: their, his, her, the, our, your, whose, vulgar,
Nearest to however: but, although, that, though, highwayman, while, russel, variously,
Average loss at step 92000: 3.397000
Average loss at step 94000: 3.256320
Average loss at step 96000: 3.356558
Average loss at step 98000: 3.237762
Average loss at step 100000: 3.356719
Nearest to that: which, what, however, where, but, who, shallower, lineman,
Nearest to world: bosniaks, lebrun, country, ruling, issue, mercury, eddington, mulligan,
Nearest to while: although, when, though, where, but, before, after, however,
Nearest to i: we, ii, you, g, lippincott, fianc, betty, they,
Nearest to up: off, out, them, him, back, down, together, fandom,
Nearest to be: been, being, are, become, refer, is, macros, have,
Nearest to known: such, possible, used, regarded, seen, defined, described, opposed,
Nearest to had: has, have, was, were, having, since, would, artois,
Nearest to as: when, cardiomyopathy, bins, meshech, like, suffices, arbitrarily, toleration,
Nearest to five: seven, four, six, eight, three, two, nine, zero,
Nearest to first: last, second, next, third, fourth, final, same, original,
Nearest to of: in, including, original, sabina, and, sedentary, during, firstborn,
Nearest to by: through, without, when, under, using, resolvers, kitab, with,
Nearest to at: during, on, in, allusions, timorese, after, observational, pythagoreans,
Nearest to its: their, his, our, her, the, vulgar, your, instants,
Nearest to however: but, although, that, though, and, while, when, where,

In [12]:
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 [27]:
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=(10, 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)



In [ ]: