DBSCAN#

class spark_rapids_ml.clustering.DBSCAN(*, featuresCol: Union[str, List[str]] = 'features', predictionCol: str = 'prediction', eps: float = 0.5, min_samples: int = 5, metric: str = 'euclidean', algorithm: str = 'brute', max_mbytes_per_batch: Optional[int] = None, calc_core_sample_indices: bool = True, verbose: Union[int, bool] = False, **kwargs: Any)#

The Density-Based Spatial Clustering of Applications with Noise (DBSCAN) is a non-parametric data clustering algorithm based on data density. It groups points close to each other that form a dense cluster and mark the far-away points as noise and exclude them from all clusters.

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.

predictionCol: str

the name of the column that stores cluster indices of input vectors. predictionCol should be set when users expect to apply the transform function of a learned model.

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.

eps: float (default = 0.5)

The maximum distance between 2 points such they reside in the same neighborhood.

min_samples: int (default = 5)

The number of samples in a neighborhood such that this group can be considered as an important core point (including the point itself).

metric: {‘euclidean’, ‘cosine’}, default = ‘euclidean’

The metric to use when calculating distances between points. Spark Rapids ML does not support the ‘precomputed’ mode from sklearn and cuML, please use those libraries instead

algorithm: {‘brute’, ‘rbc’}, default = ‘brute’

The algorithm to be used by for nearest neighbor computations.

verbose: int or boolean (default=False)
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.

max_mbytes_per_batch(optional): int

Calculate batch size using no more than this number of megabytes for the pairwise distance computation. This enables the trade-off between runtime and memory usage for making the N^2 pairwise distance computations more tractable for large numbers of samples. If you are experiencing out of memory errors when running DBSCAN, you can set this value based on the memory size of your device.

calc_core_sample_indices(optional): boolean (default = True)

Indicates whether the indices of the core samples should be calculated. Setting this to False will avoid unnecessary kernel launches

idCol: str (default = ‘unique_id’)

The internal unique id column name for label matching, will not reveal in the output. Need to be set to a name that does not conflict with an existing column name in the original input data.

Examples

>>> from spark_rapids_ml.clustering import DBSCAN
>>> data = [([0.0, 0.0],),
...        ([1.0, 1.0],),
...        ([9.0, 8.0],),
...        ([8.0, 9.0],),]
>>> df = spark.createDataFrame(data, ["features"])
>>> df.show()
+----------+
|  features|
+----------+
|[0.0, 0.0]|
|[1.0, 1.0]|
|[9.0, 8.0]|
|[8.0, 9.0]|
+----------+
>>> gpu_dbscan = DBSCAN(eps=3, metric="euclidean").setFeaturesCol("features")
>>> gpu_model = gpu_dbscan.fit(df)
>>> gpu_model.setPredictionCol("prediction")
>>> transformed = gpu_model.transform(df)
>>> transformed.show()
+----------+----------+
|  features|prediction|
+----------+----------+
|[0.0, 0.0]|         0|
|[1.0, 1.0]|         0|
|[9.0, 8.0]|         1|
|[8.0, 9.0]|         1|
+----------+----------+
>>> gpu_dbscan.save("/tmp/dbscan")
>>> gpu_model.save("/tmp/dbscan_model")
>>> # vector column input
>>> from spark_rapids_ml.clustering import DBSCAN
>>> from pyspark.ml.linalg import Vectors
>>> data = [(Vectors.dense([0.0, 0.0]),),
...        (Vectors.dense([1.0, 1.0]),),
...        (Vectors.dense([9.0, 8.0]),),
...        (Vectors.dense([8.0, 9.0]),),]
>>> df = spark.createDataFrame(data, ["features"])
>>> gpu_dbscan = DBSCAN(eps=3, metric="euclidean").setFeaturesCol("features")
>>> gpu_dbscan.getFeaturesCol()
'features'
>>> gpu_model = gpu_dbscan.fit(df)
>>> # multi-column input
>>> data = [(0.0, 0.0),
...        (1.0, 1.0),
...        (9.0, 8.0),
...        (8.0, 9.0),]
>>> df = spark.createDataFrame(data, ["f1", "f2"])
>>> gpu_dbscan = DBSCAN(eps=3, metric="euclidean").setFeaturesCols(["f1", "f2"])
>>> gpu_dbscan.getFeaturesCols()
['f1', 'f2']
>>> gpu_model = gpu_dbscan.fit(df)

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.

