In [1]:
# Basic example.

# Bridge python2 and python3
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

# Import our dependencies
import collections
import os
import tensorflow as tf
import numpy as np
import math
import random
import zipfile
from six.moves import urllib
from six.moves import xrange

In [2]:
# Download the data
url = 'http://mattmahoney.net/dc/'

def maybe_download(filename, expected_bytes):
    if not os.path.exists(filename):
        filename, _ = urllib.request.urlretrieve(url + filename, filename)
        
    statinfo = os.stat(filename)
    if statinfo.st_size == expected_bytes:
        print('Found and verified', filename)
        
    else:
        print(statinfo.st_size)
        raise Exception(
        'Failed to verify' + filename + '. Can you get to it with a browser?')
        
    return filename

In [3]:
filename = maybe_download('text8.zip', 31344016)


Found and verified text8.zip

In [4]:
# Read the data into a list of strings.
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

vocabulary = read_data(filename)
print('Data size', len(vocabulary))


Data size 17005207

In [5]:
# Step 2: Build the dictionary and replace rare words with UNK token.
vocabulary_size = 50000

def build_dataset(words, n_words):
    """Process raw inputs into a dataset."""
    count =[['UNK', -1]]
    count.extend(collections.Counter(words).most_common(n_words - 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
            unk_count += 1
        data.append(index)
    count[0][1] = unk_count
    reversed_dictionary = dict(zip(dictionary.values(), dictionary.keys()))
    return data, count, dictionary, reversed_dictionary

data, count, dictionary, reversed_dictionary = build_dataset(vocabulary, vocabulary_size)

In [6]:
del vocabulary # Reduce the memory.
print('Most common words (+UNK)', count[:5])
print('Sample data', data[:10], [reversed_dictionary[i] for i in data[:10]])


Most common words (+UNK) [['UNK', 418391], ('the', 1061396), ('of', 593677), ('and', 416629), ('one', 411764)]
Sample data [5237, 3081, 12, 6, 195, 2, 3137, 46, 59, 156] ['anarchism', 'originated', 'as', 'a', 'term', 'of', 'abuse', 'first', 'used', 'against']

In [7]:
data_index = 0

In [8]:
# Step 3: Function to generate a training batch for the skip-gram model.
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)
    if data_index + span > len(data):
        data_index = 0
    buffer.extend(data[data_index:data_index + span])
    data_index += span
    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]
        if data_index == len(data):
            buffer[:] = data[:span]
            data_index = span
        else:
            buffer.append(data[data_index])
            data_index += 1
            
    # Backtrack a little bit to avoid skipping words in the end of a batch.
    data_index = (data_index + len(data) - span) % len(data)
    return batch, labels

batch, labels = generate_batch(batch_size=8, num_skips=2, skip_window=1)

for i in range(8):
    print(batch[i], reversed_dictionary[batch[i]],
         '->', labels[i, 0], reversed_dictionary[labels[i, 0]])


3081 originated -> 5237 anarchism
3081 originated -> 12 as
12 as -> 3081 originated
12 as -> 6 a
6 a -> 195 term
6 a -> 12 as
195 term -> 6 a
195 term -> 2 of

In [9]:
# Step 4: Build and Train a skip-gram model.

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.random.choice(valid_window, valid_size, replace=False)
num_sampled = 64    # Number of negative examples to sample.

graph =tf.Graph()

with graph.as_default():
    
    # Input data
    train_inputs = 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)
    
    # Ops and variables pinned to the CPU because of missing GPU implementation
    with tf.device('/cpu:0'):
        # Look up embeddings for inputs
        embeddings = tf.Variable(
        tf.random_uniform([vocabulary_size, embedding_size], -1.0, 1.0))
        embed = tf.nn.embedding_lookup(embeddings, train_inputs)
        
        # Construct the variables for the NCE loss
        nce_weights = tf.Variable(
        tf.truncated_normal([vocabulary_size, embedding_size],
                           stddev=1.0 / math.sqrt(embedding_size)))
        nce_biases = tf.Variable(tf.zeros([vocabulary_size]))
  # Compute the average NCE loss for the batch.
  # tf.nce_loss automatically draws a new sample of the negative labels each
  # time we evaluate the loss.
    loss = tf.reduce_mean(
    tf.nn.nce_loss(weights=nce_weights,
                  biases=nce_biases,
                  labels=train_labels,
                  inputs=embed,
                  num_sampled=num_sampled,
                  num_classes=vocabulary_size))
    
    # Construct the SGD optimizer using a learning rate of 1.0
    optimizer = tf.train.GradientDescentOptimizer(1.0).minimize(loss)
    
    # Compute the cosine similarity between minibatch examples and all embeddings.
    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, normalized_embeddings, transpose_b=True)
    
    # Add variable initializer.
    init = tf.global_variables_initializer()

