余弦相似度
在spark中,有2种方式实现向量的余弦相似度,废话不说,直接上代码
1. 根据公式计算
val v1 = Array(
1.0, 2.0, 3.0
)
val v2 = Array(
2.0, 2.0, 3.0
)
println(
v1.zip(v2).map(i => i._1 * i._2).sum
/
(Math.sqrt(v1.map(Math.pow(_, 2)).sum) * Math.sqrt(v2.map(Math.pow(_, 2)).sum))
)
2. 根据余弦距离
cosineDistance 方法有时候idea自动导入不了,所以需要手动引入包 :breeze.linalg.functions.cosineDistance
println(1 - cosineDistance(DenseVector(v1), DenseVector(v2)))