getAlgorithm()

getCalcCoreSampleIndices()

getEps()

getFeaturesCol()

Gets the value of featuresCol or featuresCols

getFeaturesCols()

Gets the value of featuresCols or its default value.

getIdCol()

Gets the value of idCol.

getMaxMbytesPerBatch()

getMetric()

getMinSamples()

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.

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.

setAlgorithm(value)

setCalcCoreSampleIndices(value)

setEps(value)

setFeaturesCol(value)

Sets the value of featuresCol or featuresCols.

setFeaturesCols(value)

Sets the value of featuresCols.

setIdCol(value)

Sets the value of idCol.

setMaxMbytesPerBatch(value)

setMetric(value)

setMinSamples(value)

setPredictionCol(value)

Sets the value of predictionCol.

write()

Attributes

algorithm

calc_core_sample_indices

cuml_params

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

eps

featuresCol

featuresCols

idCol

max_mbytes_per_batch

metric

min_samples

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.

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.

getAlgorithm() str#
getCalcCoreSampleIndices() bool#
getEps() float#
getFeaturesCol() Union[str, List[str]]#

Gets the value of featuresCol or featuresCols

getFeaturesCols() List[str]#

Gets the value of featuresCols or its default value.

getIdCol() str#

Gets the value of idCol.

getMaxMbytesPerBatch() Optional[int]#
getMetric() str#
getMinSamples() int#
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.

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.

setAlgorithm(value: str) P#
setCalcCoreSampleIndices(value: bool) P#
setEps(value: float) P#
setFeaturesCol(value: Union[str, List[str]]) P#

Sets the value of featuresCol or featuresCols.

setFeaturesCols(value: List[str]) P#

Sets the value of featuresCols. Used when input vectors are stored as multiple feature columns.

setIdCol(value: str) P#

Sets the value of idCol. If not set, an id column will be added with column name unique_id. The id column is used to specify dbscan vectors by associated id value.

setMaxMbytesPerBatch(value: Optional[int]) P#
setMetric(value: str) P#
setMinSamples(value: int) P#
setPredictionCol(value: str) P#

Sets the value of predictionCol.

write() MLWriter#

Attributes Documentation

algorithm = Param(parent='undefined', name='algorithm', doc='The algorithm to be used by for nearest neighbor computations.')#
calc_core_sample_indices = Param(parent='undefined', name='calc_core_sample_indices', doc='Indicates whether the indices of the core samples should be calculated.Setting this to False will avoid unnecessary kernel launches')#
cuml_params#

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

eps = Param(parent='undefined', name='eps', doc='The maximum distance between 2 points such they reside in the same neighborhood.')#
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.')#
idCol = Param(parent='undefined', name='idCol', doc='id column name.')#
max_mbytes_per_batch = Param(parent='undefined', name='max_mbytes_per_batch', doc='Calculate batch size using no more than this number of megabytes for the pairwise distance computation.This enables the trade-off between runtime and memory usage for making the N^2 pairwise distance computations more tractable for large numbers of samples.If you are experiencing out of memory errors when running DBSCAN, you can set this value based on the memory size of your device.')#
metric = Param(parent='undefined', name='metric', doc="The metric to use when calculating distances between points.Spark Rapids ML does not support the 'precomputed' mode from sklearn and cuML, please use those libraries instead.")#
min_samples = Param(parent='undefined', name='min_samples', doc='The number of samples in a neighborhood such that this group can be considered as an important core point (including the point itself).')#
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.