【发布时间】:2017-03-19 00:41:21
【问题描述】:
作为熟悉 Tensorflow 的一种方式,我正在尝试验证 word2vec_basic.py(请参阅 tutorial)生成的词嵌入在检查人类相似度分数时是否有意义。然而,结果出人意料地令人失望。这就是我所做的。
在word2vec_basic.py 中,我在最后添加了另一个步骤,将嵌入和反向字典保存到磁盘(因此我不必每次都重新生成它们):
with open("embeddings", 'wb') as f:
np.save(f, final_embeddings)
with open("reverse_dictionary", 'wb') as f:
pickle.dump(reverse_dictionary, f, pickle.HIGHEST_PROTOCOL)
在我自己的 word2vec_test.py 中,我加载它们并为查找创建一个直接字典:
with open("embeddings", 'rb') as f:
embeddings = np.load(f)
with open("reverse_dictionary", 'rb') as f:
reverse_dictionary = pickle.load(f)
dictionary = dict(zip(reverse_dictionary.values(), reverse_dictionary.keys()))
然后我将相似度定义为嵌入向量之间的欧式距离:
def distance(w1, w2):
try:
return np.linalg.norm(embeddings[dictionary[w1]] - embeddings[dictionary[w2]])
except:
return None # no such word in our dictionary
到目前为止,结果是有意义的,例如 distance('before', 'after') 小于 distance('before', 'into')。
然后,我从http://alfonseca.org/pubs/ws353simrel.tar.gz 下载了人类分数(我从“模型动物园”的 Swivel 项目中借用了下面的链接和代码)。我比较人类的相似度和嵌入距离分数如下:
with open("wordsim353_sim_rel/wordsim_relatedness_goldstandard.txt", 'r') as lines:
for line in lines:
w1, w2, act = line.strip().split('\t')
pred = distance(w1, w2)
if pred is None:
continue
acts.append(float(act))
preds.append(-pred)
我使用-pred,因为人类分数随着相似度的增加而增加,所以距离排序需要倒置来匹配(距离越小,相似度越大)。
然后我计算相关系数:
rho, _ = scipy.stats.spearmanr(acts, preds)
print(str(rho))
但结果非常小,例如 0.006。我用 4 个上下文词和 256 的向量长度重新训练了 word2vec_basic,但它根本没有改善。然后我使用余弦相似度而不是欧几里得距离:
def distance(w1, w2):
return scipy.spatial.distance.cosine(embeddings[dictionary[w1]], embeddings[dictionary[w2]])
仍然没有相关性。
那么,我误解或做错了什么?
【问题讨论】:
-
作为健全性检查,计算几个知名词对之间的距离,例如
cat-dog和monday-tuesday。如果您没有小写您的输入,也请尝试Monday- Tuesday。尝试绘制预测和黄金标准的相似性:plt.scatter(acts, press) -
是的,我这样做了,结果看起来很正常。至少它们与训练时 word2vec_basic 本身报告的结果一致(它显示最接近 16 个选定单词的单词,每 10000 个时期,使用余弦相似度)。但是,请参阅下面的答案。
标签: python tensorflow nlp