srowen commented on a change in pull request #28206: [SPARK-31436][ML] MinHash
keyDistance optimization
URL: https://github.com/apache/spark/pull/28206#discussion_r407510019
##########
File path: mllib/src/main/scala/org/apache/spark/ml/feature/MinHashLSH.scala
##########
@@ -70,19 +70,51 @@ class MinHashLSHModel private[ml](
@Since("2.1.0")
override protected[ml] def keyDistance(x: Vector, y: Vector): Double = {
- val xSet = x.nonZeroIterator.map(_._1).toSet
- val ySet = y.nonZeroIterator.map(_._1).toSet
- val intersectionSize = xSet.intersect(ySet).size.toDouble
- val unionSize = xSet.size + ySet.size - intersectionSize
+ val xIter = x.nonZeroIterator.map(_._1)
+ val yIter = y.nonZeroIterator.map(_._1)
+ if (xIter.isEmpty) {
+ assert(yIter.hasNext, "The union of two input sets must have at least 1
elements")
+ return 1.0
+ } else if (yIter.isEmpty) {
+ return 1.0
+ }
+
+ var xIndex = xIter.next
+ var yIndex = yIter.next
+ var xSize = 1
+ var ySize = 1
+ var intersectionSize = 0
+
+ while (xIndex != -1 || yIndex != -1) {
+ if (xIndex != -1 && yIndex != -1) {
+ if (xIndex == yIndex) {
+ intersectionSize += 1
+ xIndex = if (xIter.hasNext) { xSize += 1; xIter.next } else -1
+ yIndex = if (yIter.hasNext) { ySize += 1; yIter.next } else -1
+ } else if (xIndex > yIndex) {
+ yIndex = if (yIter.hasNext) { ySize += 1; yIter.next } else -1
+ } else {
+ xIndex = if (xIter.hasNext) { xSize += 1; xIter.next } else -1
+ }
+ } else if (xIndex != -1) {
+ while (xIter.hasNext) { xIndex = xIter.next; xSize += 1 }
Review comment:
Do you need to update xIndex in this case, and yIndex below? looks like
you're just counting the remaining size of the iterator. It's possible .size()
is as fast from here.
----------------------------------------------------------------
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]