-
Notifications
You must be signed in to change notification settings - Fork 29.3k
[SPARK-13969][ML] Add FeatureHasher transformer #18513
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Changes from 8 commits
6ab19a9
ebd2cbf
ba255bf
0be1e65
2f3ea21
7d678fb
6057277
9edb3bd
8c5cb30
b580a5c
990b816
a91b53f
d6a3117
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,119 @@ | ||
| /* | ||
| * Licensed to the Apache Software Foundation (ASF) under one or more | ||
| * contributor license agreements. See the NOTICE file distributed with | ||
| * this work for additional information regarding copyright ownership. | ||
| * The ASF licenses this file to You under the Apache License, Version 2.0 | ||
| * (the "License"); you may not use this file except in compliance with | ||
| * the License. You may obtain a copy of the License at | ||
| * | ||
| * http://www.apache.org/licenses/LICENSE-2.0 | ||
| * | ||
| * Unless required by applicable law or agreed to in writing, software | ||
| * distributed under the License is distributed on an "AS IS" BASIS, | ||
| * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
| * See the License for the specific language governing permissions and | ||
| * limitations under the License. | ||
| */ | ||
|
|
||
| package org.apache.spark.ml.feature | ||
|
|
||
| import org.apache.spark.annotation.Since | ||
| import org.apache.spark.ml.Transformer | ||
| import org.apache.spark.ml.attribute.AttributeGroup | ||
| import org.apache.spark.ml.linalg.Vectors | ||
| import org.apache.spark.ml.param.{IntParam, ParamMap, ParamValidators} | ||
| import org.apache.spark.ml.param.shared.{HasInputCols, HasNumFeatures, HasOutputCol} | ||
| import org.apache.spark.ml.util.{DefaultParamsReadable, DefaultParamsWritable, Identifiable, SchemaUtils} | ||
| import org.apache.spark.mllib.feature.{HashingTF => OldHashingTF} | ||
| import org.apache.spark.sql.{DataFrame, Dataset, Row} | ||
| import org.apache.spark.sql.functions._ | ||
| import org.apache.spark.sql.types._ | ||
| import org.apache.spark.util.Utils | ||
| import org.apache.spark.util.collection.OpenHashMap | ||
|
|
||
|
|
||
| @Since("2.3.0") | ||
| class FeatureHasher(@Since("2.3.0") override val uid: String) extends Transformer | ||
| with HasInputCols with HasOutputCol with HasNumFeatures with DefaultParamsWritable { | ||
|
|
||
| @Since("2.3.0") | ||
| def this() = this(Identifiable.randomUID("featureHasher")) | ||
|
|
||
| /** @group setParam */ | ||
| @Since("2.3.0") | ||
| def setNumFeatures(value: Int): this.type = set(numFeatures, value) | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. need a way to know the default value.
Contributor
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Not sure what you mean exactly |
||
|
|
||
| /** @group setParam */ | ||
| @Since("2.3.0") | ||
| def setInputCols(values: String*): this.type = setInputCols(values.toArray) | ||
|
|
||
| /** @group setParam */ | ||
| @Since("2.3.0") | ||
| def setInputCols(value: Array[String]): this.type = set(inputCols, value) | ||
|
|
||
| /** @group setParam */ | ||
| @Since("2.3.0") | ||
| def setOutputCol(value: String): this.type = set(outputCol, value) | ||
|
|
||
| override def transform(dataset: Dataset[_]): DataFrame = { | ||
| val hashFunc: Any => Int = OldHashingTF.murmur3Hash | ||
| val n = $(numFeatures) | ||
|
|
||
| val os = transformSchema(dataset.schema) | ||
|
|
||
| val featureCols = $(inputCols).map { colName => | ||
| val field = dataset.schema(colName) | ||
| field.dataType match { | ||
| case DoubleType | StringType => dataset(field.name) | ||
| case _: NumericType | BooleanType => dataset(field.name).cast(DoubleType).alias(field.name) | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Is it possible to avoid casting to Double, since one key target of Feature Hashing is reducing memory usage.
Contributor
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Fair point, have updated to handle this. |
||
| } | ||
| } | ||
|
|
||
| val realFields = os.fields.filter(f => f.dataType.isInstanceOf[NumericType]).map(_.name).toSet | ||
|
|
||
| def hashFeatures = udf { row: Row => | ||
| val map = new OpenHashMap[Int, Double]() | ||
| $(inputCols).foreach { case colName => | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. case does nothing here
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. also, I think you'll serialize the entire object here by using
Contributor
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Ah thanks - this was left over from a previous code version |
||
| val fieldIndex = row.fieldIndex(colName) | ||
| if (!row.isNullAt(fieldIndex)) { | ||
| val (rawIdx, value) = if (realFields(colName)) { | ||
| val value = row.getDouble(fieldIndex) | ||
| val hash = hashFunc(colName) | ||
| (hash, value) | ||
| } else { | ||
| val value = row.getString(fieldIndex) | ||
| val fieldName = s"$colName=$value" | ||
| val hash = hashFunc(fieldName) | ||
| (hash, 1.0) | ||
| } | ||
| val idx = Utils.nonNegativeMod(rawIdx, n) | ||
| map.changeValue(idx, value, v => v + value) | ||
| } | ||
| } | ||
| Vectors.sparse(n, map.toSeq) | ||
| } | ||
|
|
||
| val metadata = os($(outputCol)).metadata | ||
| dataset.select( | ||
| col("*"), | ||
| hashFeatures(struct(featureCols: _*)).as($(outputCol), metadata)) | ||
| } | ||
|
|
||
| override def copy(extra: ParamMap): FeatureHasher = defaultCopy(extra) | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. since tags on all public methods (copy, transformSchema, transform) |
||
|
|
||
| override def transformSchema(schema: StructType): StructType = { | ||
| val fields = schema($(inputCols).toSet) | ||
| require(fields.map(_.dataType).forall { case dt => | ||
| dt.isInstanceOf[NumericType] || dt.isInstanceOf[StringType] | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. require message |
||
| }) | ||
| val attrGroup = new AttributeGroup($(outputCol), $(numFeatures)) | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. It seems that we didn't store
Contributor
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Feature hashing doesn't keep the feature -> idx mapping for memory efficiency, so by extension it won't keep attribute info. This is by design, and the tradeoff is speed & efficiency vs. not being able to do the reverse mapping (or knowing the cardinality of each feature, for example). If users want to keep the mapping & attribute info, then of course they can just use one-hot encoding and vector assembler.
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. @MLnick Thanks for clarifying. |
||
| SchemaUtils.appendColumn(schema, attrGroup.toStructField()) | ||
| } | ||
| } | ||
|
|
||
| @Since("2.3.0") | ||
| object FeatureHasher extends DefaultParamsReadable[FeatureHasher] { | ||
|
|
||
| @Since("2.3.0") | ||
| override def load(path: String): FeatureHasher = super.load(path) | ||
| } | ||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,140 @@ | ||
| /* | ||
| * Licensed to the Apache Software Foundation (ASF) under one or more | ||
| * contributor license agreements. See the NOTICE file distributed with | ||
| * this work for additional information regarding copyright ownership. | ||
| * The ASF licenses this file to You under the Apache License, Version 2.0 | ||
| * (the "License"); you may not use this file except in compliance with | ||
| * the License. You may obtain a copy of the License at | ||
| * | ||
| * http://www.apache.org/licenses/LICENSE-2.0 | ||
| * | ||
| * Unless required by applicable law or agreed to in writing, software | ||
| * distributed under the License is distributed on an "AS IS" BASIS, | ||
| * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
| * See the License for the specific language governing permissions and | ||
| * limitations under the License. | ||
| */ | ||
|
|
||
| package org.apache.spark.ml.feature | ||
|
|
||
| import org.apache.spark.SparkFunSuite | ||
| import org.apache.spark.ml.attribute.AttributeGroup | ||
| import org.apache.spark.ml.linalg.{Vector, Vectors} | ||
| import org.apache.spark.ml.param.ParamsSuite | ||
| import org.apache.spark.ml.util.DefaultReadWriteTest | ||
| import org.apache.spark.ml.util.TestingUtils._ | ||
| import org.apache.spark.mllib.util.MLlibTestSparkContext | ||
| import org.apache.spark.sql.catalyst.encoders.ExpressionEncoder | ||
|
|
||
| class FeatureHasherSuite extends SparkFunSuite | ||
| with MLlibTestSparkContext | ||
| with DefaultReadWriteTest { | ||
|
|
||
| import testImplicits._ | ||
| import HashingTFSuite.murmur3FeatureIdx | ||
|
|
||
| implicit val vectorEncoder = ExpressionEncoder[Vector]() | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. private |
||
|
|
||
| test("params") { | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Maybe add a test for the Unicode column name (like Chinese, "中文") |
||
| ParamsSuite.checkParams(new FeatureHasher) | ||
| } | ||
|
|
||
| test("specify input cols using varargs or array") { | ||
| val featureHasher1 = new FeatureHasher() | ||
| .setInputCols("int", "double", "float", "stringNum", "string") | ||
| val featureHasher2 = new FeatureHasher() | ||
| .setInputCols(Array("int", "double", "float", "stringNum", "string")) | ||
| assert(featureHasher1.getInputCols === featureHasher2.getInputCols) | ||
| } | ||
|
|
||
| test("feature hashing") { | ||
| val df = Seq( | ||
| (3, 4.0, 5.0f, "1", "foo"), | ||
| (6, 7.0, 8.0f, "2", "bar") | ||
| ).toDF("int", "double", "float", "stringNum", "string") | ||
|
|
||
| val n = 100 | ||
| val featureHasher = new FeatureHasher() | ||
| .setInputCols("int", "double", "float", "stringNum", "string") | ||
| .setOutputCol("features") | ||
| .setNumFeatures(n) | ||
| val output = featureHasher.transform(df) | ||
| val attrGroup = AttributeGroup.fromStructField(output.schema("features")) | ||
| require(attrGroup.numAttributes === Some(n)) | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. make this an |
||
|
|
||
| val features = output.select("features").as[Vector].collect() | ||
| // Assume perfect hash on field names | ||
| def idx: Any => Int = murmur3FeatureIdx(n) | ||
| // check expected indices | ||
| val expected = Seq( | ||
| Vectors.sparse(n, Seq((idx("int"), 3.0), (idx("double"), 4.0), (idx("float"), 5.0), | ||
| (idx("stringNum=1"), 1.0), (idx("string=foo"), 1.0))), | ||
| Vectors.sparse(n, Seq((idx("int"), 6.0), (idx("double"), 7.0), (idx("float"), 8.0), | ||
| (idx("stringNum=2"), 1.0), (idx("string=bar"), 1.0))) | ||
| ) | ||
| assert(features.zip(expected).forall { case (e, a) => e ~== a absTol 1e-14 }) | ||
| } | ||
|
|
||
| test("hash collisions sum feature values") { | ||
| val df = Seq( | ||
| (1.0, "foo", "foo"), | ||
| (2.0, "bar", "baz") | ||
| ).toDF("double", "string1", "string2") | ||
|
|
||
| val n = 1 | ||
| val featureHasher = new FeatureHasher() | ||
| .setInputCols("double", "string1", "string2") | ||
| .setOutputCol("features") | ||
| .setNumFeatures(n) | ||
| val output = featureHasher.transform(df) | ||
|
|
||
| val features = output.select("features").as[Vector].collect() | ||
| def idx: Any => Int = murmur3FeatureIdx(n) | ||
| // everything should hash into one field | ||
| assert(idx("double") === idx("string1=foo")) | ||
| assert(idx("string1=foo") === idx("string2=foo")) | ||
| assert(idx("string2=foo") === idx("string1=bar")) | ||
| assert(idx("string1=bar") === idx("string2=baz")) | ||
| val expected = Seq( | ||
| Vectors.sparse(n, Seq((idx("string1=foo"), 3.0))), | ||
| Vectors.sparse(n, Seq((idx("string2=bar"), 4.0))) | ||
| ) | ||
| assert(features.zip(expected).forall { case (e, a) => e ~== a absTol 1e-14 }) | ||
| } | ||
|
|
||
| test("ignores null values in feature hashing") { | ||
| import org.apache.spark.sql.functions._ | ||
|
|
||
| val df = Seq( | ||
| (2.0, "foo", null), | ||
| (3.0, "bar", "baz") | ||
| ).toDF("double", "string1", "string2").select( | ||
| when(col("double") === 3.0, null).otherwise(col("double")).alias("double"), | ||
| col("string1"), | ||
| col("string2") | ||
| ) | ||
|
|
||
| val n = 100 | ||
| val featureHasher = new FeatureHasher() | ||
| .setInputCols("double", "string1", "string2") | ||
| .setOutputCol("features") | ||
| .setNumFeatures(n) | ||
| val output = featureHasher.transform(df) | ||
|
|
||
| val features = output.select("features").as[Vector].collect() | ||
| def idx: Any => Int = murmur3FeatureIdx(n) | ||
| val expected = Seq( | ||
| Vectors.sparse(n, Seq((idx("double"), 2.0), (idx("string1=foo"), 1.0))), | ||
| Vectors.sparse(n, Seq((idx("string1=bar"), 1.0), (idx("string2=baz"), 1.0))) | ||
| ) | ||
| assert(features.zip(expected).forall { case (e, a) => e ~== a absTol 1e-14 }) | ||
| } | ||
|
|
||
| test("read/write") { | ||
| val t = new FeatureHasher() | ||
| .setInputCols(Array("myCol1", "myCol2", "myCol3")) | ||
| .setOutputCol("myOutputCol") | ||
| .setNumFeatures(10) | ||
| testDefaultReadWrite(t) | ||
| } | ||
| } | ||
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
comment
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Yup, forgot that!