RandomForestClassifier#

class spark_rapids_ml.classification.RandomForestClassifier(*, featuresCol: Union[str, List[str]] = 'features', labelCol: str = 'label', predictionCol: str = 'prediction', probabilityCol: str = 'probability', rawPredictionCol: str = 'rawPrediction', maxDepth: int = 5, maxBins: int = 32, minInstancesPerNode: int = 1, impurity: str = 'gini', numTrees: int = 20, featureSubsetStrategy: str = 'auto', seed: Optional[int] = None, bootstrap: Optional[bool] = True, num_workers: Optional[int] = None, verbose: Union[int, bool] = False, n_streams: int = 1, min_samples_split: Union[int, float] = 2, max_samples: float = 1.0, max_leaves: int = -1, min_impurity_decrease: float = 0.0, max_batch_size: int = 4096, **kwargs: Any)#

RandomForestClassifier implements a Random Forest classifier model which fits multiple decision tree classifiers in an ensemble. It supports both binary and multiclass labels. It implements cuML’s GPU accelerated RandomForestClassifier algorithm based on cuML python library, and it can be used in PySpark Pipeline and PySpark ML meta algorithms like CrossValidator, TrainValidationSplit, OneVsRest.

The distributed algorithm uses an embarrassingly-parallel approach. For a forest with N trees being built on w workers, each worker simply builds N/w trees on the data it has available locally. In many cases, partitioning the data so that each worker builds trees on a subset of the total dataset works well, but it generally requires the data to be well-shuffled in advance.

RandomForestClassifier automatically supports most of the parameters from both RandomForestClassifier and cuml.ensemble.RandomForestClassifier. And it can automatically map pyspark parameters to cuML parameters.

Parameters:
featuresCol: str or List[str]

The feature column names, spark-rapids-ml supports vector, array and columnar as the input.

  • When the value is a string, the feature columns must be assembled into 1 column with vector or array type.

  • When the value is a list of strings, the feature columns must be numeric types.

labelCol:

The label column name.

predictionCol:

The prediction column name.

probabilityCol:

The column name for predicted class conditional probabilities.

rawPredictionCol:

The column name for class raw predictions - this is currently set equal to probabilityCol values.

maxDepth:

Maximum tree depth. Must be greater than 0.

maxBins:

Maximum number of bins used by the split algorithm per feature.

minInstancesPerNode:

The minimum number of samples (rows) in each leaf node.

impurity: str = “gini”,

The criterion used to split nodes.

  • 'gini' for gini impurity

  • 'entropy' for information gain (entropy)

numTrees:

Total number of trees in the forest.

featureSubsetStrategy:

Ratio of number of features (columns) to consider per node split.

The supported options:

'auto': If numTrees == 1, set to ‘all’, If numTrees > 1 (forest), set to ‘sqrt’

'all': use all features

'onethird': use 1/3 of the features

'sqrt': use sqrt(number of features)

'log2': log2(number of features)

'n': when n is in the range (0, 1.0], use n * number of features. When n is in the range (1, number of features), use n features.

seed:

Seed for the random number generator.

bootstrap:

Control bootstrapping.

  • If True, each tree in the forest is built on a bootstrapped sample with replacement.

  • If False, the whole dataset is used to build each tree.

num_workers:

Number of cuML workers, where each cuML worker corresponds to one Spark task running on one GPU. If not set, spark-rapids-ml tries to infer the number of cuML workers (i.e. GPUs in cluster) from the Spark environment.

verbose:
Logging level.
  • 0 - Disables all log messages.

  • 1 - Enables only critical messages.

  • 2 - Enables all messages up to and including errors.

  • 3 - Enables all messages up to and including warnings.

  • 4 or False - Enables all messages up to and including information messages.

  • 5 or True - Enables all messages up to and including debug messages.

  • 6 - Enables all messages up to and including trace messages.

n_streams:

