Tensorflow实现word2vec

大名鼎鼎的word2vec,相关原理就不讲了,已经有很多篇优秀的博客分析这个了. 如果要看背后的数学原理的话,可以看看这个: https://wenku.baidu.com/view/042a0019767f5acfa1c7cd96.html 一个话总结下word2vec就是使用一个一层的神经网络去学习分布式词向量的方式,相关链接: [Google原版word2vec主页] https://code.google.com/archive/p/word2vec/ (需翻墙) [gensim中的word2vec] https://radimrehurek.com/gensim/models/word2vec.html

这篇来自于黄文坚的”Tensorflow实战”一书,我重新组织了下,如有侵权,联系我删除!

数据集

数据集使用的是text8 corpus, 详细地址: http://mattmahoney.net/dc/textdata,官方介绍:

数据集的下载地址是: http://mattmahoney.net/dc/text8.zip

知道地址了,直接下载就可以了,直接wget或者urlretrieve都可以,约31MB

'''Step1: download dataset'''
url = 'http://mattmahoney.net/dc/'

def may_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)
    return filename

filename = may_download('text8.zip', 31344016)

简单明了,下载然后校验下载的文件大小

读取数据

下载下来的是zip file,里面包含一个名为”text8”的二进制文件,可以直接使用zipfile进行文件的读取,然后使用tf自带的as_str_any方法将其还原成字符串表示

代码如下:

'''Step2: read dataset'''
def read_data(filename):
    with zipfile.ZipFile(filename) as f:
        data = tf.compat.as_str_any(f.read(f.namelist()[0])).split()
    return data

words = read_data(filename)
print('Datas size', len(words))

words中包含17005207个word

然而我们需要的不止是包含单词的列表,还需要将其编号 我们选择词频前5000个单词作为单词列表,其它的不在列表里面的作为unknown

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
            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

data是单词的index,dictionary是正向的word–>index的字典,reverse_dictionary是反向的index–>word的字典.

生成batch数据

使用Skip-Gram,生成batch generator: 假设现在有一句”in addition to the function below”,就是将其变为(addition, in),(addition, to),(to, addition),(to, the),(the, to),(the, function)等,假设现在我们只能相邻的两个单词生成样本,也就是说每次是3个单词来生成样本对,假设是”addition to the”,我们需要生成”(to, addition)、(to the)”样本对,将其转换为单词的index,那么可能是(3, 55)、(3, 89)这样;然后向后滑动,此时3个单词变成”to the function”,然后重复上面的步骤

'''Step3: batch generator'''
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
    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 //单词之间联系的距离
        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

训练

随机生成所有单词的词向量,因为有负样本的存在,所以最终其实是变为一个分类问题,loss使用NCE(noise-contrastive estimation) loss. TF中对于word2vec,有两种loss: 1. sampled softmax 2. NCE

当然这两种也可用于任意的分类问题. 那么为什么不直接上softmax呢? 主要是对于word2vec来说,需要分类的类别太多,sampled softmax和NCE都是一种简化版的softmax.

  • The basic idea is to convert a multinomial classification problem (as it is the problem of predicting the next word) to a binary classification problem. That is, instead of using softmax to estimate a true probability distribution of the output word, a binary logistic regression (binary classification) is used instead.
  • For each training sample, the enhanced (optimized) classifier is fed a true pair (a center word and another word that appears in its context) and a number of kk randomly corrupted pairs (consisting of the center word and a randomly chosen word from the vocabulary). By learning to distinguish the true pairs from corrupted ones, the classifier will ultimately learn the word vectors.
  • This is important: instead of predicting the next word (the “standard” training technique), the optimized classifier simply predicts whether a pair of words is good or bad.

可以看看下面的两个资料: [通俗的解释NCE loss] https://www.zhihu.com/question/50043438/answer/254300443 [understand NCE in word2vec] https://stats.stackexchange.com/questions/244616/how-sampling-works-in-word2vec-can-someone-please-make-me-understand-nce-and-ne/245452#245452

'''Step 4: training'''
batch_size = 128
embedding_size = 128
skip_window = 128
num_skips = 2
valid_size = 16
valid_window = 100 //进行validation的单词数量
valid_examples = np.random.choice(valid_window, valid_size, replace=False)
num_sampled = 64 //负样本的单词数量

