本文介绍了如何计算PySpark中两个向量的余弦相似度?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我将要计算PySpark中两个向量的余弦相似度,例如

I am about to compute the cosine similarity of two vectors in PySpark, like

1 - spatial.distance.cosine(xvec, yvec)

,但是scipy似乎不支持pyspark.ml.linalg.Vector类型.

but scipy seems to not support the pyspark.ml.linalg.Vector type.

推荐答案

您可以使用 dot norm 方法很容易地计算出这一点:

You can use dot and norm methods to calculate this pretty easily:

from pyspark.ml.linalg import Vectors
x = Vectors.dense([1,2,3])
y = Vectors.dense([2,3,5])

1 - x.dot(y)/(x.norm(2)*y.norm(2))
# 0.0028235350472619603


使用 scipy :

from scipy.spatial.distance import cosine
​
x = np.array([1,2,3])
y = np.array([2,3,5])

cosine(x, y)
# 0.0028235350472619603

这篇关于如何计算PySpark中两个向量的余弦相似度?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-05 16:04
查看更多