QuantileDiscretizer¶
-
class
pyspark.ml.feature.
QuantileDiscretizer
(*, numBuckets: int = 2, inputCol: Optional[str] = None, outputCol: Optional[str] = None, relativeError: float = 0.001, handleInvalid: str = 'error', numBucketsArray: Optional[List[int]] = None, inputCols: Optional[List[str]] = None, outputCols: Optional[List[str]] = None)[source]¶ QuantileDiscretizer
takes a column with continuous features and outputs a column with binned categorical features. The number of bins can be set using thenumBuckets
parameter. It is possible that the number of buckets used will be less than this value, for example, if there are too few distinct values of the input to create enough distinct quantiles. Since 3.0.0,QuantileDiscretizer
can map multiple columns at once by setting theinputCols
parameter. If both of theinputCol
andinputCols
parameters are set, an Exception will be thrown. To specify the number of buckets for each column, thenumBucketsArray
parameter can be set, or if the number of buckets should be the same across columns,numBuckets
can be set as a convenience.New in version 2.0.0.
Notes
NaN handling: Note also that
QuantileDiscretizer
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 settinghandleInvalid
parameter. 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
pyspark.sql.DataFrameStatFunctions.approxQuantile()
for a detailed description). The precision of the approximation can be controlled with therelativeError
parameter. The lower and upper bin bounds will be -Infinity and +Infinity, covering all real values.Examples
>>> values = [(0.1,), (0.4,), (1.2,), (1.5,), (float("nan"),), (float("nan"),)] >>> df1 = spark.createDataFrame(values, ["values"]) >>> qds1 = QuantileDiscretizer(inputCol="values", outputCol="buckets") >>> qds1.setNumBuckets(2) QuantileDiscretizer... >>> qds1.setRelativeError(0.01) QuantileDiscretizer... >>> qds1.setHandleInvalid("error") QuantileDiscretizer... >>> qds1.getRelativeError() 0.01 >>> bucketizer = qds1.fit(df1) >>> qds1.setHandleInvalid("keep").fit(df1).transform(df1).count() 6 >>> qds1.setHandleInvalid("skip").fit(df1).transform(df1).count() 4 >>> splits = bucketizer.getSplits() >>> splits[0] -inf >>> print("%2.1f" % round(splits[1], 1)) 0.4 >>> bucketed = bucketizer.transform(df1).head() >>> bucketed.buckets 0.0 >>> quantileDiscretizerPath = temp_path + "/quantile-discretizer" >>> qds1.save(quantileDiscretizerPath) >>> loadedQds = QuantileDiscretizer.load(quantileDiscretizerPath) >>> loadedQds.getNumBuckets() == qds1.getNumBuckets() True >>> inputs = [(0.1, 0.0), (0.4, 1.0), (1.2, 1.3), (1.5, 1.5), ... (float("nan"), float("nan")), (float("nan"), float("nan"))] >>> df2 = spark.createDataFrame(inputs, ["input1", "input2"]) >>> qds2 = QuantileDiscretizer(relativeError=0.01, handleInvalid="error", numBuckets=2, ... inputCols=["input1", "input2"], outputCols=["output1", "output2"]) >>> qds2.getRelativeError() 0.01 >>> qds2.setHandleInvalid("keep").fit(df2).transform(df2).show() +------+------+-------+-------+ |input1|input2|output1|output2| +------+------+-------+-------+ | 0.1| 0.0| 0.0| 0.0| | 0.4| 1.0| 1.0| 1.0| | 1.2| 1.3| 1.0| 1.0| | 1.5| 1.5| 1.0| 1.0| | NaN| NaN| 2.0| 2.0| | NaN| NaN| 2.0| 2.0| +------+------+-------+-------+ ... >>> qds3 = QuantileDiscretizer(relativeError=0.01, handleInvalid="error", ... numBucketsArray=[5, 10], inputCols=["input1", "input2"], ... outputCols=["output1", "output2"]) >>> qds3.setHandleInvalid("skip").fit(df2).transform(df2).show() +------+------+-------+-------+ |input1|input2|output1|output2| +------+------+-------+-------+ | 0.1| 0.0| 1.0| 1.0| | 0.4| 1.0| 2.0| 2.0| | 1.2| 1.3| 3.0| 3.0| | 1.5| 1.5| 4.0| 4.0| +------+------+-------+-------+ ...
Methods
clear
(param)Clears a param from the param map if it has been explicitly set.
copy
([extra])Creates a copy of this instance with the same uid and some extra params.
explainParam
(param)Explains a single param and returns its name, doc, and optional default value and user-supplied value in a string.
Returns the documentation of all params with their optionally default values and user-supplied values.
extractParamMap
([extra])Extracts the embedded default param values and user-supplied values, and then merges them with extra values from input into a flat param map, where the latter value is used if there exist conflicts, i.e., with ordering: default param values < user-supplied values < extra.
fit
(dataset[, params])Fits a model to the input dataset with optional parameters.
fitMultiple
(dataset, paramMaps)Fits a model to the input dataset for each param map in paramMaps.
Gets the value of handleInvalid or its default value.
Gets the value of inputCol or its default value.
Gets the value of inputCols or its default value.
Gets the value of numBuckets or its default value.
Gets the value of numBucketsArray or its default value.
getOrDefault
(param)Gets the value of a param in the user-supplied param map or its default value.
Gets the value of outputCol or its default value.
Gets the value of outputCols or its default value.
getParam
(paramName)Gets a param by its name.
Gets the value of relativeError or its default value.
hasDefault
(param)Checks whether a param has a default value.
hasParam
(paramName)Tests whether this instance contains a param with a given (string) name.
isDefined
(param)Checks whether a param is explicitly set by user or has a default value.
isSet
(param)Checks whether a param is explicitly set by user.
load
(path)Reads an ML instance from the input path, a shortcut of read().load(path).
read
()Returns an MLReader instance for this class.
save
(path)Save this ML instance to the given path, a shortcut of ‘write().save(path)’.
set
(param, value)Sets a parameter in the embedded param map.
setHandleInvalid
(value)Sets the value of
handleInvalid
.setInputCol
(value)Sets the value of
inputCol
.setInputCols
(value)Sets the value of
inputCols
.setNumBuckets
(value)Sets the value of
numBuckets
.setNumBucketsArray
(value)Sets the value of
numBucketsArray
.setOutputCol
(value)Sets the value of
outputCol
.setOutputCols
(value)Sets the value of
outputCols
.setParams
(self, \*[, numBuckets, inputCol, …])Set the params for the QuantileDiscretizer
setRelativeError
(value)Sets the value of
relativeError
.write
()Returns an MLWriter instance for this ML instance.
Attributes
Returns all params ordered by name.
Methods Documentation
-
clear
(param: pyspark.ml.param.Param) → None¶ Clears a param from the param map if it has been explicitly set.
-
copy
(extra: Optional[ParamMap] = None) → JP¶ Creates a copy of this instance with the same uid and some extra params. This implementation first calls Params.copy and then make a copy of the companion Java pipeline component with extra params. So both the Python wrapper and the Java pipeline component get copied.
- Parameters
- extradict, optional
Extra parameters to copy to the new instance
- Returns
JavaParams
Copy of this instance
-
explainParam
(param: Union[str, pyspark.ml.param.Param]) → str¶ Explains a single param and returns its name, doc, and optional default value and user-supplied value in a string.
-
explainParams
() → str¶ Returns the documentation of all params with their optionally default values and user-supplied values.
-
extractParamMap
(extra: Optional[ParamMap] = None) → ParamMap¶ Extracts the embedded default param values and user-supplied values, and then merges them with extra values from input into a flat param map, where the latter value is used if there exist conflicts, i.e., with ordering: default param values < user-supplied values < extra.
- Parameters
- extradict, optional
extra param values
- Returns
- dict
merged param map
-
fit
(dataset: pyspark.sql.dataframe.DataFrame, params: Union[ParamMap, List[ParamMap], Tuple[ParamMap], None] = None) → Union[M, List[M]]¶ Fits a model to the input dataset with optional parameters.
New in version 1.3.0.
- Parameters
- dataset
pyspark.sql.DataFrame
input dataset.
- paramsdict or list or tuple, optional
an optional param map that overrides embedded params. If a list/tuple of param maps is given, this calls fit on each param map and returns a list of models.
- dataset
- Returns
Transformer
or a list ofTransformer
fitted model(s)
-
fitMultiple
(dataset: pyspark.sql.dataframe.DataFrame, paramMaps: Sequence[ParamMap]) → Iterator[Tuple[int, M]]¶ Fits a model to the input dataset for each param map in paramMaps.
New in version 2.3.0.
- Parameters
- dataset
pyspark.sql.DataFrame
input dataset.
- paramMaps
collections.abc.Sequence
A Sequence of param maps.
- dataset
- Returns
_FitMultipleIterator
A thread safe iterable which contains one model for each param map. Each call to next(modelIterator) will return (index, model) where model was fit using paramMaps[index]. index values may not be sequential.
-
getHandleInvalid
() → str¶ Gets the value of handleInvalid or its default value.
-
getInputCol
() → str¶ Gets the value of inputCol or its default value.
-
getInputCols
() → List[str]¶ Gets the value of inputCols or its default value.
-
getNumBuckets
() → int[source]¶ Gets the value of numBuckets or its default value.
New in version 2.0.0.
-
getNumBucketsArray
() → List[int][source]¶ Gets the value of numBucketsArray or its default value.
New in version 3.0.0.
-
getOrDefault
(param: Union[str, pyspark.ml.param.Param[T]]) → Union[Any, T]¶ Gets the value of a param in the user-supplied param map or its default value. Raises an error if neither is set.
-
getOutputCol
() → str¶ Gets the value of outputCol or its default value.
-
getOutputCols
() → List[str]¶ Gets the value of outputCols or its default value.
-
getParam
(paramName: str) → pyspark.ml.param.Param¶ Gets a param by its name.
-
getRelativeError
() → float¶ Gets the value of relativeError or its default value.
-
hasDefault
(param: Union[str, pyspark.ml.param.Param[Any]]) → bool¶ Checks whether a param has a default value.
-
hasParam
(paramName: str) → bool¶ Tests whether this instance contains a param with a given (string) name.
-
isDefined
(param: Union[str, pyspark.ml.param.Param[Any]]) → bool¶ Checks whether a param is explicitly set by user or has a default value.
-
isSet
(param: Union[str, pyspark.ml.param.Param[Any]]) → bool¶ Checks whether a param is explicitly set by user.
-
classmethod
load
(path: str) → RL¶ Reads an ML instance from the input path, a shortcut of read().load(path).
-
classmethod
read
() → pyspark.ml.util.JavaMLReader[RL]¶ Returns an MLReader instance for this class.
-
save
(path: str) → None¶ Save this ML instance to the given path, a shortcut of ‘write().save(path)’.
-
set
(param: pyspark.ml.param.Param, value: Any) → None¶ Sets a parameter in the embedded param map.
-
setHandleInvalid
(value: str) → pyspark.ml.feature.QuantileDiscretizer[source]¶ Sets the value of
handleInvalid
.
-
setInputCol
(value: str) → pyspark.ml.feature.QuantileDiscretizer[source]¶ Sets the value of
inputCol
.
-
setInputCols
(value: List[str]) → pyspark.ml.feature.QuantileDiscretizer[source]¶ Sets the value of
inputCols
.New in version 3.0.0.
-
setNumBuckets
(value: int) → pyspark.ml.feature.QuantileDiscretizer[source]¶ Sets the value of
numBuckets
.New in version 2.0.0.
-
setNumBucketsArray
(value: List[int]) → pyspark.ml.feature.QuantileDiscretizer[source]¶ Sets the value of
numBucketsArray
.New in version 3.0.0.
-
setOutputCol
(value: str) → pyspark.ml.feature.QuantileDiscretizer[source]¶ Sets the value of
outputCol
.
-
setOutputCols
(value: List[str]) → pyspark.ml.feature.QuantileDiscretizer[source]¶ Sets the value of
outputCols
.New in version 3.0.0.
-
setParams
(self, \*, numBuckets=2, inputCol=None, outputCol=None, relativeError=0.001, handleInvalid="error", numBucketsArray=None, inputCols=None, outputCols=None)[source]¶ Set the params for the QuantileDiscretizer
New in version 2.0.0.
-
setRelativeError
(value: float) → pyspark.ml.feature.QuantileDiscretizer[source]¶ Sets the value of
relativeError
.New in version 2.0.0.
-
write
() → pyspark.ml.util.JavaMLWriter¶ Returns an MLWriter instance for this ML instance.
Attributes Documentation
-
handleInvalid
: pyspark.ml.param.Param[str] = Param(parent='undefined', name='handleInvalid', doc="how to handle invalid entries. Options are skip (filter out rows with invalid values), error (throw an error), or keep (keep invalid values in a special additional bucket). Note that in the multiple columns case, the invalid handling is applied to all columns. That said for 'error' it will throw an error if any invalids are found in any columns, for 'skip' it will skip rows with any invalids in any columns, etc.")¶
-
inputCol
= Param(parent='undefined', name='inputCol', doc='input column name.')¶
-
inputCols
= Param(parent='undefined', name='inputCols', doc='input column names.')¶
-
numBuckets
: pyspark.ml.param.Param[int] = Param(parent='undefined', name='numBuckets', doc='Maximum number of buckets (quantiles, or categories) into which data points are grouped. Must be >= 2.')¶
-
numBucketsArray
: pyspark.ml.param.Param[List[int]] = Param(parent='undefined', name='numBucketsArray', doc='Array of number of buckets (quantiles, or categories) into which data points are grouped. This is for multiple columns input. If transforming multiple columns and numBucketsArray is not set, but numBuckets is set, then numBuckets will be applied across all columns.')¶
-
outputCol
= Param(parent='undefined', name='outputCol', doc='output column name.')¶
-
outputCols
= Param(parent='undefined', name='outputCols', doc='output column names.')¶
-
params
¶ Returns all params ordered by name. The default implementation uses
dir()
to get all attributes of typeParam
.
-
relativeError
= Param(parent='undefined', name='relativeError', doc='the relative target precision for the approximate quantile algorithm. Must be in the range [0, 1]')¶
-