Skip to main content
 首页 » 编程设计

python之fastText 嵌入句向量

2024年12月31日9txw1958

我想了解创建句子的 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 

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

为什么两个值不同?这会与我对向量进行平均的方式有关吗?或者,也许我遗漏了什么?

请您参考如下方法:

首先,您错过了 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 .