LinearRegression#
- class spark_rapids_ml.regression.LinearRegression(*, featuresCol: Union[str, List[str]] = 'features', labelCol: str = 'label', predictionCol: str = 'prediction', maxIter: int = 100, regParam: float = 0.0, elasticNetParam: float = 0.0, tol: float = 1e-06, fitIntercept: bool = True, standardization: bool = True, solver: str = 'auto', loss: str = 'squaredError', num_workers: Optional[int] = None, verbose: Union[int, bool] = False, **kwargs: Any)#
LinearRegression is a machine learning model where the response y is modeled by a linear combination of the predictors in X. It implements cuML’s GPU accelerated LinearRegression algorithm based on cuML python library, and it can be used in PySpark Pipeline and PySpark ML meta algorithms like
CrossValidator
/TrainValidationSplit
/OneVsRest
This supports multiple types of regularization:
none (a.k.a. ordinary least squares)
L2 (ridge regression)
L1 (Lasso)
L2 + L1 (elastic net)
LinearRegression automatically supports most of the parameters from both
LinearRegression
,cuml.LinearRegression
,cuml.Ridge
,cuml.Lasso
andcuml.ElasticNet
. And it will 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.
- maxIter:
Max number of iterations (>= 0).
- regParam:
Regularization parameter (>= 0)
- elasticNetParam:
The ElasticNet mixing parameter, in range [0, 1]. For alpha = 0, the penalty is an L2 penalty. For alpha = 1, it is an L1 penalty.
- tol:
The convergence tolerance for iterative algorithms (>= 0).
- fitIntercept:
whether to fit an intercept term.
- standardization:
Whether to standardize the training features before fitting the model.
- solver:
The solver algorithm for optimization. If this is not set or empty, default value is ‘auto’.
The supported options: ‘auto’, ‘normal’ and ‘eig’, all of them will be mapped to ‘eig’ in cuML.
- loss:
The loss function to be optimized. The supported options: ‘squaredError’
- 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.
Notes
Results for spark ML and spark rapids ml fit() will currently match in all regularization cases only if features and labels are standardized in the input dataframe. Otherwise, they will match only if regParam = 0 or elastNetParam = 1.0 (aka Lasso).
Examples
>>> from spark_rapids_ml.regression import LinearRegression, LinearRegressionModel >>> from pyspark.ml.linalg import Vectors >>> >>> df = spark.createDataFrame([ ... (6.5, Vectors.dense(1.0, 2.0)), ... (3.5, Vectors.sparse(2, {1: 2}))], ["label", "features"]) >>> >>> lr = LinearRegression(regParam=0.0, solver="normal") >>> lr.setMaxIter(5) LinearRegression... >>> model = lr.fit(df) >>> model.setFeaturesCol("features") LinearRegressionModel... >>> model.setPredictionCol("newPrediction") LinearRegressionModel... >>> model.getMaxIter() 5 >>> model.coefficients [3.000000000000001, 0.0] >>> model.intercept 3.4999999999999996 >>> model.transform(df).show() +-----+----------+------------------+ |label| features| newPrediction| +-----+----------+------------------+ | 6.5|[1.0, 2.0]| 6.5| | 3.5|[0.0, 2.0]|3.4999999999999996| +-----+----------+------------------+
>>> lr_path = temp_path + "/rl" >>> lr.save(lr_path) >>> lr2 = LinearRegression.load(lr_path) >>> lr2.getMaxIter() 5 >>> model_path = temp_path + "/lr_model" >>> model.save(model_path) >>> model2 = LinearRegressionModel.load(model_path) >>> model.coefficients[0] == model2.coefficients[0] True >>> model.intercept == model2.intercept True >>> model.numFeatures 2 >>> model2.transform(df).show() +-----+----------+------------------+ |label| features| newPrediction| +-----+----------+------------------+ | 6.5|[1.0, 2.0]| 6.5| | 3.5|[0.0, 2.0]|3.4999999999999996| +-----+----------+------------------+
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.
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.
Gets the value of elasticNetParam or its default value.
Gets the value of
featuresCol
orfeaturesCols
Gets the value of featuresCols or its default value.
Gets the value of fitIntercept or its default value.
Gets the value of labelCol or its default value.
getLoss
()Gets the value of loss or its default value.
Gets the value of maxIter 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.
Gets the value of predictionCol or its default value.
Gets the value of regParam or its default value.
Gets the value of solver or its default value.
Gets the value of standardization or its default value.
getTol
()Gets the value of tol 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.
setElasticNetParam
(value)Sets the value of
elasticNetParam
.setFeaturesCol
(value)Sets the value of
featuresCol
orfeatureCols
.setFeaturesCols
(value)Sets the value of
featuresCols
.setLabelCol
(value)Sets the value of
labelCol
.setLoss
(value)Sets the value of
loss
.setMaxIter
(value)Sets the value of
maxIter
.setPredictionCol
(value)Sets the value of
predictionCol
.setRegParam
(value)Sets the value of
regParam
.setStandardization
(value)Sets the value of
standardization
.setTol
(value)Sets the value of
tol
.write
()Attributes
Returns the dictionary of parameters intended for the underlying cuML class.
Number of cuML workers, where each cuML worker corresponds to one Spark task running on one GPU.
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:
- 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: DataFrame, paramMaps: Sequence[ParamMap]) Iterator[Tuple[int, _CumlModel]] #
Fits multiple models to the input dataset for all param maps in a single pass.
- 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.
- getElasticNetParam() float #
Gets the value of elasticNetParam or its default value.
- getFeaturesCol() Union[str, List[str]] #
Gets the value of
featuresCol
orfeaturesCols
- getFeaturesCols() List[str] #
Gets the value of featuresCols or its default value.
- getFitIntercept() bool #
Gets the value of fitIntercept or its default value.
- getLabelCol() str #
Gets the value of labelCol or its default value.
- getLoss() str #
Gets the value of loss or its default value.
- getMaxIter() int #
Gets the value of maxIter or its default value.
- 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.
- getPredictionCol() str #
Gets the value of predictionCol or its default value.
- getRegParam() float #
Gets the value of regParam or its default value.
- getSolver() str #
Gets the value of solver or its default value.
- getStandardization() bool #
Gets the value of standardization or its default value.
- getTol() float #
Gets the value of tol or its 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.
- classmethod load(path: str) RL #
Reads an ML instance from the input path, a shortcut of read().load(path).
- save(path: str) None #
Save this ML instance to the given path, a shortcut of ‘write().save(path)’.
- setElasticNetParam(value: float) LinearRegression #
Sets the value of
elasticNetParam
.
- setFeaturesCol(value: Union[str, List[str]]) P #
Sets the value of
featuresCol
orfeatureCols
.
- setFeaturesCols(value: List[str]) P #
Sets the value of
featuresCols
.
- setLoss(value: str) LinearRegression #
Sets the value of
loss
.
- setMaxIter(value: int) LinearRegression #
Sets the value of
maxIter
.
- setPredictionCol(value: str) P #
Sets the value of
predictionCol
.
- setRegParam(value: float) LinearRegression #
Sets the value of
regParam
.
- setStandardization(value: bool) LinearRegression #
Sets the value of
standardization
.
- setTol(value: float) LinearRegression #
Sets the value of
tol
.
Attributes Documentation
- cuml_params#
Returns the dictionary of parameters intended for the underlying cuML class.
- elasticNetParam: Param[float] = Param(parent='undefined', name='elasticNetParam', doc='the ElasticNet mixing parameter, in range [0, 1]. For alpha = 0, the penalty is an L2 penalty. For alpha = 1, it is an L1 penalty.')#
- 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.')#
- fitIntercept: Param[bool] = Param(parent='undefined', name='fitIntercept', doc='whether to fit an intercept term.')#
- labelCol: Param[str] = Param(parent='undefined', name='labelCol', doc='label column name.')#
- loss: Param[str] = Param(parent='undefined', name='loss', doc='The loss function to be optimized. Supported options: squaredError, huber.')#
- maxIter: Param[int] = Param(parent='undefined', name='maxIter', doc='max number of iterations (>= 0).')#
- 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 typeParam
.
- predictionCol: Param[str] = Param(parent='undefined', name='predictionCol', doc='prediction column name.')#
- regParam: Param[float] = Param(parent='undefined', name='regParam', doc='regularization parameter (>= 0).')#
- solver: Param[str] = Param(parent='undefined', name='solver', doc='The solver algorithm for optimization. Supported options: auto, normal, l-bfgs.')#
- standardization: Param[bool] = Param(parent='undefined', name='standardization', doc='whether to standardize the training features before fitting the model.')#
- tol: Param[float] = Param(parent='undefined', name='tol', doc='the convergence tolerance for iterative algorithms (>= 0).')#