【问题标题】:Tensorflow implementation of word2vecword2vec的Tensorflow实现
【发布时间】:2016-11-01 20:12:46
【问题描述】:

Tensorflow 教程here 指的是它们的基本实现,您可以在 github here 上找到,Tensorflow 作者使用 Skipgram 模型实现 word2vec 向量嵌入训练/评估。

我的问题是关于 generate_batch() 函数中(目标,上下文)对的实际生成。

this lineTensorflow 作者从单词滑动窗口中的“中心”单词索引中随机抽取附近的目标索引。

但是,他们also keep a data structure targets_to_avoid 首先添加了“中心”上下文词(当然我们不想对其进行采样),但在我们添加它们之后还添加了其他词。

我的问题如下:

  1. 为什么要从这个围绕单词的滑动窗口进行采样,为什么不直接使用循环并使用它们而不是采样呢?他们担心word2vec_basic.py(他们的“基本”实现)中的性能/内存似乎很奇怪。
  2. 无论 1) 的答案是什么,为什么他们 采样并跟踪他们使用 targets_to_avoid 选择的内容?如果他们想要真正随机,他们会使用带替换的选择,如果他们想确保获得所有选项,他们应该首先使用循环并获得所有选项!
  3. 内置的tf.models.embedding.gen_word2vec 也可以这样工作吗?如果是这样,我在哪里可以找到源代码? (在 Github 存储库中找不到 .py 文件)

谢谢!

【问题讨论】:

  • 你找到答案了吗?如果是这样,您可以添加作为答案吗?

标签: python tensorflow word2vec


【解决方案1】:

有一个名为num_skips的参数表示从单个窗口生成的(输入,输出)对的数量:[skip_window target skip_window]。所以num_skips 限制我们用作输出词的上下文词的数量。这就是 generate_batch 函数assert num_skips <= 2*skip_window 的原因。代码只是随机选取num_skip 上下文词来构建带有目标的训练对。 但我不知道num_skips 对性能有何影响。

【讨论】:

    【解决方案2】:

    我尝试了您建议的生成批次的方法 - 有一个循环并使用整个跳过窗口。结果是:

    1.更快地生成批次

    批量大小为 128,跳过窗口为 5

    • 通过逐个循环数据来生成批次需要 0.73s 每 10,000 个批次
    • 使用教程代码和num_skips=2 生成批次需要 3.59s 每 10,000 个批次

    2。过拟合的风险更高

    保持教程代码的其余部分不变,我用两种方法训练模型并记录每 2000 步的平均损失:

    这种模式反复出现。它表明每个单词使用 10 个样本而不是 2 个可能会导致过拟合。

    这是我用于生成批次的代码。它取代了教程的generate_batch 函数。

    data_index = 0
    
    def generate_batch(batch_size, skip_window):
        global data_index
        batch = np.ndarray(shape=(batch_size), dtype=np.int32)  # Row
        labels = np.ndarray(shape=(batch_size, 1), dtype=np.int32)  # Column
    
        # For each word in the data, add the context to the batch and the word to the labels
        batch_index = 0
        while batch_index < batch_size:
            context = data[get_context_indices(data_index, skip_window)]
    
            # Add the context to the remaining batch space
            remaining_space = min(batch_size - batch_index, len(context))
            batch[batch_index:batch_index + remaining_space] = context[0:remaining_space]
            labels[batch_index:batch_index + remaining_space] = data[data_index]
    
            # Update the data_index and the batch_index
            batch_index += remaining_space
            data_index = (data_index + 1) % len(data)
    
        return batch, labels
    

    编辑:get_context_indices 是一个简单的函数,它在 data_index 周围的 skip_window 中返回索引切片。请参阅slice() documentation 了解更多信息。

    【讨论】:

    • get_context_indices 中有什么
    • 这不能回答问题。
    • @ToussaintLouverture 它确实回答了第 1 个问题。:) 你指的是哪个问题?
    猜你喜欢
    • 2018-12-04
    • 2017-03-07
    • 1970-01-01
    • 2020-03-05
    • 1970-01-01
    • 1970-01-01
    • 2016-09-02
    • 2015-10-04
    • 2016-05-13
    相关资源
    最近更新 更多