srowen commented on a change in pull request #27758: [SPARK-31007][ML] KMeans
optimization based on triangle-inequality
URL: https://github.com/apache/spark/pull/27758#discussion_r387140942
##########
File path:
mllib/src/main/scala/org/apache/spark/mllib/clustering/DistanceMeasure.scala
##########
@@ -234,6 +342,39 @@ private[spark] object EuclideanDistanceMeasure {
}
private[spark] class CosineDistanceMeasure extends DistanceMeasure {
+
+ /**
+ * @return Radii of centers. If distance between point x and center c is
less than
+ * the radius of center c, then center c is the closest center to
point x.
+ * For Cosine distance, it is similar to Euclidean distance.
However, here
+ * radian/angle is used instead of Cosine distance: for center c,
finding
+ * its closest center, computing the radian/angle between them,
halving the
+ * radian/angle, and converting it back to Cosine distance at the
end.
+ */
+ override def computeRadii(centers: Array[VectorWithNorm]): Array[Double] = {
+ val k = centers.length
+ if (k == 1) {
+ Array(Double.NaN)
+ } else {
+ val distances = Array.fill(k)(Double.PositiveInfinity)
+ var i = 0
+ while (i < k) {
+ var j = i + 1
+ while (j < k) {
+ val d = distance(centers(i), centers(j))
+ if (d < distances(i)) distances(i) = d
+ if (d < distances(j)) distances(j) = d
+ j += 1
+ }
+ i += 1
+ }
+
+ // d = 1 - cos(x)
+ // r = 1 - cos(x/2) = 1 - sqrt((cos(x) + 1) / 2) = 1 - sqrt(1 - d/2)
+ distances.map(d => 1 - math.sqrt(1 - d / 2))
Review comment:
OK, the last expression comes from the cos(2x) identity, OK.
----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
For queries about this service, please contact Infrastructure at:
[email protected]
With regards,
Apache Git Services
---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]