QuantileDiscretizer
QuantileDiscretizer takes a column with continuous features and outputs a column with binned categorical features. The number of bins is set by the numBuckets parameter. It is possible that the number of buckets used will be smaller than this value, for example, if there are too few distinct values of the input to create enough distinct quantiles.
NaN values: NaN values will be removed from the column during QuantileDiscretizer fitting. This will produce a Bucketizer model for making predictions. During the transformation, Bucketizer will raise an error when it finds NaN values in the dataset, but the user can also choose to either keep or remove NaN values within the dataset by setting handleInvalid. If the user chooses to keep NaN values, they will be handled specially and placed into their own bucket, for example, if 4 buckets are used, then non-NaN data will be put into buckets[0-3], but NaNs will be counted in a special bucket[4].
Algorithm: The bin ranges are chosen using an approximate algorithm (see the documentation for approxQuantile for a detailed description). The precision of the approximation can be controlled with the relativeError parameter. When set to zero, exact quantiles are calculated (Note: Computing exact quantiles is an expensive operation). The lower and upper bin bounds will be -Infinity and +Infinity covering all real values.
Examples
Assume that we have a DataFrame with the columns id, hour:
id
hour
0
18.0
----
------
1
19.0
----
------
2
8.0
----
------
3
5.0
----
------
4
2.2
hour is a continuous feature with Double type. We want to turn the continuous feature into a categorical one. Given numBuckets = 3, we should get the following DataFrame:
id
hour
result
0
18.0
2.0
----
------
------
1
19.0
2.0
----
------
------
2
8.0
1.0
----
------
------
3
5.0
1.0
----
------
------
4
2.2
0.0
1
import org.apache.spark.ml.feature.QuantileDiscretizer
2
​
3
val data = Array((0, 18.0), (1, 19.0), (2, 8.0), (3, 5.0), (4, 2.2))
4
val df = spark.createDataFrame(data).toDF("id", "hour")
5
​
6
val discretizer = new QuantileDiscretizer()
7
.setInputCol("hour")
8
.setOutputCol("result")
9
.setNumBuckets(3)
10
​
11
val result = discretizer.fit(df).transform(df)
12
result.show(false)
13
​
14
/*
15
Output:
16
+---+----+------+
17
|id |hour|result|
18
+---+----+------+
19
|0 |18.0|2.0 |
20
|1 |19.0|2.0 |
21
|2 |8.0 |1.0 |
22
|3 |5.0 |1.0 |
23
|4 |2.2 |0.0 |
24
+---+----+------+
25
​
26
​
27
*/
Copied!
​
Last modified 1yr ago
Copy link