【问题标题】:fastText embeddings sentence vectors?fastText 嵌入句子向量?
【发布时间】:2019-01-14 12:01:48
【问题描述】:

我想了解创建句子的 fastText 向量的方式。根据这个issue 309,句子的向量是通过对单词的向量进行平均得到的。

为了确认这一点,我编写了以下脚本:

import numpy as np
import fastText as ft

# Loading model for Finnish.
model = ft.load_model('cc.fi.300.bin')

# Getting word vectors for 'one' and 'two'.
one = model.get_word_vector('yksi')
two = model.get_word_vector('kaksi')

# Getting the sentence vector for the sentence "one two" in Finnish.
one_two = model.get_sentence_vector('yksi kaksi')
one_two_avg = (one + two) / 2

# Checking if the two approaches yield the same result.
is_equal = np.array_equal(one_two, one_two_avg)

# Printing the result.
print(is_equal)

# Result: FALSE

但是,似乎获得的向量并不相似。

为什么两个值不一样?它会与我平均向量的方式有关吗?或者,也许我错过了什么?

【问题讨论】:

    标签: python fasttext


    【解决方案1】:

    首先,您错过了get_sentence_vector 不仅仅是一个简单的“平均值”的部分。在 FastText 对每个词向量求和之前,每个向量除以其范数(L2 范数),然后平均过程只涉及具有正 L2 范数值的向量。

    其次,一个句子总是以 EOS 结尾。因此,如果您尝试手动计算,则需要在计算平均值之前放入 EOS。

    试试这个(我假设每个单词的 L2 范数都是正数):

    
    def l2_norm(x):
       return np.sqrt(np.sum(x**2))
    
    def div_norm(x):
       norm_value = l2_norm(x)
       if norm_value > 0:
           return x * ( 1.0 / norm_value)
       else:
           return x
    
    # Getting word vectors for 'one' and 'two'.
    one = model.get_word_vector('yksi')
    two = model.get_word_vector('kaksi')
    eos = model.get_word_vector('\n')
    
    # Getting the sentence vector for the sentence "one two" in Finnish.
    one_two = model.get_sentence_vector('yksi kaksi')
    one_two_avg = (div_norm(one) + div_norm(two) + div_norm(eos)) / 3
    

    可以看源码here也可以看讨论here。

    【讨论】:

    • 它或多或少是一个平均值,而是单位向量的平均值。
    • 请注意l2范数不能为负数:为0或正数。如果 l2 norm 为 0,除以它是没有意义的。
    • 从您的链接中,我们仅在 args_->model != model_name::sup?我想这意味着我们不会在受监督的情况下这样做。
    • @malioboro 你能解释一下为什么我们需要包含\n 的向量吗?它是否篡改了句子和/或多短语词的定义?
    【解决方案2】:

    您可能会遇到浮点数学问题 - 例如如果一个加法是在 CPU 上完成的,而另一个是在 GPU 上完成的,它们可能会有所不同。

    检查它是否在做你想要的最好的方法是确保向量几乎完全相同。

    您可能希望打印出这两个向量并手动检查它们,或者对自身进行 one_two 减去 one_two_avg 的点积(即两者之间差异的长度)。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-04-07
      • 1970-01-01
      • 1970-01-01
      • 2019-11-26
      • 2019-10-17
      • 2019-03-07
      • 1970-01-01
      相关资源
      最近更新 更多