TensorFlow官方文档中文版-笔记(七)

来源:互联网 发布:qt编程入门 书籍 编辑:程序博客网 时间:2024/05/19 00:41

实现word2vec中skip_gram模型

建立图形

先定义一个嵌套参数矩阵。我们用唯一的随机值来初始化这个大矩阵。

embeddings = tf.Variable(    tf.random_uniform([vocabulary_size, embedding_size], -1.0, 1.0))

对噪声-比对的损失计算就使用一个逻辑回归模型。对此,我们需要对语料库中的每个单词定义一个权重值和偏差值。(也可称之为输出权重 与之对应的 输入嵌套值)。定义如下。

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

Skip-Gram模型有两个输入。一个是一组用整型表示的上下文单词,另一个是目标单词。给这些输入建立占位符节点,之后就可以填入数据了。

# 建立输入占位符train_inputs = tf.placeholder(tf.int32, shape=[batch_size])train_labels = tf.placeholder(tf.int32, shape=[batch_size, 1])

然后我们需要对批数据中的单词建立嵌套向量,TensorFlow提供了方便的工具函数。

embed = tf.nn.embedding_lookup(embeddings, train_inputs)

好了,现在我们有了每个单词的嵌套向量,接下来就是使用噪声-比对的训练方式来预测目标单词。

# 计算 NCE 损失函数, 每次使用负标签的样本.loss = tf.reduce_mean(  tf.nn.nce_loss(nce_weights, nce_biases, embed, train_labels,num_sampled, vocabulary_size))

我们对损失函数建立了图形节点,然后我们需要计算相应梯度和更新参数的节点,比如说在这里我们会使用随机梯度下降法,TensorFlow也已经封装好了该过程。

# 使用 SGD 控制器.optimizer = tf.train.GradientDescentOptimizer(learning_rate=1.0).minimize(loss)

训练模型

训练的过程很简单,只要在循环中使用feed_dict不断给占位符填充数据,同时调用 session.run即可。

 for step in range(num_steps):        # 先使用generate_batch生成一个batch的inputs和labels数据        batch_inputs, batch_labels = generate_batch(batch_size, num_skips, skip_window)        # 并用他们创建feed_dict        feed_dict = {train_inputs: batch_inputs, train_labels: batch_labels}        # 然后执行一次优化器运算(即一次参数更新)和损失计算        _, loss_val = session.run([optimizer, loss], feed_dict=feed_dict)

完整代码如下:

from __future__ import absolute_importfrom __future__ import divisionfrom __future__ import print_functionimport collectionsimport mathimport osimport randomfrom tempfile import gettempdirimport zipfileimport numpy as npimport urllib# from six.moves import urllib# from six.moves import xrange  # pylint: disable=redefined-builtinimport tensorflow as tf# 解压下载的压缩文件,并使用tf.compat.as_str将数据转成单词的列表。def read_data(filename):    with zipfile.ZipFile(filename) as f:        data = tf.compat.as_str(f.read(f.namelist()[0])).split()    return data# vocabulary是将文本分词后的所有单词,按照文本顺序保存vocabulary = read_data("/Users/iris/Documents/数据集/text8.zip")print('Data size', len(vocabulary))vocabulary_size = 50000# 创建vocabulary词汇表def build_dataset(words, n_words):    # 使用collections.Counter统计单词列表中单词的频数,然后使用most_common方法提取top 50000频数的单词作为vocabulary    count = [['UNK', -1]]    count.extend(collections.Counter(words).most_common(n_words - 1))  # count[['UNK', -1],[word,word频数],。。。]    # 将top 50000 词汇的vocabulary转为编号,以频数排序    dictionary = dict()    for word, _ in count:        dictionary[word] = len(dictionary)  # dictionary [word: 编号]    # 遍历单词列表,判断每个单词是否出现在dictionary中,是则转换为dictionary中按频数排序的编号,不是则转为编号0    data = list()    unk_count = 0    for word in words:        index = dictionary.get(word, 0)  # 查找word,若不存在返回默认值0        if index == 0:  # dictionary['UNK']            unk_count += 1        data.append(index)  # data (w1编号,w2编号,。。。,wn编号)    # 更新count的第一个数据    count[0][1] = unk_count    reversed_dictionary = dict(zip(dictionary.values(), dictionary.keys()))    # 最后返回转换后的编码(data)、每个单词的频数统计(count)、词汇表(dictionary)及其反转的形式(reverse_dictionary)    return data, count, dictionary, reversed_dictionarydata, count, dictionary, reverse_dictionary = build_dataset(vocabulary, vocabulary_size)# 删除原始单词列表,可以节约内存,再打印出最高频出现的词汇及其数量del vocabulary  # Hint to reduce memory.print('Most common words (+UNK)', count[:5])print('Sample data', data[:10], [reverse_dictionary[i] for i in data[:10]])data_index = 0  # 定义data_index为全局变量,因为我们会反复调用generate_batch# 生成训练用的batch数据:#  batch_size为batch的大小#  num_skips为对每个单词生成多少个样本(不能大于skip_window值的两倍,batch_size必须是它的整数倍(确保每个batch包含了一个词汇对应的所有样本))#  skip_window指单词最远可以联系的距离def generate_batch(batch_size, num_skips, skip_window):    global data_index    # 断言是声明其布尔值必须为真的判定,如果发生异常就说明表达示为假    assert batch_size % num_skips == 0    assert num_skips <= 2 * skip_window    # np.ndarray 初始化为数组,shape 生成数组形状,dtype 数据类型    batch = np.ndarray(shape=(batch_size), dtype=np.int32)    labels = np.ndarray(shape=(batch_size, 1), dtype=np.int32)    # span为对某个单词创建相关样本时会使用到的单词数量,包括目标单词本身和它前后的单词    span = 2 * skip_window + 1    # deque是double-ended queue的缩写,双端队列结构。最大容量为span,在对deque执行append方法添加变量时,只会保留最后插入的span个变量    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):  # //整数除法        context_words = [w for w in range(span) if w != skip_window]  # 输出0~span中所有数值,除了skip_window        # print(context_words)        words_to_use = random.sample(context_words, num_skips)        # print(words_to_use)        for j, context_word in enumerate(words_to_use):            batch[i * num_skips + j] = buffer[skip_window]            labels[i * num_skips + j, 0] = buffer[context_word]        if data_index == len(data):            buffer[:] = data[:span]            data_index = span        else:            buffer.append(data[data_index])            data_index += 1    data_index = (data_index + len(data) - span) % len(data)    return batch, labels# 这里调用generate_batch函数测试一下其功能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]])########################################################################################################### Step1、2 定义输入和定义算法公式batch_size = 128embedding_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.num_sampled = 64  # Number of negative examples to sample.valid_size = 16  # Random set of words to evaluate similarity on.用来抽取的验证单词数valid_window = 100  # Only pick dev samples in the head of the distribution.指验证单词只从频数最高的100个单词中抽取valid_examples = np.random.choice(valid_window, valid_size, replace=False)  # 使用np.random.choice函数进行随机抽取# 下面开始定义Skip-Gram WordVec模型的网络结构graph = tf.Graph()# 返回一个上下文管理器,使得这个Graph对象成为当前默认的graph.# with关键字让这个代码块内创建的从操作(ops)添加到这个新的图里面.# 让with下面代码块的操作都执行在这个图中,作为默认graphwith graph.as_default():    #  Input data. 创建训练数据中的inputs和labels的placeholder,placeholder给节点输入数据    #  placeholder是占位符,相当于java中的定义    train_inputs = tf.placeholder(tf.int32, shape=[batch_size])    train_labels = tf.placeholder(tf.int32, shape=[batch_size, 1])    # 将前面产生的valid_examples转为TensorFlow中的constant    valid_dataset = tf.constant(valid_examples, dtype=tf.int32)    # 限定所有计算再CPU上执行    # 以下代码块操作是初始化所有参数    with tf.device('/cpu:0'):        # 随机生成所有单词的词向量embeddings        embeddings = tf.Variable(tf.random_uniform([vocabulary_size, embedding_size], -1.0, 1.0))        # embedding_lookup(params, ids)其实就是按照ids顺序返回params中的第ids行。        # 在embeddings中查找train_inputs对应的表示,赋值给embed        embed = tf.nn.embedding_lookup(embeddings, train_inputs)        # NCE Loss作为训练的优化目标        # 使用truncated_normal初始化NCE Loss中的权重参数nce_weights        nce_weights = tf.Variable(tf.truncated_normal([vocabulary_size, embedding_size], stddev=1.0 / math.sqrt(embedding_size)))        # 将nce_biases初始化为0        nce_biases = tf.Variable(tf.zeros([vocabulary_size]))# Step3 定义损失函数    # 使用tf.nn.nce_loss计算学习出的词向量embedding在训练数据上的loss,并使用tf.reduce_mean进行汇总    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))# Step4 定义优化算法    # 定义优化器为SGD并且学习速率为1.0    optimizer = tf.train.GradientDescentOptimizer(1.0).minimize(loss)    # Compute the cosine similarity between minibatch examples and all embeddings.    # 计算embeddings的L2范数norm    norm = tf.sqrt(tf.reduce_sum(tf.square(embeddings), 1, keep_dims=True))    # embeddings除以L2范数到标准化后的normalized_embeddings    normalized_embeddings = embeddings / norm    # 查询验证单词的嵌入向量embeddings    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()  # 最后初始化所有模型参数# Step5 迭代执行训练操作num_steps = 100001with 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 range(num_steps):        # 先使用generate_batch生成一个batch的inputs和labels数据        batch_inputs, batch_labels = generate_batch(batch_size, num_skips, skip_window)        # 并用他们创建feed_dict        feed_dict = {train_inputs: batch_inputs, train_labels: batch_labels}        # 然后执行一次优化器运算(即一次参数更新)和损失计算        _, loss_val = session.run([optimizer, loss], feed_dict=feed_dict)        average_loss += loss_val  # 并将这一步训练的loss累积到average_loss        # 之后每2000次循环,计算一下平均loss并显示出来        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        # 每10000次循环,计算一次验证单词与全部单词的相似度,并将与每个验证单词最相似的8个单词展示出来        # Note that this is expensive (~20% slowdown if computed every 500 steps)        if step % 10000 == 0:            sim = similarity.eval()            for i in range(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 range(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.# pylint: disable=missing-docstring# Function to draw visualization of distance between embeddings.# 下面定义一个用来可视化Word2Vec效果的函数,low_dim_embs是降维到2维的单词的空间向量,将在图表中展示每个单词的位置def plot_with_labels(low_dim_embs, labels, filename):    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)# 实现降维,将原始的128维降到2维,再使用plot_with_labels进行展示,这里只展示词频最高的100个单词的可视化结果try:    # pylint: disable=g-import-not-at-top    from sklearn.manifold import TSNE    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 = [reverse_dictionary[i] for i in range(plot_only)]    plot_with_labels(low_dim_embs, labels, os.path.join(gettempdir(), 'tsne.png'))except ImportError as ex:    print('Please install sklearn, matplotlib, and scipy to show embeddings.')    print(ex)
原创粉丝点击