Number of parallel streams used for forest building. Please note that there is a bug running spark-rapids-ml on a node with multi-gpus when n_streams > 1. See rapidsai/cuml#5402.

min_samples_split:

The minimum number of samples required to split an internal node.

  • If type int, then min_samples_split represents the minimum number.

  • If type float, then min_samples_split represents a fraction and ceil(min_samples_split * n_rows) is the minimum number of samples for each split. max_samples:

Ratio of dataset rows used while fitting each tree.

max_leaves:

Maximum leaf nodes per tree. Soft constraint. Unlimited, if -1.

min_impurity_decrease:

Minimum decrease in impurity required for node to be split.

max_batch_size:

Maximum number of nodes that can be processed in a given batch.

Examples

>>> import numpy
>>> from numpy import allclose
>>> from pyspark.ml.linalg import Vectors
>>> from pyspark.ml.feature import StringIndexer
>>> df = spark.createDataFrame([
...     (1.0, Vectors.dense(1.0)),
...     (0.0, Vectors.sparse(1, [], []))], ["label", "features"])
>>> stringIndexer = StringIndexer(inputCol="label", outputCol="indexed")
>>> si_model = stringIndexer.fit(df)
>>> td = si_model.transform(df)
>>> from spark_rapids_ml.classification import RandomForestClassifier, RandomForestClassificationModel
>>> rf = RandomForestClassifier(numTrees=3, maxDepth=2, labelCol="indexed", seed=42)
>>> model = rf.fit(td)
>>> model.getLabelCol()
'indexed'
>>> model.setFeaturesCol("features")
RandomForestClassificationModel_...
>>> model.getBootstrap()
True
>>> test0 = spark.createDataFrame([(Vectors.dense(-1.0),)], ["features"])
>>> result = model.transform(test0).head()
>>> result.prediction
0.0
>>> test1 = spark.createDataFrame([(Vectors.sparse(1, [0], [1.0]),)], ["features"])
>>> model.transform(test1).head().prediction
1.0
>>>
>>> rfc_path = temp_path + "/rfc"
>>> rf.save(rfc_path)
>>> rf2 = RandomForestClassifier.load(rfc_path)
>>> rf2.getNumTrees()
3
>>> model_path = temp_path + "/rfc_model"
>>> model.save(model_path)
>>> model2 = RandomForestClassificationModel.load(model_path)
>>> model2.getNumTrees
3
>>> model.transform(test0).take(1) == model2.transform(test0).take(1)
True

Methods

clear(param)

Reset a Spark ML Param to its default value, setting matching cuML parameter, if exists.

copy([extra])

explainParam(param)

Explains a single param and returns its name, doc, and optional default value and user-supplied value in a string.

explainParams()

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 multiple models to the input dataset for all param maps in a single pass.

getBootstrap()

Gets the value of bootstrap or its default value.

getFeatureSubsetStrategy()

Gets the value of featureSubsetStrategy or its default value.

getFeaturesCol()

Gets the value of featuresCol or featuresCols

getFeaturesCols()

Gets the value of featuresCols or its default value.

getImpurity()

Gets the value of impurity or its default value.

getLabelCol()

Gets the value of labelCol or its default value.

getMaxBins()

Gets the value of maxBins or its default value.

getMaxDepth()

Gets the value of maxDepth or its default value.

getMinInstancesPerNode()

Gets the value of minInstancesPerNode or its default value.

getNumTrees()

Gets the value of numTrees or its default value.

getOrDefault(param)

Gets the value of a param in the user-supplied param map or its default value.

getParam(paramName)

Gets a param by its name.

getProbabilityCol()

Gets the value of probabilityCol or its default value.

getRawPredictionCol()

Gets the value of rawPredictionCol or its default value.

getSeed()

Gets the value of seed 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()

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.

setBootstrap(value)

Sets the value of bootstrap.

setFeatureSubsetStrategy(value)

Sets the value of featureSubsetStrategy.

setFeaturesCol(value)

Sets the value of featuresCol or featureCols.

setFeaturesCols(value)

Sets the value of featuresCols.

setImpurity(value)

Sets the value of impurity.

setLabelCol(value)

Sets the value of labelCol.

setMaxBins(value)

Sets the value of maxBins.

setMaxDepth(value)

Sets the value of maxDepth.

setMinInstancesPerNode(value)

Sets the value of minInstancesPerNode.

setNumTrees(value)

Sets the value of numTrees.

setPredictionCol(value)

Sets the value of predictionCol.

setProbabilityCol(value)

Sets the value of probabilityCol.

setRawPredictionCol(value)

Sets the value of rawPredictionCol.

setSeed(value)

Sets the value of seed.

write()

Attributes

bootstrap

cuml_params

Returns the dictionary of parameters intended for the underlying cuML class.

featureSubsetStrategy

featuresCol

featuresCols

impurity

labelCol

maxBins

maxDepth

minInstancesPerNode

numTrees

num_workers

Number of cuML workers, where each cuML worker corresponds to one Spark task running on one GPU.

params

Returns all params ordered by name.

probabilityCol

rawPredictionCol

seed

supportedFeatureSubsetStrategies

supportedImpurities

Methods Documentation

clear(param: Param) None#

Reset a Spark ML Param to its default value, setting matching cuML parameter, if exists.

