tensorflow word2vec_basic 输入输出占位符

tensoflow word2vec_basic input-output placeholders

我是张量流的新手。我正在尝试理解 word2vec_basic 脚本。

一开始定义了输入输出。

train_inputs = tf.placeholder(tf.int32, shape=[batch_size])
train_labels = tf.placeholder(tf.int32, shape=[batch_size, 1])

如果我理解正确的话 train_inputs - [batch_size] 的形状是一个整数数组,数组的长度是 batch_size。那么train_labels的形状就是[batch_size, 1],也就是单行的矩阵。正确的?如果是,我不明白为什么会这样,以及那些占位符中应该存储什么。按照理论,label是一个int,input是context滑动window的数组,为什么会出现batch_size呢?

看来我错过了理论中的一些基本知识。我将不胜感激。

为了训练,并行计算多个句子很方便。这就是 batch_size 的目的。批次中的每个单词都来自数据中的不同部分,并且 train_labels 具有相应的标签。梯度在整个批次中聚合,然后完成单个参数更新。

最近刚好在调试word2vec_basic.py,举个简单的数据集例子"the dog saw a cat the dog chased the cat the cat climbed a tree",dictionary就是{'the': 0, 'cat': 1, 'dog': 2, 'a': 3, 'saw': 4, 'chased': 5, 'climbed': 6, 'tree': 7}reverse_dictionary就是[=14] =].

当batch_size=8、skip_window=1、embedding_size=1、num_skips=2时,调用generate_batchreturns : batch: [2 2 4 4 3 3 1 1] labels: [[0] [4] [2] [3] [4] [1] [0] [3]]

翻译成文字,它们是: batch: [dog, dog, saw, saw, a, a, cat, cat] labels: [[the], [saw], [dog], [a], [saw], [cat], [the], [a]]

对于数据集中的前三个单词"the dog saw",由于skip_window为1,预期的(target, context)对应该是(dog, the)和(dog, saw) - 如果需要,请参阅 https://www.tensorflow.org/tutorials/word2vec 中的 "The Skip-gram Model" 了解更多详细信息。

至于为什么在 [batch_size, 1] 中使用 1,https://www.tensorflow.org/api_docs/python/tf/nn/nce_lossnce_loss 文档说 "labels: A Tensor of type int64 and shape [batch_size, num_true]. The target classes." 和 "num_true: An int. The number of target classes per training example."(num_true默认值为 1)

而代码中的nce_loss定义为:

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

所以现在应该很容易看出 train_inputstrain_labels 的形状是有意义的。