使用tensorflow实现word2vec中文词向量的训练

使用tensorflow实现word2vec中文词向量的训练

一、word2vec简要介绍

word2vec 是 Google 于 2013 年开源推出的一个用于获取 word vector 的工具包,它简单、高效,因此引起了很多人的关注。对word2vec数学原理感兴趣的可以移步word2vec 中的数学原理详解,这里就不具体介绍。word2vec对词向量的训练有两种方式,一种是CBOW模型,即通过上下文来预测中心词;另一种skip-Gram模型,即通过中心词来预测上下文。其中CBOW对小型数据比较适合,而skip-Gram模型在大型的训练语料中表现更好。两种模型结构如下:


二、使用word2vec对中文训练词向量

word2vec的源码github上可以找到点这里,这里面已经实现了对英文的训练。不过要想运行的话的要小小改动一个地方,修改后如下:

loss = tf.reduce_mean(tf.nn.nce_loss(weights=nce_weights,
                                         biases=nce_biases, 
                                         inputs=embed, 
                                         labels=train_labels,
                                         num_sampled=num_sampled, 
                                         num_classes=vocabulary_size))

对英文的训练就不再介绍,这里主要讲如何对中文进行词向量的训练(采用skip-Gram模型)。相对于英文来说稍微繁琐一点,不过对中文的训练的代码和英文训练的代码大多数都一样,只要改动前面一部分关于获取词列表的代码即可。对中文的训练步骤有:

  1. 对文本进行分词,采用的jieba分词
  2. 将语料中的所有词组成一个列表,为构建词频统计,词典及反转词典。因为计算机不能理解中文,我们必须把文字转换成数值来替代。
  3. 构建skip-Gram模型需要的训练数据:由于这里采用的是skip-Gram模型进行训练,即通过中心词预测上下文。因此中心词相当于x,上下文的词相当于y。这里我们设置上下文各为一个词,假设我要对“恐怕 顶多 只 需要 三年 时间”这段话生成样本,我们应该通过“顶多”预测“恐怕”和“只”;通过“只”预测“顶多”和“需要”依次下去即可。最终的训练样本应该为(顶多,恐怕),(顶多,只),(只,顶多),(只,需要),(需要,只),(需要,三年)。
