Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
35 changes: 30 additions & 5 deletions mllib/src/main/scala/org/apache/spark/ml/feature/HashingTF.scala
Original file line number Diff line number Diff line change
Expand Up @@ -91,12 +91,37 @@ class HashingTF @Since("3.0.0") private[ml] (
override def transform(dataset: Dataset[_]): DataFrame = {
val outputSchema = transformSchema(dataset.schema)
val n = $(numFeatures)
val updateFunc = if ($(binary)) (v: Double) => 1.0 else (v: Double) => v + 1.0
def binaryHashUDF(hashFunc: Any => Int) = udf { terms: Seq[_] =>
val map = new OpenHashMap[Int, Int]
terms.foreach { term =>
map.update(Utils.nonNegativeMod(hashFunc(term), n), 1)
}
Vectors.sparse(n, map.iterator.map { case (index, count) =>
(index, count.toDouble)
}.toSeq)
}

def countHashUDF(hashFunc: Any => Int) = udf { terms: Seq[_] =>
val map = new OpenHashMap[Int, Int]
terms.foreach { term =>
val index = Utils.nonNegativeMod(hashFunc(term), n)
map.changeValue(index, 1, _ + 1)
}
Vectors.sparse(n, map.iterator.map { case (index, count) =>
(index, count.toDouble)
}.toSeq)
}

val hashUDF = udf { terms: Seq[_] =>
val map = new OpenHashMap[Int, Double]()
terms.foreach { term => map.changeValue(indexOf(term), 1.0, updateFunc) }
Vectors.sparse(n, map.toSeq)
val hashUDF = ($(binary), hashFuncVersion) match {
case (true, HashingTF.SPARK_2_MURMUR3_HASH) =>
binaryHashUDF(OldHashingTF.murmur3Hash)
case (false, HashingTF.SPARK_2_MURMUR3_HASH) =>
countHashUDF(OldHashingTF.murmur3Hash)
case (true, HashingTF.SPARK_3_MURMUR3_HASH) =>
binaryHashUDF(FeatureHasher.murmur3Hash)
case (false, HashingTF.SPARK_3_MURMUR3_HASH) =>
countHashUDF(FeatureHasher.murmur3Hash)
case _ => throw new IllegalArgumentException("Illegal hash function version setting.")
}

dataset.withColumn($(outputCol), hashUDF(col($(inputCol))),
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -97,6 +97,18 @@ class HashingTFSuite extends MLTest with DefaultReadWriteTest {
assert(loadedHashingTF.indexOf("c") === mLlibHashingTF.indexOf("c"))
assert(loadedHashingTF.indexOf("d") === mLlibHashingTF.indexOf("d"))

mLlibHashingTF.setBinary(loadedHashingTF.getBinary)
val terms = "a a b b c d".split(" ").toSeq
val df = Seq(Tuple1(terms)).toDF("words")
val features = loadedHashingTF
.setInputCol("words")
.setOutputCol("features")
.transform(df)
.select("features")
.first()
.getAs[Vector](0)
assert(features ~== mLlibHashingTF.transform(terms).asML absTol 1e-14)

val metadata = spark.read.json(s"$hashingTFPath/metadata")
val sparkVersionStr = metadata.select("sparkVersion").first().getString(0)
assert(sparkVersionStr === "2.4.4")
Expand Down