copy(extra: Optional[ParamMap] = None) P#
explainParam(param: Union[str, 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: DataFrame, params: Optional[Union[ParamMap, List[ParamMap], Tuple[ParamMap]]] = None) Union[M, List[M]]#

Fits a model to the input dataset with optional parameters.

New in version 1.3.0.

Parameters:
datasetpyspark.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.

Returns:
Transformer or a list of Transformer

fitted model(s)

fitMultiple(dataset: DataFrame, paramMaps: Sequence[ParamMap]) Iterator[Tuple[int, _CumlModel]]#

Fits multiple models to the input dataset for all param maps in a single pass.

Parameters:
datasetpyspark.sql.DataFrame

input dataset.

paramMapscollections.abc.Sequence

A Sequence of param maps.

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.

getBootstrap() bool#

Gets the value of bootstrap or its default value.

New in version 3.0.0.

getFeatureSubsetStrategy() str#

Gets the value of featureSubsetStrategy or its default value.

New in version 1.4.0.

getFeaturesCol() Union[str, List[str]]#

Gets the value of featuresCol or featuresCols

getFeaturesCols() List[str]#

Gets the value of featuresCols or its default value.

getImpurity() str#

Gets the value of impurity or its default value.

New in version 1.6.0.

getLabelCol() str#

Gets the value of labelCol or its default value.

getMaxBins() int#

Gets the value of maxBins or its default value.

getMaxDepth() int#

Gets the value of maxDepth or its default value.

getMinInstancesPerNode() int#

Gets the value of minInstancesPerNode or its default value.

getNumTrees() int#

Gets the value of numTrees or its default value.

New in version 1.4.0.

getOrDefault(param: Union[str, 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.

getParam(paramName: str) Param#

Gets a param by its name.

getProbabilityCol() str#

Gets the value of probabilityCol or its default value.

getRawPredictionCol() str#

Gets the value of rawPredictionCol or its default value.

getSeed() int#

Gets the value of seed or its default value.

hasDefault(param: Union[str, 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, Param[Any]]) bool#

Checks whether a param is explicitly set by user or has a default value.

isSet(param: Union[str, 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() MLReader#
save(path: str) None#

Save this ML instance to the given path, a shortcut of ‘write().save(path)’.

set(param: Param, value: Any) None#

Sets a parameter in the embedded param map.

setBootstrap(value: bool) P#

Sets the value of bootstrap.

setFeatureSubsetStrategy(value: str) P#

Sets the value of featureSubsetStrategy.

setFeaturesCol(value: Union[str, List[str]]) P#

Sets the value of featuresCol or featureCols.

setFeaturesCols(value: List[str]) P#

Sets the value of featuresCols.

setImpurity(value: str) P#

Sets the value of impurity.

setLabelCol(value: str) P#

Sets the value of labelCol.

setMaxBins(value: int) P#

Sets the value of maxBins.

setMaxDepth(value: int) P#

Sets the value of maxDepth.

setMinInstancesPerNode(value: int) P#

Sets the value of minInstancesPerNode.

setNumTrees(value: int) P#

Sets the value of numTrees.

setPredictionCol(value: str) P#

Sets the value of predictionCol.

setProbabilityCol(value: str) _RFClassifierParams#

Sets the value of probabilityCol.

setRawPredictionCol(value: str) _RFClassifierParams#

Sets the value of rawPredictionCol.

setSeed(value: int) P#

Sets the value of seed.

write() MLWriter#

Attributes Documentation

bootstrap: Param[bool] = Param(parent='undefined', name='bootstrap', doc='Whether bootstrap samples are used when building trees.')#
cuml_params#

Returns the dictionary of parameters intended for the underlying cuML class.

featureSubsetStrategy: Param[str] = Param(parent='undefined', name='featureSubsetStrategy', doc="The number of features to consider for splits at each tree node. Supported options: 'auto' (choose automatically for task: If numTrees == 1, set to 'all'. If numTrees > 1 (forest), set to 'sqrt' for classification and to 'onethird' for regression), 'all' (use all features), 'onethird' (use 1/3 of the features), 'sqrt' (use sqrt(number of features)), 'log2' (use log2(number of features)), 'n' (when n is in the range (0, 1.0], use n * number of features. When n is in the range (1, number of features), use n features). default = 'auto'")#
featuresCol: Param[str] = Param(parent='undefined', name='featuresCol', doc='features column name.')#
featuresCols = Param(parent='undefined', name='featuresCols', doc='features column names for multi-column input.')#
impurity: Param[str] = Param(parent='undefined', name='impurity', doc='Criterion used for information gain calculation (case-insensitive). Supported options: entropy, gini')#
labelCol: Param[str] = Param(parent='undefined', name='labelCol', doc='label column name.')#
maxBins: Param[int] = Param(parent='undefined', name='maxBins', doc='Max number of bins for discretizing continuous features.  Must be >=2 and >= number of categories for any categorical feature.')#
maxDepth: Param[int] = Param(parent='undefined', name='maxDepth', doc='Maximum depth of the tree. (>= 0) E.g., depth 0 means 1 leaf node; depth 1 means 1 internal node + 2 leaf nodes. Must be in range [0, 30].')#
minInstancesPerNode: Param[int] = Param(parent='undefined', name='minInstancesPerNode', doc='Minimum number of instances each child must have after split. If a split causes the left or right child to have fewer than minInstancesPerNode, the split will be discarded as invalid. Should be >= 1.')#
numTrees: Param[int] = Param(parent='undefined', name='numTrees', doc='Number of trees to train (>= 1).')#
num_workers#

Number of cuML workers, where each cuML worker corresponds to one Spark task running on one GPU.

params#

Returns all params ordered by name. The default implementation uses dir() to get all attributes of type Param.

probabilityCol: Param[str] = Param(parent='undefined', name='probabilityCol', doc='Column name for predicted class conditional probabilities. Note: Not all models output well-calibrated probability estimates! These probabilities should be treated as confidences, not precise probabilities.')#
rawPredictionCol: Param[str] = Param(parent='undefined', name='rawPredictionCol', doc='raw prediction (a.k.a. confidence) column name.')#
seed: Param[int] = Param(parent='undefined', name='seed', doc='random seed.')#
supportedFeatureSubsetStrategies: List[str] = ['auto', 'all', 'onethird', 'sqrt', 'log2']#
supportedImpurities: List[str] = ['entropy', 'gini']#