zhengruifeng commented on a change in pull request #26948: [SPARK-30120][ML]
LSH approxNearestNeighbors should use BoundedPriorityQueue when
numNearestNeighbors is small
URL: https://github.com/apache/spark/pull/26948#discussion_r360766075
##########
File path: mllib/src/main/scala/org/apache/spark/ml/feature/LSH.scala
##########
@@ -138,24 +138,59 @@ private[ml] abstract class LSHModel[T <: LSHModel[T]]
// Limit the use of hashDist since it's controversial
val hashDistUDF = udf((x: Seq[Vector]) => hashDistance(x, keyHash),
DataTypes.DoubleType)
val hashDistCol = hashDistUDF(col($(outputCol)))
-
- // Compute threshold to get around k elements.
- // To guarantee to have enough neighbors in one pass, we need (p - err)
* N >= M
- // so we pick quantile p = M / N + err
- // M: the number of nearest neighbors; N: the number of elements in
dataset
- val relativeError = 0.05
- val approxQuantile = numNearestNeighbors.toDouble / count + relativeError
val modelDatasetWithDist = modelDataset.withColumn(distCol, hashDistCol)
- if (approxQuantile >= 1) {
- modelDatasetWithDist
+
+ val spark = dataset.sparkSession
+ import spark.implicits._
+
+ if (numNearestNeighbors < 1000) {
+ val r = Random.nextInt
+ val distColIdx =
modelDatasetWithDist.schema.fieldNames.indexOf(distCol)
+ val rows = modelDatasetWithDist
+ .rdd
+ .map { row =>
+ val dist = row.getDouble(distColIdx)
+ (r, (dist, row))
+ }.aggregateByKey(new BoundedPriorityQueue[(Double,
Row)](numNearestNeighbors)(
+ Ordering.by[(Double, Row), Double](_._1).reverse))(
+ seqOp = (c, v) => c += v,
+ combOp = (c1, c2) => c1 ++= c2
+ ).flatMap { case (_, c) => c.iterator.map(_._2) }
+ spark.createDataFrame(rows, modelDatasetWithDist.schema)
Review comment:
The log of both methods in testsuites:
`approxQuantile/QuantileSummaries`:
numNearestNeighbors=100, modelSubset.size=231, threshold=0.0
topK
numNearestNeighbors=100, modelSubset.size=100, threshold=0.0
----------------------------------------------------------------
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]