In [10]:
# Step 5: Begin training.
num_steps = 100001

with tf.Session(graph=graph) as session:
    # We must initialize all variables before we use them.
    init.run()
    print('Initialized')
    
    average_loss = 0
    for step in xrange(num_steps):
        batch_inputs, batch_labels = generate_batch(batch_size, num_skips, skip_window)
        feed_dict = {train_inputs: batch_inputs, train_labels: batch_labels}
        
        # We perform one update step by evaluating the optimizer op (including it
        # in the list of returned values for session.run()
        _, loss_val = session.run([optimizer, loss], feed_dict=feed_dict)
        average_loss += loss_val
        
        if step % 2000 ==0:
            if step > 0:
                average_loss /= 2000
            # The average loss is an estimate of the loss over the last 2000 batches
            print('Average loss at step ', 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 xrange(valid_size):
                valid_word = reversed_dictionary[valid_examples[i]]
                top_k = 8 # Number of nearest neighbors
                nearest = (-sim[i, :]).argsort()[1:top_k + 1]
                log_str = 'Nearest to %s: '% valid_word
                for k in xrange(top_k):
                    close_word = reversed_dictionary[nearest[k]]
                    log_str = '%s %s, ' % (log_str, close_word)
                print(log_str)
        final_embeddings = normalized_embeddings.eval()


Initialized
Average loss at step  0 :  256.125488281
Nearest to war:  baronies,  batavian,  glued,  hexen,  seng,  quadra,  permission,  absorbs, 
Nearest to one:  clipped,  rios,  nlds,  overlooking,  subtleties,  surpluses,  feeding,  runge, 
Nearest to often:  tesla,  installs,  chanukah,  benz,  adjustment,  ecu,  succumb,  subsisting, 
Nearest to no:  dou,  classical,  cations,  agena,  ganesh,  chorus,  tentacles,  corinth, 
Nearest to in:  rooster,  grouping,  trio,  speller,  wife,  insistence,  manna,  bentine, 
Nearest to called:  raeder,  pubs,  bofors,  fleurs,  mop,  phenol,  raisins,  colts, 
Nearest to more:  derby,  dualism,  hadadezer,  qigong,  betrothed,  oases,  comfortable,  dylan, 
Nearest to there:  weekly,  shorts,  byu,  cartoons,  backing,  alex,  hobbyists,  arithmetical, 
Nearest to at:  abdulaziz,  len,  cytology,  tremblay,  apartments,  silva,  saber,  escu, 
Nearest to i:  trajan,  familia,  hendrick,  invalid,  reichenbach,  spikes,  absurdum,  pseudocode, 
Nearest to with:  repository,  abrogation,  originates,  paste,  maneuverability,  ergot,  hempstead,  mph, 
Nearest to a:  similar,  munk,  disaccharide,  leda,  nova,  kimball,  strelitz,  apocalyptic, 
Nearest to two:  pane,  cloning,  shale,  rosario,  berwick,  taste,  inadequacy,  glance, 
Nearest to zero:  disney,  sparring,  muscat,  gimmicks,  potions,  pontiac,  escaped,  logged, 
Nearest to over:  miocene,  inputs,  fonda,  sta,  squarepants,  tertullian,  nordic,  rabbinic, 
Nearest to history:  reactivated,  neighbourhoods,  hernando,  glamorous,  abolishing,  padding,  bullock,  camping, 
Average loss at step  2000 :  113.48879455
Average loss at step  4000 :  52.7594953554
Average loss at step  6000 :  33.4944622982
Average loss at step  8000 :  23.2072636607
Average loss at step  10000 :  17.963139003
Nearest to war:  chinese,  contrast,  permission,  amplifier,  napoleon,  deuteronomy,  arkham,  channel, 
Nearest to one:  two,  nine,  archie,  zero,  coke,  vs,  three,  jpg, 
Nearest to often:  carinthia,  generals,  examples,  benz,  followed,  supercontinent,  robeson,  accept, 
Nearest to no:  yeast,  classical,  chorus,  junior,  vs,  cocaine,  believed,  and, 
Nearest to in:  and,  of,  on,  with,  for,  to,  by,  from, 
Nearest to called:  bofors,  pubs,  gland,  squid,  phenol,  morphology,  side,  agnosticism, 
Nearest to more:  very,  comfortable,  dylan,  oases,  fear,  derby,  adopted,  revised, 
Nearest to there:  weekly,  alex,  eighteen,  and,  cartoons,  archie,  cardinality,  ruled, 
Nearest to at:  of,  from,  in,  is,  inch,  silva,  annual,  by, 
Nearest to i:  good,  santos,  freedom,  regime,  familia,  tories,  unable,  invalid, 
Nearest to with:  in,  and,  basins,  maximum,  web,  one,  on,  to, 
Nearest to a:  the,  vs,  jpg,  cc,  UNK,  agave,  cardinality,  and, 
Nearest to two:  one,  bckgr,  nine,  archie,  zero,  mosque,  three,  zar, 
Nearest to zero:  nine,  eight,  six,  coke,  agave,  one,  bckgr,  archie, 
Nearest to over:  aries,  miocene,  inputs,  nordic,  conduct,  academy,  sentiments,  amplifier, 
Nearest to history:  labour,  reginae,  come,  cease,  glamorous,  disaster,  conservative,  midst, 
Average loss at step  12000 :  13.9055444072
Average loss at step  14000 :  11.8678603967
Average loss at step  16000 :  9.99394213057
Average loss at step  18000 :  8.38209566092
Average loss at step  20000 :  8.11842006624
Nearest to war:  chinese,  permission,  contrast,  circ,  napoleon,  audacity,  plow,  jagiellon, 
Nearest to one:  two,  three,  eight,  circ,  nine,  six,  dasyprocta,  operatorname, 
Nearest to often:  carinthia,  generals,  strasbourg,  examples,  supercontinent,  gollancz,  followed,  would, 
Nearest to no:  operatorname,  yeast,  acacia,  dou,  rape,  a,  closet,  gypsum, 
Nearest to in:  and,  on,  for,  of,  with,  agouti,  at,  from, 
Nearest to called:  agouti,  homomorphism,  bofors,  pubs,  squid,  morphology,  phenol,  gland, 
Nearest to more:  very,  comfortable,  motifs,  dylan,  derby,  qigong,  oases,  furnishing, 
Nearest to there:  it,  eighteen,  weekly,  he,  arithmetical,  alex,  ruled,  amphitryon, 
Nearest to at:  in,  from,  and,  gollancz,  of,  inch,  during,  rotate, 
Nearest to i:  regime,  feynman,  good,  mousetrap,  delayed,  familia,  freedom,  unable, 
Nearest to with:  in,  and,  by,  on,  for,  of,  maximum,  basins, 
Nearest to a:  the,  this,  vs,  dasyprocta,  any,  circ,  one,  agouti, 
Nearest to two:  one,  three,  five,  seven,  six,  zero,  eight,  nine, 
Nearest to zero:  eight,  nine,  six,  five,  seven,  four,  three,  dasyprocta, 
Nearest to over:  aries,  and,  discontinuous,  miocene,  polymerization,  resonator,  compromising,  inputs, 
Nearest to history:  labour,  cease,  midst,  dasyprocta,  amazonas,  abolishing,  reginae,  frontal, 
Average loss at step  22000 :  6.92261194623
Average loss at step  24000 :  6.88105111957
Average loss at step  26000 :  6.76036904693
Average loss at step  28000 :  6.39946018732
Average loss at step  30000 :  5.92384209216
Nearest to war:  quadra,  chinese,  permission,  trinomial,  audacity,  contrast,  napoleon,  jagiellon, 
Nearest to one:  two,  four,  eight,  seven,  dasyprocta,  three,  circ,  operatorname, 
Nearest to often:  also,  carinthia,  strasbourg,  generals,  almighty,  would,  gollancz,  supercontinent, 
Nearest to no:  operatorname,  rape,  dou,  canova,  yeast,  acacia,  nine,  and, 
Nearest to in:  on,  and,  at,  from,  for,  of,  agouti,  with, 
Nearest to called:  agouti,  homomorphism,  bofors,  pubs,  raeder,  morphology,  squid,  abet, 
Nearest to more:  very,  comfortable,  motifs,  dylan,  oases,  compartments,  qigong,  woolwich, 
Nearest to there:  it,  almighty,  he,  eighteen,  they,  shorts,  arithmetical,  moloch, 
Nearest to at:  in,  from,  during,  and,  gollancz,  of,  rotate,  abet, 
Nearest to i:  delayed,  regime,  mousetrap,  six,  feynman,  g,  abakan,  two, 
Nearest to with:  in,  by,  and,  for,  on,  coke,  basins,  between, 
Nearest to a:  the,  abet,  any,  dasyprocta,  this,  their,  operatorname,  circ, 
Nearest to two:  three,  four,  five,  six,  one,  eight,  seven,  agouti, 
Nearest to zero:  six,  eight,  five,  four,  seven,  nine,  three,  dasyprocta, 
Nearest to over:  aries,  discontinuous,  and,  rabbinic,  with,  miocene,  spanish,  centauri, 
Nearest to history:  console,  midst,  cease,  frontal,  dasyprocta,  abolishing,  hereford,  conservative, 
Average loss at step  32000 :  5.9325501616
Average loss at step  34000 :  5.70974723554
Average loss at step  36000 :  5.80503253639
Average loss at step  38000 :  5.5000863241
Average loss at step  40000 :  5.24327234399
Nearest to war:  quadra,  chinese,  permission,  trinomial,  aveiro,  mordechai,  audacity,  napoleon, 
Nearest to one:  two,  eight,  four,  three,  six,  seven,  five,  zero, 
Nearest to often:  also,  strasbourg,  carinthia,  usually,  generals,  agglutinative,  observational,  which, 
Nearest to no:  operatorname,  rape,  acacia,  canova,  dou,  downloading,  a,  nine, 
Nearest to in:  on,  and,  at,  from,  during,  agouti,  of,  abet, 
Nearest to called:  agouti,  homomorphism,  pubs,  bofors,  and,  morphology,  raeder,  abet, 
Nearest to more:  very,  comfortable,  most,  compartments,  oases,  derby,  albury,  motifs, 
Nearest to there:  it,  they,  he,  almighty,  eighteen,  shorts,  also,  moloch, 
Nearest to at:  in,  from,  during,  rotate,  gollancz,  and,  under,  abet, 
Nearest to i:  delayed,  regime,  mousetrap,  abakan,  feynman,  g,  nail,  tories, 
Nearest to with:  in,  and,  for,  between,  by,  under,  on,  coke, 
Nearest to a:  the,  abet,  any,  dasyprocta,  circ,  eight,  its,  lazio, 
Nearest to two:  three,  one,  four,  five,  six,  eight,  seven,  zero, 
Nearest to zero:  eight,  six,  five,  seven,  four,  nine,  three,  dasyprocta, 
Nearest to over:  aries,  rabbinic,  thabit,  discontinuous,  with,  miocene,  spanish,  dip, 
Nearest to history:  neighbourhoods,  midst,  console,  cease,  frontal,  abolishing,  dasyprocta,  universit, 
Average loss at step  42000 :  5.36412538362
Average loss at step  44000 :  5.24571981144
Average loss at step  46000 :  5.22912004554
Average loss at step  48000 :  5.24206423473
Average loss at step  50000 :  4.99505409825
Nearest to war:  quadra,  glued,  chinese,  permission,  mordechai,  trinomial,  aveiro,  batavian, 
Nearest to one:  two,  four,  eight,  three,  six,  seven,  five,  dasyprocta, 
Nearest to often:  also,  usually,  strasbourg,  roshan,  now,  tesla,  carinthia,  widely, 
Nearest to no:  operatorname,  rape,  canova,  dou,  acacia,  downloading,  a,  closet, 
Nearest to in:  on,  at,  during,  agouti,  of,  and,  from,  abet, 
Nearest to called:  agouti,  homomorphism,  and,  pubs,  abet,  bofors,  aquila,  morphology, 
Nearest to more:  very,  most,  hadadezer,  comfortable,  kapoor,  furnishing,  compartments,  oases, 
Nearest to there:  it,  they,  he,  almighty,  eighteen,  now,  immersed,  which, 
Nearest to at:  in,  during,  from,  rotate,  and,  gollancz,  abet,  masking, 
Nearest to i:  delayed,  g,  mousetrap,  abakan,  regime,  five,  fripp,  feynman, 
Nearest to with:  in,  and,  by,  for,  between,  kapoor,  coke,  agouti, 
Nearest to a:  the,  any,  artemis,  abet,  hygiene,  solicitation,  its,  their, 
Nearest to two:  three,  four,  six,  one,  five,  seven,  eight,  dasyprocta, 
Nearest to zero:  eight,  six,  seven,  four,  five,  nine,  three,  dasyprocta, 
Nearest to over:  aries,  three,  spanish,  dip,  with,  eight,  rabbinic,  thabit, 
Nearest to history:  neighbourhoods,  reactivated,  midst,  frontal,  kvac,  cease,  dasyprocta,  console, 
Average loss at step  52000 :  5.02781537628
Average loss at step  54000 :  5.20035373425
Average loss at step  56000 :  5.03388169527
Average loss at step  58000 :  5.04096658444
Average loss at step  60000 :  4.95575606167
Nearest to war:  brp,  mordechai,  aveiro,  audacity,  quadra,  chinese,  jagiellon,  permission, 
Nearest to one:  two,  five,  six,  four,  three,  eight,  ursus,  operatorname, 
Nearest to often:  also,  usually,  strasbourg,  roshan,  still,  widely,  now,  tesla, 
Nearest to no:  operatorname,  rape,  canova,  a,  dou,  acacia,  downloading,  nine, 
Nearest to in:  on,  during,  at,  and,  agouti,  from,  of,  gollancz, 
Nearest to called:  agouti,  homomorphism,  pubs,  bofors,  abet,  UNK,  morphology,  frustration, 
Nearest to more:  very,  most,  hadadezer,  comfortable,  less,  kapoor,  albury,  compartments, 
Nearest to there:  it,  they,  he,  almighty,  immersed,  eighteen,  which,  moloch, 
Nearest to at:  in,  during,  pulau,  gollancz,  from,  thibetanus,  rotate,  five, 
Nearest to i:  delayed,  g,  mousetrap,  fripp,  abakan,  regime,  we,  ii, 
Nearest to with:  in,  between,  by,  and,  kapoor,  coke,  ursus,  agouti, 
Nearest to a:  the,  any,  abet,  roshan,  dasyprocta,  this,  cardinality,  ursus, 
Nearest to two:  three,  four,  five,  six,  one,  ursus,  eight,  agouti, 
Nearest to zero:  seven,  six,  eight,  five,  nine,  four,  dasyprocta,  ursus, 
Nearest to over:  aries,  spanish,  dip,  six,  three,  thabit,  discontinuous,  gst, 
Nearest to history:  neighbourhoods,  reactivated,  midst,  dasyprocta,  frontal,  kvac,  console,  cease, 
Average loss at step  62000 :  5.00046935546
Average loss at step  64000 :  4.84309346265
Average loss at step  66000 :  4.61848791575
Average loss at step  68000 :  4.96936549592
Average loss at step  70000 :  4.87830419707
Nearest to war:  brp,  mordechai,  glued,  quadra,  aveiro,  trinomial,  chinese,  audacity, 
Nearest to one:  two,  six,  five,  three,  four,  eight,  ursus,  seven, 
Nearest to often:  also,  usually,  now,  still,  widely,  strasbourg,  roshan,  sometimes, 
Nearest to no:  operatorname,  canova,  microcebus,  dou,  rape,  acacia,  downloading,  a, 
Nearest to in:  during,  at,  agouti,  on,  pulau,  dasyprocta,  abet,  gollancz, 
Nearest to called:  agouti,  homomorphism,  abet,  and,  pubs,  UNK,  gland,  bofors, 
Nearest to more:  very,  most,  less,  hadadezer,  comfortable,  kapoor,  larger,  furnishing, 
Nearest to there:  it,  they,  he,  almighty,  now,  which,  immersed,  moloch, 
Nearest to at:  in,  during,  pulau,  rotate,  thibetanus,  gollancz,  thaler,  under, 
Nearest to i:  delayed,  g,  we,  fripp,  mousetrap,  ii,  abakan,  regime, 
Nearest to with:  between,  in,  coke,  by,  kapoor,  while,  microcebus,  ursus, 
Nearest to a:  the,  any,  abet,  roshan,  dasyprocta,  or,  hygiene,  ursus, 
Nearest to two:  three,  six,  five,  four,  one,  eight,  ursus,  seven, 
Nearest to zero:  eight,  five,  six,  seven,  nine,  four,  dasyprocta,  three, 
Nearest to over:  aries,  spanish,  dip,  three,  microcebus,  tariff,  thabit,  gst, 
Nearest to history:  neighbourhoods,  reactivated,  dasyprocta,  hereford,  console,  thaler,  frontal,  kvac, 
Average loss at step  72000 :  4.75430187297
Average loss at step  74000 :  4.79805519032
Average loss at step  76000 :  4.73123903799
Average loss at step  78000 :  4.81065634012
Average loss at step  80000 :  4.78391779649
Nearest to war:  brp,  glued,  mordechai,  quadra,  audacity,  batavian,  jagiellon,  permission, 
Nearest to one:  two,  six,  seven,  four,  five,  three,  ursus,  operatorname, 
Nearest to often:  usually,  also,  still,  now,  widely,  sometimes,  roshan,  strasbourg, 
Nearest to no:  dou,  operatorname,  canova,  rape,  microcebus,  a,  acacia,  downloading, 
Nearest to in:  during,  on,  at,  agouti,  abet,  and,  gollancz,  of, 
Nearest to called:  agouti,  UNK,  abet,  homomorphism,  gland,  and,  austrians,  apatosaurus, 
Nearest to more:  very,  most,  less,  hadadezer,  comfortable,  kapoor,  larger,  restraint, 
Nearest to there:  it,  they,  he,  almighty,  now,  immersed,  which,  moloch, 
Nearest to at:  during,  in,  pulau,  rotate,  on,  from,  thibetanus,  under, 
Nearest to i:  g,  delayed,  we,  witwatersrand,  ii,  mousetrap,  abakan,  iii, 
Nearest to with:  between,  in,  by,  microcebus,  coke,  ursus,  kapoor,  ramps, 
Nearest to a:  the,  dasyprocta,  pontificia,  abet,  microcebus,  any,  roshan,  callithrix, 
Nearest to two:  three,  four,  six,  five,  one,  seven,  ursus,  eight, 
Nearest to zero:  five,  eight,  six,  seven,  four,  nine,  ursus,  dasyprocta, 
Nearest to over:  aries,  dip,  spanish,  tariff,  three,  microcebus,  gst,  discontinuous, 
Nearest to history:  neighbourhoods,  reactivated,  hereford,  dasyprocta,  padding,  frontal,  kvac,  midst, 
Average loss at step  82000 :  4.76589788294
Average loss at step  84000 :  4.76574867678
Average loss at step  86000 :  4.76153513241
Average loss at step  88000 :  4.73987494373
Average loss at step  90000 :  4.74054417133
Nearest to war:  brp,  mordechai,  glued,  quadra,  jagiellon,  during,  audacity,  permission, 
Nearest to one:  two,  three,  four,  seven,  six,  five,  eight,  ursus, 
Nearest to often:  usually,  also,  still,  sometimes,  now,  widely,  roshan,  easily, 
Nearest to no:  scalia,  dou,  operatorname,  medgar,  microcebus,  canova,  rape,  downloading, 
Nearest to in:  during,  on,  at,  agouti,  pulau,  and,  gollancz,  abet, 
Nearest to called:  agouti,  abet,  homomorphism,  austrians,  gland,  apatosaurus,  UNK,  basins, 
Nearest to more:  very,  less,  most,  hadadezer,  comfortable,  kapoor,  larger,  restraint, 
Nearest to there:  they,  it,  he,  now,  almighty,  immersed,  still,  moloch, 
Nearest to at:  in,  during,  pulau,  on,  rotate,  from,  thibetanus,  when, 
Nearest to i:  we,  ii,  you,  g,  delayed,  witwatersrand,  iii,  mousetrap, 
Nearest to with:  between,  by,  in,  ursus,  microcebus,  while,  ramps,  kapoor, 
Nearest to a:  the,  another,  any,  pontificia,  microcebus,  roshan,  abet,  ursus, 
Nearest to two:  three,  four,  five,  one,  six,  seven,  eight,  ursus, 
Nearest to zero:  five,  eight,  seven,  six,  nine,  four,  ursus,  dasyprocta, 
Nearest to over:  within,  dip,  aries,  coincidentally,  gst,  discontinuous,  spanish,  tariff, 
Nearest to history:  peacocks,  neighbourhoods,  hereford,  dasyprocta,  padding,  conservative,  reactivated,  frontal, 
Average loss at step  92000 :  4.67660328543
Average loss at step  94000 :  4.72435604775
Average loss at step  96000 :  4.68681526983
Average loss at step  98000 :  4.59555627429
Average loss at step  100000 :  4.69024629998
Nearest to war:  during,  brp,  quadra,  glued,  mordechai,  jagiellon,  aveiro,  deceleration, 
Nearest to one:  two,  six,  four,  seven,  five,  three,  ursus,  eight, 
Nearest to often:  usually,  also,  sometimes,  now,  still,  widely,  strasbourg,  roshan, 
Nearest to no:  dou,  scalia,  medgar,  operatorname,  microcebus,  rape,  acacia,  a, 
Nearest to in:  during,  at,  on,  agouti,  gollancz,  from,  pulau,  within, 
Nearest to called:  agouti,  abet,  and,  austrians,  homomorphism,  gland,  named,  intercept, 
Nearest to more:  very,  less,  most,  hadadezer,  comfortable,  kapoor,  larger,  albury, 
Nearest to there:  they,  it,  he,  now,  immersed,  almighty,  still,  which, 
Nearest to at:  during,  in,  pulau,  under,  on,  rotate,  thibetanus,  gollancz, 
Nearest to i:  we,  you,  ii,  g,  witwatersrand,  delayed,  iii,  abakan, 
Nearest to with:  between,  in,  kapoor,  by,  during,  microcebus,  ursus,  for, 
Nearest to a:  the,  any,  another,  abet,  pontificia,  roshan,  dasyprocta,  hygiene, 
Nearest to two:  three,  four,  five,  six,  one,  seven,  eight,  ursus, 
Nearest to zero:  eight,  five,  seven,  four,  nine,  six,  three,  dasyprocta, 
Nearest to over:  within,  dip,  gst,  three,  coincidentally,  discontinuous,  aries,  spanish, 
Nearest to history:  peacocks,  neighbourhoods,  dasyprocta,  hereford,  frontal,  iit,  padding,  kvac, 

In [12]:
# Step 6: Visualize the embeddings.

def plot_with_labels(low_dim_embs, labels, filename='tsne.png'):
    assert low_dim_embs.shape[0] >= len(labels), 'More labels than embeddings'
    plt.figure(figsize=(18,18)) # in inches
    for i, label in enumerate(labels):
        x, y = low_dim_embs[i, :]
        plt.scatter(x, y)
        plt.annotate(label, xy=(x, y),
                    xytext=(5, 2),
                    textcoords='offset points',
                    ha='right',
                    va='bottom')
        
    plt.savefig(filename)

try:
    # pylint: disable=g-import-not-at-top
    from sklearn.manifold import TNSE
    import matplotlib.pyplot as plt
    
    tsne = TSNE(perplexity=30, n_components=2, init='pca',
                n_iter=5000, method='exact')
    plot_only = 500
    low_dim_embs = tsne.fit_transform(final_embeddings[:plot_only, :])
    labels = [reversed_dictionary[i] for i in xrange(plot_only)]
    plot_with_labels(low_dim_embs, labels)
    
except ImportError:
    print('Please install sklearn, matplotlib, scipy to show embeddings.')


Please install sklearn, matplotlib, scipy to show embeddings.

In [ ]: