tensorflow中的word2vec代码注解

    本文对谷歌开源的词向量生成工具 word2vec_basic.py 进行了注释,以备自己和需要了解其运行原理的同学理解其背后的机理,有注解不当之处还请及时提出,本人会不断修正,争取每一行代码都有正确和清晰的注解。

   可以分为如下几个步骤。

  •  下载数据,将数据读取为列表格式
     
    from __future__ import absolute_import
    from __future__ import print_function
    
    import collections
    import math
    import os
    import random
    import zipfile
    
    import numpy as np
    from six.moves import urllib
    from six.moves import xrange  # pylint: disable=redefined-builtin
    import tensorflow as tf
    
    # Step 1: 下载数据
    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, _ = 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
    
    filename = maybe_download('text8.zip', 31344016)
    
    
    # 将文件内容读取为列表格式
    def read_data(filename):
      f = zipfile.ZipFile(filename)
      for name in f.namelist():
        return f.read(name).split()
      f.close()
    
    words = read_data(filename)
    print('Data size', len(words))

     

  •  构造词典和逆向词典等训练数据,定义miniBatch生成方法
     
    vocabulary_size = 50000
    # Step 2: Build the dictionary and replace rare words with UNK token.
    '''
        构建数据,为后面训练模型做准备
        输入:words, 单词列表
        输出:data, words中每个词在dictionary中对应的值, 即词的索引
              count, 词与词频的元组列表,其中'UNK'表示所有非高频词的数量
              dictionary, 词与词索引的映射
              reverse_dictionary, dictionary的逆向映射
    '''
    def build_dataset(words):
      count = [['UNK', -1]]
      # 选取words中词频最高的49999个词,以(word, frequency)的格式加入count
      # 此时count内部的元素排列如:[['UNK',-1], ('is',2), ('name',5), ...]
      count.extend(collections.Counter(words).most_common(vocabulary_size - 1))
      
      # 创建词到词索引的映射,如: {'UNK' : 1, 'is' : 200, 'name' : 30, ... }
      dictionary = dict()
      for word, _ in count:
        dictionary[word] = len(dictionary)
        
      # 对words中的每个词,将其在dictionary中的索引取出,放到data列表中
      # 最终的data列表,如[1,3,2,5,20,0,2,0,0,9,...],0表示某个词不在词频最高的49999个词当中
      # 同时,计数'UNK'的数量
      data = list()
      unk_count = 0
      for word in words:
        if word in dictionary:
          index = dictionary[word]
        else:
          index = 0  # dictionary['UNK']
          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)
    
    # Hint to reduce memory.
    del words
    
    # 输出最高频的5个词,打印data中的前10个索引值
    print('Most common words (+UNK)', count[:5])
    print('Sample data', data[:10])
    
    data_index = 0
    
    '''
        为skip-gram模型生成一个batch的训练样本集合
        输入:batch_size, batch大小
              num_skips, 每个窗口产生多少样本
              skip_window, 窗口大小
        输出:batch, 中心词列表
             labels, 标签列表
    '''
    def generate_batch(batch_size, num_skips, skip_window):
      global data_index
      # batch_size需是num_skips的整数倍
      assert batch_size % num_skips == 0
      
      # num_skips的上限,不能超过2倍窗口大小
      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)
      
      # 窗口左边界到右边界之间的长度
      # 样例:[skip_window target skip_window]
      # 若skip_window是1,则span是3;若skip_window是2,则span是5
      span = 2 * skip_window + 1
      
      # 建立一个容量为span的队列,当容量大于span时,若有插入操作,最老的元素出队
      # 队列容量始终保持为span
      buffer = collections.deque(maxlen=span)
      
      # 将词索引列表data中[data_index : data_index+span]范围内的词索引加入buffer
      # buffer本质就是一个滑动窗口
      # 若data为[1,4,3,5,2,5], 则当前窗口为[1,4,3], 中心词索引为4
      for _ in range(span):
        buffer.append(data[data_index])
        data_index = (data_index + 1) % len(data)
        
      # 对batch_size / num_skips个窗口进行样本采集
      # 注:一个样本由一个中心词以及该中心词的标签(即中心词要预测的词)构成,例如
      #     在句子I like to eat apple中,(eat, apple)为生成的样本,eat为中心词,apple为该中心词     对应的标签
      # 注:中心词总是对应当前窗口的中心位置
      for i in range(batch_size // num_skips):
        target = skip_window  # target label at the center of the buffer
        targets_to_avoid = [ skip_window ]
        
        # 在第i个窗口中采集num_skips个样本
        for j in range(num_skips):
        
          # 在[0,span)区间(该区间的大小对应窗口的大小)进行随机无放回采样,
          # 直至发现不在targets_to_avoid的值为止,
          # 搜索到的target下次将不再采样.
          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]
          
        # 窗口右移一个位置,假设data为[1,4,3,5,2,5]
        # 若当前窗口为[1,4,3], 则更新后的窗口为[4,3,5], 中心词的索引为3
        buffer.append(data[data_index])
        data_index = (data_index + 1) % len(data)
    
      return batch, labels
    
    # 生成batch, 并采样打印
    batch, labels = generate_batch(batch_size=8, num_skips=2, skip_window=1)
    for i in range(8):
      print(batch[i], '->', labels[i, 0])
      print(reverse_dictionary[batch[i]], '->', reverse_dictionary[labels[i, 0]])

     

  •  定义词向量训练过程

       其中,关于NCE损失的介绍不在本文范围内,代码注释中给出了一个比较不错的说明文档,可供参考。
     
    batch_size = 128      # batch大小
    embedding_size = 128  # 嵌入层大小
    skip_window = 1       # 窗口大小
    
    # 如果窗口大小为2,则某个词附近一共有4个词可取到,最多可以组成4个训练样本,
    # 但如果你只需要2个样本的话则可通过num_skip来设置
    # 如:I like to eat apple, skip_window = 1, num_skips = 2, 则
    # 生成的样本是 (like, I), (like, to), (to, like), (to, eat), (eat, to), (eat, apple)
    num_skips = 2
    
    # 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.
    # 验证集构造,仅从词频最高的100个词中随机选择16个
    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
    
    
    # Step 4: 构建并训练skip-gram模型.
    
    # 实例化一个用于tensorflow计算和表示用的数据流图
    graph = tf.Graph()
    
    # 定义属于计算图graph的张量和操作
    with graph.as_default():
    
      # 中心词,标签,验证集
      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.
        # 生成维度为[vocabulary_size, embedding_size], 且范围为[-1,1]的均匀分布随机浮点嵌入张量
        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.
      # 定义nce平均损失值计算
      # 关于nce损失可参见:https://blog.csdn.net/qq_36092251/article/details/79684721
      loss = tf.reduce_mean(
          tf.nn.nce_loss(nce_weights, nce_biases, embed, train_labels,
                         num_sampled, vocabulary_size))
    
      # Construct the SGD optimizer using a learning rate o
      # 定义随机梯度下降优化器最小化loss,初始学习率为1.0
      optimizer = tf.train.GradientDescentOptimizer(1.0).minimize(loss)
    
      # Compute the cosine similarity between minibatch examples and all embeddings.
      # 计算余弦相似度
      
      # 对embeddings中的每个值规范化
      norm = tf.sqrt(tf.reduce_sum(tf.square(embeddings), 1, keep_dims=True))
      normalized_embeddings = embeddings / norm
      
      # 根据normalized_embeddings查询valid_dataset中每个词的词嵌入
      valid_embeddings = tf.nn.embedding_lookup(
          normalized_embeddings, valid_dataset)
          
      # 计算相似度矩阵,首先要对normalized_embeddings进行矩阵转置
      # 其中,valid_embeddings维度为16 * 128, normalized_embeddings维度为50000 * 128
      # 这一步的输出维度是16 * 50000,每行表示某个词与词表中每个词的相似度
      similarity = tf.matmul(
          valid_embeddings, normalized_embeddings, transpose_b=True)

     

  •  词向量训练
     
    # 训练轮数
    num_steps = 100001
    
    with tf.Session(graph=graph) as session:
      # 训练之前,初始化所有需要用到的变量
      tf.initialize_all_variables().run()
      print("Initialized")
    
      average_loss = 0
      for step in xrange(num_steps):
      
        # 生成一个batch数据
        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
    
        # 每隔2000轮打印一次目前的平均损失
        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)
        # 当训练完10000轮时,输出与验证集valid_examples中每个词最相近的8个词
        # 因为这一步特别耗时,所以整个训练过程仅进行了10次
        if step % 10000 == 0:
          sim = similarity.eval()
          for i in xrange(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_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_embeddings = normalized_embeddings.eval()

     

  •  可视化词嵌入
# 可视化词嵌入
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:
  from sklearn.manifold import TSNE
  import matplotlib.pyplot as plt

  tsne = TSNE(perplexity=30, n_components=2, init='pca', n_iter=5000)
  plot_only = 500
  low_dim_embs = tsne.fit_transform(final_embeddings[:plot_only,:])
  labels = [reverse_dictionary[i] for i in xrange(plot_only)]
  plot_with_labels(low_dim_embs, labels)

except ImportError:
  print("Please install sklearn and matplotlib to visualize embeddings.")

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值