-
Notifications
You must be signed in to change notification settings - Fork 28.9k
[SPARK-5893][ML] Add bucketizer #5980
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
Closed
Closed
Changes from all commits
Commits
Show all changes
13 commits
Select commit
Hold shift + click to select a range
5fe190e
add bucketizer
yinxusen 4024cf1
add test suite
yinxusen 998bc87
check buckets
yinxusen 11fb00a
change it into an Estimator
yinxusen 2466322
refactor Bucketizer
yinxusen fb30d79
fix and test binary search
yinxusen ac77859
fix style error
yinxusen 3a16cc2
refine comments and names
yinxusen c3cc770
add more unit test for binary search
yinxusen eacfcfa
change ML attribute from splits into buckets
yinxusen 34f124a
Removed lowerInclusive, upperInclusive params from Bucketizer, and us…
jkbradley 1ca973a
one more bucketizer test
jkbradley dc8c843
Merge pull request #4 from jkbradley/yinxusen-SPARK-5893
yinxusen File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
131 changes: 131 additions & 0 deletions
131
mllib/src/main/scala/org/apache/spark/ml/feature/Bucketizer.scala
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,131 @@ | ||
/* | ||
* 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.AlphaComponent | ||
import org.apache.spark.ml.attribute.NominalAttribute | ||
import org.apache.spark.ml.param._ | ||
import org.apache.spark.ml.param.shared.{HasInputCol, HasOutputCol} | ||
import org.apache.spark.ml.util.SchemaUtils | ||
import org.apache.spark.ml.{Estimator, Model} | ||
import org.apache.spark.sql._ | ||
import org.apache.spark.sql.functions._ | ||
import org.apache.spark.sql.types.{DoubleType, StructField, StructType} | ||
|
||
/** | ||
* :: AlphaComponent :: | ||
* `Bucketizer` maps a column of continuous features to a column of feature buckets. | ||
*/ | ||
@AlphaComponent | ||
final class Bucketizer private[ml] (override val parent: Estimator[Bucketizer]) | ||
extends Model[Bucketizer] with HasInputCol with HasOutputCol { | ||
|
||
def this() = this(null) | ||
|
||
/** | ||
* Parameter for mapping continuous features into buckets. With n splits, there are n+1 buckets. | ||
* A bucket defined by splits x,y holds values in the range [x,y). Splits should be strictly | ||
* increasing. Values at -inf, inf must be explicitly provided to cover all Double values; | ||
* otherwise, values outside the splits specified will be treated as errors. | ||
* @group param | ||
*/ | ||
val splits: Param[Array[Double]] = new Param[Array[Double]](this, "splits", | ||
"Split points for mapping continuous features into buckets. With n splits, there are n+1 " + | ||
"buckets. A bucket defined by splits x,y holds values in the range [x,y). The splits " + | ||
"should be strictly increasing. Values at -inf, inf must be explicitly provided to cover" + | ||
" all Double values; otherwise, values outside the splits specified will be treated as" + | ||
" errors.", | ||
Bucketizer.checkSplits) | ||
|
||
/** @group getParam */ | ||
def getSplits: Array[Double] = $(splits) | ||
|
||
/** @group setParam */ | ||
def setSplits(value: Array[Double]): this.type = set(splits, value) | ||
|
||
/** @group setParam */ | ||
def setInputCol(value: String): this.type = set(inputCol, value) | ||
|
||
/** @group setParam */ | ||
def setOutputCol(value: String): this.type = set(outputCol, value) | ||
|
||
override def transform(dataset: DataFrame): DataFrame = { | ||
transformSchema(dataset.schema) | ||
val bucketizer = udf { feature: Double => | ||
Bucketizer.binarySearchForBuckets($(splits), feature) | ||
} | ||
val newCol = bucketizer(dataset($(inputCol))) | ||
val newField = prepOutputField(dataset.schema) | ||
dataset.withColumn($(outputCol), newCol.as($(outputCol), newField.metadata)) | ||
} | ||
|
||
private def prepOutputField(schema: StructType): StructField = { | ||
val buckets = $(splits).sliding(2).map(bucket => bucket.mkString(", ")).toArray | ||
val attr = new NominalAttribute(name = Some($(outputCol)), isOrdinal = Some(true), | ||
values = Some(buckets)) | ||
attr.toStructField() | ||
} | ||
|
||
override def transformSchema(schema: StructType): StructType = { | ||
SchemaUtils.checkColumnType(schema, $(inputCol), DoubleType) | ||
SchemaUtils.appendColumn(schema, prepOutputField(schema)) | ||
} | ||
} | ||
|
||
private[feature] object Bucketizer { | ||
/** We require splits to be of length >= 3 and to be in strictly increasing order. */ | ||
def checkSplits(splits: Array[Double]): Boolean = { | ||
if (splits.length < 3) { | ||
false | ||
} else { | ||
var i = 0 | ||
while (i < splits.length - 1) { | ||
if (splits(i) >= splits(i + 1)) return false | ||
i += 1 | ||
} | ||
true | ||
} | ||
} | ||
|
||
/** | ||
* Binary searching in several buckets to place each data point. | ||
* @throws RuntimeException if a feature is < splits.head or >= splits.last | ||
*/ | ||
def binarySearchForBuckets( | ||
splits: Array[Double], | ||
feature: Double): Double = { | ||
// Check bounds. We make an exception for +inf so that it can exist in some bin. | ||
if ((feature < splits.head) || (feature >= splits.last && feature != Double.PositiveInfinity)) { | ||
throw new RuntimeException(s"Feature value $feature out of Bucketizer bounds" + | ||
s" [${splits.head}, ${splits.last}). Check your features, or loosen " + | ||
s"the lower/upper bound constraints.") | ||
} | ||
var left = 0 | ||
var right = splits.length - 2 | ||
while (left < right) { | ||
val mid = (left + right) / 2 | ||
val split = splits(mid + 1) | ||
if (feature < split) { | ||
right = mid | ||
} else { | ||
left = mid + 1 | ||
} | ||
} | ||
left | ||
} | ||
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
148 changes: 148 additions & 0 deletions
148
mllib/src/test/scala/org/apache/spark/ml/feature/BucketizerSuite.scala
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,148 @@ | ||
/* | ||
* 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 scala.util.Random | ||
|
||
import org.scalatest.FunSuite | ||
|
||
import org.apache.spark.SparkException | ||
import org.apache.spark.mllib.linalg.Vectors | ||
import org.apache.spark.mllib.util.MLlibTestSparkContext | ||
import org.apache.spark.mllib.util.TestingUtils._ | ||
import org.apache.spark.sql.{DataFrame, Row, SQLContext} | ||
|
||
class BucketizerSuite extends FunSuite with MLlibTestSparkContext { | ||
|
||
@transient private var sqlContext: SQLContext = _ | ||
|
||
override def beforeAll(): Unit = { | ||
super.beforeAll() | ||
sqlContext = new SQLContext(sc) | ||
} | ||
|
||
test("Bucket continuous features, without -inf,inf") { | ||
// Check a set of valid feature values. | ||
val splits = Array(-0.5, 0.0, 0.5) | ||
val validData = Array(-0.5, -0.3, 0.0, 0.2) | ||
val expectedBuckets = Array(0.0, 0.0, 1.0, 1.0) | ||
val dataFrame: DataFrame = | ||
sqlContext.createDataFrame(validData.zip(expectedBuckets)).toDF("feature", "expected") | ||
|
||
val bucketizer: Bucketizer = new Bucketizer() | ||
.setInputCol("feature") | ||
.setOutputCol("result") | ||
.setSplits(splits) | ||
|
||
bucketizer.transform(dataFrame).select("result", "expected").collect().foreach { | ||
case Row(x: Double, y: Double) => | ||
assert(x === y, | ||
s"The feature value is not correct after bucketing. Expected $y but found $x") | ||
} | ||
|
||
// Check for exceptions when using a set of invalid feature values. | ||
val invalidData1: Array[Double] = Array(-0.9) ++ validData | ||
val invalidData2 = Array(0.5) ++ validData | ||
val badDF1 = sqlContext.createDataFrame(invalidData1.zipWithIndex).toDF("feature", "idx") | ||
intercept[RuntimeException]{ | ||
bucketizer.transform(badDF1).collect() | ||
println("Invalid feature value -0.9 was not caught as an invalid feature!") | ||
} | ||
val badDF2 = sqlContext.createDataFrame(invalidData2.zipWithIndex).toDF("feature", "idx") | ||
intercept[RuntimeException]{ | ||
bucketizer.transform(badDF2).collect() | ||
println("Invalid feature value 0.5 was not caught as an invalid feature!") | ||
} | ||
} | ||
|
||
test("Bucket continuous features, with -inf,inf") { | ||
val splits = Array(Double.NegativeInfinity, -0.5, 0.0, 0.5, Double.PositiveInfinity) | ||
val validData = Array(-0.9, -0.5, -0.3, 0.0, 0.2, 0.5, 0.9) | ||
val expectedBuckets = Array(0.0, 1.0, 1.0, 2.0, 2.0, 3.0, 3.0) | ||
val dataFrame: DataFrame = | ||
sqlContext.createDataFrame(validData.zip(expectedBuckets)).toDF("feature", "expected") | ||
|
||
val bucketizer: Bucketizer = new Bucketizer() | ||
.setInputCol("feature") | ||
.setOutputCol("result") | ||
.setSplits(splits) | ||
|
||
bucketizer.transform(dataFrame).select("result", "expected").collect().foreach { | ||
case Row(x: Double, y: Double) => | ||
assert(x === y, | ||
s"The feature value is not correct after bucketing. Expected $y but found $x") | ||
} | ||
} | ||
|
||
test("Binary search correctness on hand-picked examples") { | ||
import BucketizerSuite.checkBinarySearch | ||
// length 3, with -inf | ||
checkBinarySearch(Array(Double.NegativeInfinity, 0.0, 1.0)) | ||
// length 4 | ||
checkBinarySearch(Array(-1.0, -0.5, 0.0, 1.0)) | ||
// length 5 | ||
checkBinarySearch(Array(-1.0, -0.5, 0.0, 1.0, 1.5)) | ||
// length 3, with inf | ||
checkBinarySearch(Array(0.0, 1.0, Double.PositiveInfinity)) | ||
// length 3, with -inf and inf | ||
checkBinarySearch(Array(Double.NegativeInfinity, 1.0, Double.PositiveInfinity)) | ||
// length 4, with -inf and inf | ||
checkBinarySearch(Array(Double.NegativeInfinity, 0.0, 1.0, Double.PositiveInfinity)) | ||
} | ||
|
||
test("Binary search correctness in contrast with linear search, on random data") { | ||
val data = Array.fill(100)(Random.nextDouble()) | ||
val splits: Array[Double] = Double.NegativeInfinity +: | ||
Array.fill(10)(Random.nextDouble()).sorted :+ Double.PositiveInfinity | ||
val bsResult = Vectors.dense(data.map(x => Bucketizer.binarySearchForBuckets(splits, x))) | ||
val lsResult = Vectors.dense(data.map(x => BucketizerSuite.linearSearchForBuckets(splits, x))) | ||
assert(bsResult ~== lsResult absTol 1e-5) | ||
} | ||
} | ||
|
||
private object BucketizerSuite extends FunSuite { | ||
/** Brute force search for buckets. Bucket i is defined by the range [split(i), split(i+1)). */ | ||
def linearSearchForBuckets(splits: Array[Double], feature: Double): Double = { | ||
require(feature >= splits.head) | ||
var i = 0 | ||
while (i < splits.length - 1) { | ||
if (feature < splits(i + 1)) return i | ||
i += 1 | ||
} | ||
throw new RuntimeException( | ||
s"linearSearchForBuckets failed to find bucket for feature value $feature") | ||
} | ||
|
||
/** Check all values in splits, plus values between all splits. */ | ||
def checkBinarySearch(splits: Array[Double]): Unit = { | ||
def testFeature(feature: Double, expectedBucket: Double): Unit = { | ||
assert(Bucketizer.binarySearchForBuckets(splits, feature) === expectedBucket, | ||
s"Expected feature value $feature to be in bucket $expectedBucket with splits:" + | ||
s" ${splits.mkString(", ")}") | ||
} | ||
var i = 0 | ||
while (i < splits.length - 1) { | ||
testFeature(splits(i), i) // Split i should fall in bucket i. | ||
testFeature((splits(i) + splits(i + 1)) / 2, i) // Value between splits i,i+1 should be in i. | ||
i += 1 | ||
} | ||
if (splits.last === Double.PositiveInfinity) { | ||
testFeature(Double.PositiveInfinity, splits.length - 2) | ||
} | ||
} | ||
} |
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
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.
I know it's implied, but can this please state that the splits should be strictly increasing?