NLP中的余弦相似度 Cosine similarity 是什么,如何计算(学习心得)

余弦相似度 Cosine similarity

To measure how similar two words are, we need a way to measure the degree of similarity between two embedding vectors for the two words. Given two vectors 𝑢 and 𝑣, cosine similarity is defined as follows:

1.jpg

分子:u 和 v 的点积 dot product(或内积 inner product)
分母:向量 u 和 v 的范式 norm(或长度 length)相乘
得到的就是 u 和 v 向量夹角 θ 的余弦值,即两个向量的相似度

2.jpg
余弦值的范围是 -1~1,其中 1 对应 完全正相关,-1 对应完全负相关,0 对应完全不相关
3.jpg
其中,向量 norm 的计算公式为,向量中每个元素的平方和开根号