<jupyter_start><jupyter_text>Import TensforFlow and Numpy, make sure the package is there<jupyter_code>import numpy as np
import tensorflow as tf<jupyter_output><empty_output><jupyter_text>Read the text into a list of strings, using tensorflow<jupyter_code>import zipfile as zf

#This function return a list of words
def read_data(filename):
  with zf.ZipFile(filename) as f:
    raw=f.read(f.namelist()[0])
    data = tf.compat.as_str(raw).split()    
        #tf.compat is not in online document
  return data

word_list = read_data('data/text/text8.zip')
#data size is the total number of words in the file
print 'Data size: ', len(word_list)<jupyter_output>Data size:  17005207<jupyter_text>Build dataset<jupyter_code>import collections

#This is our universe, we don't study any word outside this vocabulary 
vocabulary_size = 50000  

#Replace every word by its index, this is our dataset; replace rare words with token "UNK"
def build_dataset(words):
  #initialize an array with word and its count, with the first word as 'UNK'
  word_Count = [['UNK', -1]]   
  #Find common words, and add them to our vocabulary array
  unique_words=collections.Counter(word_list)
  print "unique words: ", len(unique_words)
  # We are using a function from "Collection", most_common  
  common_words=unique_words.most_common(vocabulary_size-1)  
          #make sure this is "vocabulary_size-1" as we already have 1 word in 
  word_Count.extend(common_words)
  """After the above operation, word_Count is a 2-d array with 50,001 words and their count"""

  #Initialize an empty hashtable
  dictionary = dict()
  for word, _ in word_Count:
    dictionary[word] = len(dictionary)  #current size, thus it is an index
  """After the above operation, dictionary is a hashtable with 50,001 words and their index, ordered by Count"""

  #Create our dataset, where every word is replaced by its index
  data = list()
  unk_count = 0
  for word in word_list:
    if word in dictionary:
      index = dictionary[word]
    else:
      index = 0  # dictionary['UNK']
      unk_count += 1
    data.append(index)
    
  #Update the count for UNK, any word that is not common is considered as UNK
  word_Count[0][1] = unk_count  #this is a side-product

  reverse_dictionary = dict(zip(dictionary.values(), dictionary.keys())) #zip just make the hashtable more compact
    
  return data, word_Count, dictionary, reverse_dictionary

#It takes about 4 seconds to finish
data, word_Count, dictionary, reverse_dictionary = build_dataset(word_list)
del word_list  # to reduce memory.

print('top 10 common words (+UNK)', word_Count[:10])   #the top 10 common words
print ('data= ', data[:10])
print('Sample data',  [reverse_dictionary[i] for i in data[:10]])<jupyter_output>unique words:  253854
('top 10 common words (+UNK)', [['UNK', 418391], ('the', 1061396), ('of', 593677), ('and', 416629), ('one', 411764), ('in', 372201), ('a', 325873), ('to', 316376), ('zero', 264975), ('nine', 250430)])
('data= ', [5239, 3084, 12, 6, 195, 2, 3137, 46, 59, 156])
('Sample data', ['anarchism', 'originated', 'as', 'a', 'term', 'of', 'abuse', 'first', 'used', 'against'])<jupyter_text>Generate a training batch for the skip-gram model. Reference paper:<jupyter_code>import random

data_index = 0

batch_size = 128  #the number of words we process each time 
embedding_size = 128  # Dimension of the embedding vector.
num_skips = 2      # How many times to reuse an input to generate a label.
skip_window = 1      # Number of words to consider left and right.

#Given batch size, generate labeled data from original sequence
#for every word, find its label, which is within the skip-window
def generate_batch(batch_size, num_skips, skip_window):
  global data_index

  assert batch_size % num_skips == 0  #if this condition does not hold, the system will issue error
  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)

  """Read data if size span into buffer """ 
  ## Span is the total number of words, before + after+ current word
  span = 2 * skip_window + 1   #span=3
  buffer = collections.deque(maxlen=span)
  for _ in range(span):
    buffer.append(data[data_index])
    data_index = data_index + 1
  
  """ The actual number of operation is batch_size // num_skips, where "//" is floor division, removing decimal numbers """ 
  for i in range(batch_size // num_skips):
    # start with the center word, 
    target = skip_window  
    
    # this is a list that records what we have processed
    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
    
  return batch, labels

#Some sample output
batch, labels = generate_batch(batch_size=10, num_skips=2, skip_window=1)
print batch
print labels
for i in range(len(batch)):
  print(reverse_dictionary[batch[i]], '->', reverse_dictionary[labels[i, 0]])
print "data index=",data_index<jupyter_output>[3084 3084   12   12    6    6  195  195    2    2]
[[5239]
 [  12]
 [3084]
 [   6]
 [ 195]
 [  12]
 [   6]
 [   2]
 [3137]
 [ 195]]
('originated', '->', 'anarchism')
('originated', '->', 'as')
('as', '->', 'originated')
('as', '->', 'a')
('a', '->', 'term')
('a', '->', 'as')
('term', '->', 'a')
('term', '->', 'of')
('of', '->', 'abuse')
('of', '->', 'term')
data index= 8<jupyter_text>Build and train a skip-gram model.<jupyter_code>#Some sample output
batch, labels = generate_batch(batch_size=10, num_skips=2, skip_window=1)
print batch
print labels
for i in range(len(batch)):
  print(reverse_dictionary[batch[i]], '->', reverse_dictionary[labels[i, 0]])
print "data index=",data_index
import math

# We pick a random validation set to sample nearest neighbors. Here we limit the validation samples to frequent words .
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():
  train_inputs = tf.placeholder(tf.int32, shape=[batch_size])
     #a list if integers that are indexes for words
  train_labels = tf.placeholder(tf.int32, shape=[batch_size, 1])
     #a list if integers that are indexes for words
  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'):
    #word vectors are all intialized as numbers between -1 and 1 
    wordsE = tf.Variable(tf.random_uniform([vocabulary_size, embedding_size], -1.0, 1.0))
    
    #inputE is a smaller size list than all wordsE, 
    inputE = tf.nn.embedding_lookup(wordsE, train_inputs)
    #The resulting dimension is [batch_size, embedding_size]
    
    # Construct the variables
    #The weights is initialized from a normal distribution, with mean 0 and standard deviation 1/128^2, almost 0
    initial_weights=tf.truncated_normal([vocabulary_size, embedding_size], stddev=1.0 / math.sqrt(embedding_size))
    weights = tf.Variable(initial_weights)
    biases = tf.Variable(tf.zeros([vocabulary_size]))

  loss = tf.reduce_mean(
              tf.nn.sampled_softmax_loss(weights, biases, inputE, train_labels, num_sampled, 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(wordsE), 1, keep_dims=True))
  normalized_wordsE = wordsE / norm
    
  #calculate pairwise similarity score for every word in valid set, and all the words in vocabulary
  validE = tf.nn.embedding_lookup(normalized_wordsE, valid_dataset)
  similarity = tf.matmul(validE, normalized_wordsE, transpose_b=True)

  # Add variable initializer.
  init = tf.initialize_all_variables()

with tf.Session() as sess:
    allwords =tf.Variable(tf.random_uniform([5, 2], -1.0, 1.0)) 
    #Variable has to initialized before running
    #sess.run(allwords.initializer)
    tf.initialize_all_variables().run() #this is more general
    print allwords.eval()
    batch=[1,3,4]
    bwords=tf.nn.embedding_lookup(allwords, batch)
    print bwords.eval()<jupyter_output>[[ 0.72809243 -0.58059263]
 [-0.51278496  0.12801981]
 [ 0.63370943  0.52823448]
 [ 0.83592129  0.17996573]
 [ 0.06860638  0.12861061]]
[[-0.51278496  0.12801981]
 [ 0.83592129  0.17996573]
 [ 0.06860638  0.12861061]]<jupyter_text>Begin training.<jupyter_code>print normalized_wordsE
from six.moves import xrange   

num_steps = 100001

with tf.Session(graph=graph) as session:
  init.run()  #initialize the graph
  print("Initialized")
  #print normalized_wordsE.eval()

  data_index=0 #Reinitialize, important to do this
  average_loss = 0
  for step in xrange(num_steps):
    binputs, blabels = generate_batch(batch_size, num_skips, skip_window)
    # We perform one update step by evaluating the optimizer op (including it
    # in the list of returned values for session.run()
    assignment={train_inputs : binputs, train_labels : blabels}
    _, loss_val = session.run([optimizer, loss], feed_dict = assignment )
    average_loss += loss_val

    if step % 2000 == 0:
      # The average loss is an estimate of the loss over the last 2000 batches.
      if step > 0:
        average_loss /= 2000
      print("Average loss at step ", step, ": ", average_loss)
      average_loss = 0
    
    """
    if step == 2000:
      print binputs  #a list of indexes
      #print blabels
      print wordsE.eval()  
      print normalized_wordsE.eval()
      print inputE
      #print inputE.eval()
    """
    
    # Note that this is expensive, so only doing it every 10,000
    if step % 10000 == 0:  
      sim = similarity.eval()  #get pairwise similarity for every word
      for i in range(5):
        valid_word = reverse_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 = reverse_dictionary[nearest[k]]
          log_str = "%s %s," % (log_str, close_word)
        print(log_str)
        
  final_wordsE = normalized_wordsE.eval()<jupyter_output>Initialized
('Average loss at step ', 0, ': ', 7.840111255645752)
Nearest to one: bertolt, mergers, kristallnacht, observatories, silvanus, ambedkar, selznick, electrically,
Nearest to people: behavior, coronado, npd, pathos, soliciting, mauritian, applicant, decidedly,
Nearest to that: prefrontal, gross, werth, enquiries, over, patriarchates, tortoise, rk,
Nearest to new: chap, exarch, donegal, zealot, ptah, serine, updating, hillary,
Nearest to state: archaeoastronomy, cheered, rigid, marlowe, boyd, qaeda, kilometers, psionic,
('Average loss at step ', 2000, ': ', 4.8493102321624759)
('Average loss at step ', 4000, ': ', 4.1473633738979698)
('Average loss at step ', 6000, ': ', 4.04280930018425)
('Average loss at step ', 8000, ': ', 3.8951156964600084)
('Average loss at step ', 10000, ': ', 3.8154547293186187)
Nearest to one: two, arnstadt, ambedkar, UNK, sur, the, manic, adler,
Nearest to people: behavior, npd, mauritian, pathos, coronado, no, supplemental, soliciting,
Nearest to th[...]<jupyter_text>Visualize the results<jupyter_code>print(final_wordsE)
import matplotlib.pyplot as plt
%matplotlib inline

import sklearn
from sklearn.manifold import TSNE
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)

tsne = TSNE(perplexity=30, n_components=2, init='pca', n_iter=5000)
plot_only = 500
low_dim_embs = tsne.fit_transform(final_wordsE[:plot_only,:])
labels = [reverse_dictionary[i] for i in xrange(plot_only)]
plot_with_labels(low_dim_embs, labels)<jupyter_output><empty_output>
{'fraction_non_alphanumeric': 0.1143832354341959, 'fraction_numerical': 0.04691220828702969, 'mean_word_length': 4.021522518931845, 'pattern_counts': {'":': 1, '<': 25, '<?xml version=': 0, '>': 38, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 1, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '7', 'dir': 'jupyter-structured-clean-dedup', 'id': '619825', 'license': 'Apache-2.0', 'n_tokens_mistral': 4580, 'n_tokens_neox': 4096, 'n_words': 1289, 'path': 'jupyterhub/notebooks/zz_under_construction/zz_old/TensorFlow/Labs/lab4_word2Vec.ipynb', 'repo_name': 'just4jc/pipeline', 'size': '12598'}