昨天我们使用了 Python 自然语言处理套件 spaCy 预训练好的 word embedding model 将英文单词转换成为高维度的向量。今天就让我们接着谈我们如何衡量单词在意义上的远近吧!
我们将单词表示成高维度的向量,根据 word embedding 的特性:两两愈是意义相近的单词,它们的向量距离就愈接近。因此我们可以纯然地从向量之间的距离大小,反推单词的语意亲疏程度。以下分别介绍用来测量向量距离常见的三种方式:
欧氏距离( Euclidean Distance ):
在中学时期我们学习过测量向量距离的方式-两向量箭头端点相连直线段的长度,这也是欧氏空间( Euclidean space )中最常被使用来距离测定的方式。在n维空间上的欧氏距离定义如下:
曼哈顿距离( Manhattan Distance ):
有别於我们最习惯的直线距离,曼哈顿距离考虑两点之间方格线长度的总和,因此又被称为方格线距离,在n维空间上的曼哈顿距离定义如下:
欧氏距离 v.s. 曼哈顿距离
word embedding 向量将语意资讯隐藏在各个维度的数值里。向量的方向有意义,而长度并不重要,因此用 cosine distance 来衡量 word embeddings 的距离再适合不过了!因着 cosine distance 可以衡量语意的相似程度,又被称为 cosine similarity 。在自然语言处理的实务上,使用cosine distance 来衡量距离有以下好处:
夹角大小和语意相似度的关系
图片来源:www.bbsmax.com
在向量长度不重要的情境中,cosine similarity 可用来衡量向量之间的距离:
Cosine similarity is generally used as a metric for measuring distance when the magnitude of the vectors does not matter. This happens for example when working with text data represented by word counts. We could assume that when a word (e.g. science) occurs more frequent in document 1 than it does in document 2, that document 1 is more related to the topic of science. However, it could also be the case that we are working with documents of uneven lengths (Wikipedia articles for example). Then, science probably occurred more in document 1 just because it was way longer than document 2. Cosine similarity corrects for this.文字来源:cmry.github.io
我们使用 spaCy 套件中预先训练好的英文 word embedding model 。我们依旧使用最轻量的模型 en_core_web_sm ,若要向量化更广泛的单词,可以考虑下载其他模型: en_core_web_md、en_core_web_lg、en_core_web_trf 。
我们先将以下三个单词 like、love、hate 表示成向量,并且比较两两之间的相似程度:
import spacy
# import cosine distance metric
from scipy.spatial.distance import cosine
nlp = spacy.load("en_core_web_sm")
# vectorise words "like", "love", "hate"
word_1 = nlp("like").vector
word_2 = nlp("love").vector
word_3 = nlp("hate").vector
# compare semantic similarities
dist_1_2 = cosine(word_1, word_2)
dist_2_3 = cosine(word_2, word_3)
dist_3_1 = cosine(word_3, word_1)
print("similarity between 'like' and 'love': ", dist_1_2)
print("similarity between 'love'and 'hate': ", dist_2_3)
print("similarity between 'hate' and 'like': ", dist_3_1)
检视一下两两单词之间的 cosine similarity:
我们发现 like 与 love 非常相似,反之 love 与 hate 几乎无相关,这与我们的认知一致。
至於 like 与 hate 的相似度高达81%,说明它们经常出现在相同上下文当中。而这与模型训练的文件选择有关,下一集我们就来训练自己的 word embedding model!
今天的介绍就到这里,为期四天的中秋连假终於结束,明天又是上班日了!不知各位会不会有收假症候群呢?废话不多说,期待与各位在下一篇文章相见,晚安!
哈罗 ~ 大家好 ~ 欢迎回来 ~ 昨天提到 Power Automate 的自动化流程以及核准流程...
这个得上一篇:https://ithelp.ithome.com.tw/articles/10258...
godog 简介 godog是Cucumber官方的Golang BDD(Behaviour-Dri...
1. Action 与 Side Effect 昨天,我们确认了状态能被储存起来,然而我们这个开门,...
欧阳克是谁杀的? 这个this是谁?要看凶手是谁而定! 前面有提到,这个e是在当事件发生时,事件处...