zhengruifeng commented on a change in pull request #28206: [SPARK-31436][ML]
MinHash keyDistance optimization
URL: https://github.com/apache/spark/pull/28206#discussion_r407836213
##########
File path: mllib/src/main/scala/org/apache/spark/ml/feature/MinHashLSH.scala
##########
@@ -70,19 +70,46 @@ 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
- assert(unionSize > 0, "The union of two input sets must have at least 1
elements")
- 1 - intersectionSize / unionSize
+ val xIter = x.nonZeroIterator.map(_._1)
+ val yIter = y.nonZeroIterator.map(_._1)
+ if (xIter.isEmpty) {
+ require(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 == 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
+ }
+ }
+
+ xSize += xIter.size
+ ySize += yIter.size
+
+ val unionSize = xSize + ySize - intersectionSize
+ require(unionSize > 0, "The union of two input sets must have at least 1
elements")
+ 1 - intersectionSize.toDouble / unionSize
}
@Since("2.1.0")
Review comment:
ditto
----------------------------------------------------------------
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]