#!usr/bin/env python
# -*- coding:utf-8 -*-
"""
Created on Sat Sep  1 21:39:20 2017
@author: Deermini
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

import collections
import math
import random
import jieba
import numpy as np
from six.moves import xrange
import tensorflow as tf

# Step 1: Download the data.
# Read the data into a list of strings.
def read_data():
    """
    对要训练的文本进行处理,最后把文本的内容的所有词放在一个列表中
    """
    #读取停用词
    stop_words = []
    with open('stop_words.txt',"r",encoding="UTF-8") as f:
        line = f.readline()
        while line:
            stop_words.append(line[:-1])
            line = f.readline()
    stop_words = set(stop_words)
    print('停用词读取完毕,共{n}个词'.format(n=len(stop_words)))

    # 读取文本,预处理,分词,得到词典
    raw_word_list = []
    with open('doupocangqiong.txt',"r", encoding='UTF-8') as f:
        line = f.readline()
        while line:
            while '\n' in line:
                line = line.replace('\n','')
            while ' ' in line:
                line = line.replace(' ','')
            if len(line)>0: # 如果句子非空
                raw_words = list(jieba.cut(line,cut_all=False))
                raw_word_list.extend(raw_words)
            line=f.readline()
    return raw_word_list

#step 1:读取文件中的内容组成一个列表
words = read_data()
print('Data size', len(words))

# Step 2: Build the dictionary and replace rare words with UNK token.
vocabulary_size = 50000
def build_dataset(words):
    count = [['UNK', -1]]
    count.extend(collections.Counter(words).most_common(vocabulary_size - 1))
    print("count",len(count))
    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
    reverse_dictionary = dict(zip(dictionary.values(), dictionary.keys()))
    return data, count, dictionary, reverse_dictionary

data, count, dictionary, reverse_dictionary = build_dataset(words)

del words  #删除words节省内存
print('Most common words (+UNK)', count[:5])
print('Sample data', data[:10], [reverse_dictionary[i] for i in data[:10]])

data_index = 0
# 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)
    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

batch, labels = generate_batch(batch_size=8, num_skips=2, skip_window=1)
for i in range(8):
    print(batch[i], reverse_dictionary[batch[i]],'->', labels[i, 0], reverse_dictionary[labels[i, 0]])

# Step 4: Build and train a skip-gram model.
batch_size = 128
embedding_size = 128  
skip_window = 1       
num_skips = 2         
valid_size = 9      #切记这个数字要和len(valid_word)对应,要不然会报错哦   
valid_window = 100  
num_sampled = 64    # Number of negative examples to sample.
#验证集
valid_word = ['萧炎','灵魂','火焰','萧薰儿','药老','天阶',"云岚宗","乌坦城","惊诧"]
valid_examples =[dictionary[li] for li in valid_word]
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]),dtype=tf.float32)

    # 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, inputs=embed, labels=train_labels,
                 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()

# Step 5: Begin training.
num_steps = 2000000
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 = reverse_dictionary[valid_examples[i]]
                top_k = 8  # number of nearest neighbors
                nearest = (-sim[i, :]).argsort()[:top_k]
                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()

# Step 6: Visualize the embeddings.
def plot_with_labels(low_dim_embs, labels, filename='tsne.png',fonts=None):
    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,
                    fontproperties=fonts,
                    xy=(x, y),
                    xytext=(5, 2),
                    textcoords='offset points',
                    ha='right',
                    va='bottom')
    plt.savefig(filename,dpi=600)
try:
    from sklearn.manifold import TSNE
    import matplotlib.pyplot as plt
    from matplotlib.font_manager import FontProperties
    
    #为了在图片上能显示出中文
    font = FontProperties(fname=r"c:\windows\fonts\simsun.ttc", size=14)
    
    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,fonts=font)
    
except ImportError:
    print("Please install sklearn, matplotlib, and scipy to visualize embeddings.")

经过大约三小时的训练后,使用s-TNE把词向量降至2维进行可视化,部分词可视化结果如下:

随机对几个词进行验证,得到的结果为:

Nearest to 萧炎: 萧炎, 他, 韩枫, 林焱, 古元, 萧厉, 她, 叶重,
Nearest to 灵魂: 灵魂, 斗气, 触手可及, 乌钢, 探头探脑, 能量, 庄严, 晋阶,
Nearest to 火焰: 火焰, 异火, 能量, 黑雾, 火苗, 砸场, 雷云, 火海,
Nearest to 天阶: 天阶, 地阶, 七品, 相媲美, 斗帝, 碧蛇, 稍有不慎, 玄阶,
Nearest to 云岚宗: 云岚宗, 炎盟, 魔炎谷, 磐门, 丹塔, 萧家, 叶家, 花宗,
Nearest to 乌坦城: 乌坦城, 加玛, 大殿, 丹域, 兽域, 大厅, 帝国, 内院,
Nearest to 惊诧: 惊诧, 惊愕, 诧异, 震惊, 惊骇, 惊叹, 错愕, 好笑,

这里只是随便挑选的几个词进行验证,看起来效果还不错的样子,大家可以自己讨点有意思的词进行验证一下效果哦。

完整程序及数据见我的github,接下来我准备用把这篇小说做成词云进行展示,让大家更直观的了解这本小说大概在讲什么(正在更新中。。。。。。。。)。词云制作可以参考如何用Python做中文词云

以上只是个人最近所学,有错误的地方还请指正,谢谢。

上面只是针对tensorflow实现word2vec,另外还有一个非常好的gensim库对word2vec已封装好,用起来非常的得心应手。gensim的word2vec也已经有人写好,具体参考利用gensim库训练word2vec中文模型

三、参考资料

  1. 使用Tensorflow实现word2vec模型
  2. Tensorflow机器学习--图文理解Word2Vec
  3. tensorflow实现中文词向量训练
  4. tensorflow实战 (黄文坚、唐源 著)
  5. word2vec 中的数学原理详解
  6. 如何用Python做中文词云
编辑于 2018-02-05