PCA#

class spark_rapids_ml.feature.PCA(*, k: Optional[int] = None, inputCol: Optional[Union[str, List[str]]] = None, outputCol: Optional[str] = None, num_workers: Optional[int] = None, verbose: Union[int, bool] = False, **kwargs: Any)#

PCA algorithm learns principal component vectors to project high-dimensional vectors into low-dimensional vectors, while preserving the similarity of the vectors. PCA has been used in dimensionality reduction, clustering, and data visualization on large datasets. This class provides GPU acceleration for pyspark distributed PCA.

Parameters:
k: int

the number of components, or equivalently the dimension that all vectors will be projected to.

inputCol: 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.

outputCol: str

the name of the column that stores output vectors. outputCol should be set when users expect to store output vectors in a single column.

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.

Examples

>>> from spark_rapids_ml.feature import PCA
>>> data = [([1.0, 1.0],),
...         ([2.0, 2.0],),
...         ([3.0, 3.0],),]
>>> df = spark.createDataFrame(data, ["features"])
>>> gpu_pca = PCA(k=1, inputCol="features")
>>> gpu_pca.setOutputCol("pca_features")
PCA...
>>> gpu_model = gpu_pca.fit(df)
>>> gpu_model.getK()
1
>>> print(gpu_model.mean)
[2.0, 2.0]
>>> print(gpu_model.pc)
DenseMatrix([[0.70710678],
             [0.70710678]])
>>> print(gpu_model.explained_variance)
[1.0]
>>> gpu_pca.save("/tmp/pca")
>>> # vector column input
>>> from pyspark.ml.linalg import Vectors
>>> data = [(Vectors.dense([1.0, 1.0]),),
...         (Vectors.dense([2.0, 2.0]),),
...         (Vectors.dense([3.0, 3.0]),),]
>>> df = spark.createDataFrame(data, ["features"])
>>> gpu_pca = PCA(k=1).setInputCol("features")
>>> gpu_pca.getInputCol()
'features'
>>> gpu_model = gpu_pca.fit(df)
>>> # multi-column input
>>> data = [(1.0, 1.0),
...         (2.0, 2.0),
...         (3.0, 3.0),]
>>> df = spark.createDataFrame(data, ["f1", "f2"])
>>> gpu_pca = PCA(k=1).setInputCols(["f1", "f2"])
>>> gpu_pca.getInputCols()
['f1', 'f2']
>>> gpu_model = gpu_pca.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.

getInputCol()

Gets the value of inputCol or its default value.

getInputCols()

Gets the value of inputCols or its default value.

getK()

Gets the value of k or its default value.

getOrDefault(param)

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

getOutputCol()

Gets the value of outputCol 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.

setInputCol(value)

Sets the value of inputCol or inputCols.

setInputCols(value)

Sets the value of inputCols.

setK(value)

Sets the value of k.

setOutputCol(value)

Sets the value of outputCol

write()

Attributes

cuml_params

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

inputCol

inputCols

k

num_workers

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

outputCol

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.

getInputCol() str#

Gets the value of inputCol or its default value.

getInputCols() List[str]#

Gets the value of inputCols or its default value.

getK() int#

Gets the value of k or its default value.

New in version 1.5.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.

getOutputCol() str#

Gets the value of outputCol or its default value.

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.

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

Sets the value of inputCol or inputCols.

setInputCols(value: List[str]) P#

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

setK(value: int) PCA#

Sets the value of k.

setOutputCol(value: str) P#

Sets the value of outputCol

write() MLWriter#

Attributes Documentation

cuml_params#

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

inputCol: Param[str] = Param(parent='undefined', name='inputCol', doc='input column name.')#
inputCols: Param[List[str]] = Param(parent='undefined', name='inputCols', doc='input column names.')#
k: Param[int] = Param(parent='undefined', name='k', doc='the number of principal components')#
num_workers#

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

outputCol: Param[str] = Param(parent='undefined', name='outputCol', doc='output column name.')#
params#

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