graph = tf.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)

    with tf.device('/cpu:0'):
        embeddings = tf.Variable(tf.random_uniform([vocabulary_size, embedding_size], -1.0, 1.0)) //随机生成词向量
        embed = tf.nn.embedding_lookup(embeddings, train_inputs)
        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]))

        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)) //使用NCE loss
        optimizer = tf.train.GradientDescentOptimizer(0.1).minimize(loss)

        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)
        init = tf.global_variables_initializer()

        num_steps = 1000000
        with tf.Session(graph=graph) as session:
            init.run()
            print('Initialized')

            average_loss = 0
            for step in range(num_steps+1):
                batch_inputs, batch_labels = generate_batch(batch_size, num_skips, skip_window)
                feed_dict = {train_inputs: batch_inputs, train_labels: batch_labels}
                _, loss_val = session.run([optimizer, loss], feed_dict=feed_dict)
                average_loss += loss_val

                if step % 2000 == 0:
                    if  step > 0:
                        average_loss /= 2000
                    print('Average loss at step %d : %.4f' % (step, average_loss))
                    average_loss = 0

                if step % 10000 == 0:
                    sim = similarity.eval()
                    for i in range(valid_size):
                        valid_word = reverse_dictionary[valid_examples[i]]
                        top_k = 5
                        nearst = (-sim[i, :]).argsort()[1:top_k+1]
                        log_str = 'Nearst to %s:' % valid_word
                        for k in range(top_k):
                            close_word = reverse_dictionary[nearst[k]]
                            log_str = '%s %s,' % (log_str, close_word)
                        print(log_str)
                    final_embeddings = normalized_embeddings.eval()

这里原书设置的是learning rate=1.0, steps=100000,跑这个例子发现就会发现loss的值在波动,出现过拟合,所以我把迭代次数增加,lr降低为0.1

我的结果:

我的结果跟原作者的不一样,loss降不到作者那么低,可能再跑几个step loss还会降低点,谁知道原因的请告诉我!

可视化

先把单词的维度降成2维,然后画个散点图,理论上来说相同词性的词之间距离比较近.

'''Step 5: visualization'''
from sklearn.manifold import TSNE
import  matplotlib.pyplot as plt
def plot_with_label(low_dim_embs, labels, filename='tsne.png'):
    assert low_dim_embs.shape[0] >= len(labels), 'More labels than embeddings'
    plt.figure(figsize=(18,18))
    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 = 3000
low_dim_embs = tsne.fit_transform(final_embeddings[:plot_only, :])
labels = [reverse_dictionary[i] for i in range(plot_only)]
plot_with_label(low_dim_embs, labels)

结果:

代码我也传上来吧,跟原书几乎一致,有需要的可以下载, http://download.csdn.net/download/gavin__zhou/10149281

本文参与腾讯云自媒体分享计划,欢迎正在阅读的你也加入,一起分享。

发表于

我来说两句

0 条评论
登录 后参与评论

相关文章

来自专栏智能算法

十张GIFs让你弄懂递归等概念

链接:http://codingpy.com/article/10-gifs-to-understand-some-programming-concepts/(...

3529
来自专栏应兆康的专栏

100个Numpy练习【2】

翻译:YingJoy 网址: https://www.yingjoy.cn/ 来源: https://github.com/rougier/numpy-100...

40810
来自专栏杨建荣的学习笔记

Python之Numpy初识

今天翻了下计划,要学习Numpy了,所以得调动脑细胞的积极性,看看能有什么收获。 首先得了解下什么是Numpy,从我的印象中,一般提到这个工具都会和机器学习关...

33111
来自专栏北京马哥教育

详解 Python qrcode 二维码模块

1、version:控制二维码的大小,取值范围从1到40。取最小值1时,二维码大小为21*21。取值为 None (默认)或者使用fit=true参数(默认)时...

990
来自专栏我有一个梦想

Python 项目实践二(下载数据)第三篇

接着上节继续学习,在本章中,你将从网上下载数据,并对这些数据进行可视化。网上的数据多得难以置信,且大多未经过仔细检查。如果能够对这些数据进行分析,你就能发现别人...

2075
来自专栏佳爷的后花媛

复习C艹(更新中)

之前在win7中运行c/c++下个vc就可以编译运行了,现在换了Mac,上网一看需要下个xcode,哎哟,好大啊,当时又没网,捉急,咦,mac的终端可以编译cp...

814
来自专栏应兆康的专栏

100个Numpy练习【2】

Numpy是Python做数据分析必须掌握的基础库之一,非常适合刚学习完Numpy基础的同学,完成以下习题可以帮助你更好的掌握这个基础库。

3599
来自专栏AndroidTv

【Android】TextView的文字长度测量及各种padding解析

老规矩,先上张图 o,这篇好像是分析篇,没有效果图。不管了,位置占着,老规矩不能坏,下面开始正文。

3547
来自专栏C语言及其他语言

[每日一题]C语言程序设计教程(第三版)课后习题4.9

题目描述 输入一个华氏温度,要求输出摄氏温度。公式为 c=5(F-32)/9 输出要求有文字说明,取位2小数。 输入 一个华氏温度,浮点数 输出 摄氏温度,浮点...

2596
来自专栏CDA数据分析师

Excel中6个怪异的公式,你知多少?

文 | 兰色幻想-赵志东 在excel中我们有时会看到一些奇奇怪怪的公式,为了帮助新手学习,兰色今天带大家一起盘点这些公式。 公式1:=Sum(表1:表20!A...

1815

扫码关注云+社区