srowen commented on a change in pull request #27758: [SPARK-31007][ML][WIP]
KMeans optimization based on triangle-inequality
URL: https://github.com/apache/spark/pull/27758#discussion_r408157550
##########
File path:
mllib/src/main/scala/org/apache/spark/mllib/clustering/DistanceMeasure.scala
##########
@@ -17,23 +17,124 @@
package org.apache.spark.mllib.clustering
+import org.apache.spark.SparkContext
import org.apache.spark.annotation.Since
+import org.apache.spark.broadcast.Broadcast
import org.apache.spark.mllib.linalg.{Vector, Vectors}
import org.apache.spark.mllib.linalg.BLAS.{axpy, dot, scal}
import org.apache.spark.mllib.util.MLUtils
private[spark] abstract class DistanceMeasure extends Serializable {
+ /**
+ * Statistics used in triangle inequality to obtain useful bounds to find
closest centers.
+ * @param distance distance between two centers
+ */
+ def computeStatistics(distance: Double): Double
+
+ /**
+ * Statistics used in triangle inequality to obtain useful bounds to find
closest centers.
+ *
+ * @return A symmetric matrix containing statistics, matrix(i)(j) represents:
+ * 1, a lower bound r of the center i, if i==j. If distance between
point x and center i
+ * is less than f(r), then center i is the closest center to point x.
+ * 2, a lower bound r=matrix(i)(j) to help avoiding unnecessary
distance computation.
+ * Given point x, let i be current closest center, and d be current
best distance,
+ * if d < f(r), then we no longer need to compute the distance to
center j.
+ */
+ def computeStatistics(centers: Array[VectorWithNorm]): Array[Array[Double]]
= {
+ val k = centers.length
+ if (k == 1) return Array(Array(Double.NaN))
+
+ val stats = Array.ofDim[Double](k, k)
+ var i = 0
+ while (i < k) {
+ stats(i)(i) = Double.PositiveInfinity
+ i += 1
+ }
+ i = 0
+ while (i < k) {
+ var j = i + 1
+ while (j < k) {
+ val d = distance(centers(i), centers(j))
+ val s = computeStatistics(d)
+ stats(i)(j) = s
Review comment:
If you're micro-optimizing, I suppose you can lift stats(i) out of the loop,
but it may not o anything
----------------------------------------------------------------
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]