TrainValidationSplit

class pyspark.ml.tuning.TrainValidationSplit(*, estimator: Optional[pyspark.ml.base.Estimator] = None, estimatorParamMaps: Optional[List[ParamMap]] = None, evaluator: Optional[pyspark.ml.evaluation.Evaluator] = None, trainRatio: float = 0.75, parallelism: int = 1, collectSubModels: bool = False, seed: Optional[int] = None)

Validation for hyper-parameter tuning. Randomly splits the input dataset into train and validation sets, and uses evaluation metric on the validation set to select the best model. Similar to CrossValidator, but only splits the set once.

Examples

>>> from pyspark.ml.classification import LogisticRegression
>>> from pyspark.ml.evaluation import BinaryClassificationEvaluator
>>> from pyspark.ml.linalg import Vectors
>>> from pyspark.ml.tuning import TrainValidationSplit, ParamGridBuilder
>>> from pyspark.ml.tuning import TrainValidationSplitModel
>>> import tempfile
>>> dataset = spark.createDataFrame(
...     [(Vectors.dense([0.0]), 0.0),
...      (Vectors.dense([0.4]), 1.0),
...      (Vectors.dense([0.5]), 0.0),
...      (Vectors.dense([0.6]), 1.0),
...      (Vectors.dense([1.0]), 1.0)] * 10,
...     ["features", "label"]).repartition(1)
>>> lr = LogisticRegression()
>>> grid = ParamGridBuilder().addGrid(lr.maxIter, [0, 1]).build()
>>> evaluator = BinaryClassificationEvaluator()
>>> tvs = TrainValidationSplit(estimator=lr, estimatorParamMaps=grid, evaluator=evaluator,
...     parallelism=1, seed=42)
>>> tvsModel = tvs.fit(dataset)
>>> tvsModel.getTrainRatio()
0.75
>>> tvsModel.validationMetrics
[0.5, ...
>>> path = tempfile.mkdtemp()
>>> model_path = path + "/model"
>>> tvsModel.write().save(model_path)
>>> tvsModelRead = TrainValidationSplitModel.read().load(model_path)
>>> tvsModelRead.validationMetrics
[0.5, ...
>>> evaluator.evaluate(tvsModel.transform(dataset))
0.833...
>>> evaluator.evaluate(tvsModelRead.transform(dataset))
0.833...

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 a randomly generated 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.

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 a model to the input dataset for each param map in paramMaps.

getCollectSubModels()

Gets the value of collectSubModels or its default value.

getEstimator()

Gets the value of estimator or its default value.

getEstimatorParamMaps()

Gets the value of estimatorParamMaps or its default value.

getEvaluator()

Gets the value of evaluator or its default value.

getOrDefault(param)

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

getParallelism()

Gets the value of parallelism or its default value.

getParam(paramName)

Gets a param by its name.

getSeed()

Gets the value of seed or its default value.

getTrainRatio()

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

setCollectSubModels(value)

Sets the value of collectSubModels.

setEstimator(value)

Sets the value of estimator.

setEstimatorParamMaps(value)

Sets the value of estimatorParamMaps.

setEvaluator(value)

Sets the value of evaluator.

setParallelism(value)

Sets the value of parallelism.

setParams(*[, estimator, …])

setParams(self, *, estimator=None, estimatorParamMaps=None, evaluator=None, trainRatio=0.75, parallelism=1, collectSubModels=False, seed=None): Sets params for the train validation split.

setSeed(value)

Sets the value of seed.

setTrainRatio(value)

Sets the value of trainRatio.

write()

Returns an MLWriter instance for this ML instance.

Attributes

collectSubModels

estimator

estimatorParamMaps

evaluator

parallelism

params

Returns all params ordered by name.

seed

trainRatio

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) → TrainValidationSplit

Creates a copy of this instance with a randomly generated uid and some extra params. This copies creates a deep copy of the embedded paramMap, and copies the embedded and extra parameters over.

Parameters
extradict, optional

Extra parameters to copy to the new instance

Returns
TrainValidationSplit

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.

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: pyspark.sql.dataframe.DataFrame, paramMaps: Sequence[ParamMap]) → Iterator[Tuple[int, M]]

Fits a model to the input dataset for each param map in paramMaps.

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.

getCollectSubModels() → bool

Gets the value of collectSubModels or its default value.

getEstimator() → pyspark.ml.base.Estimator

Gets the value of estimator or its default value.

getEstimatorParamMaps() → List[ParamMap]

Gets the value of estimatorParamMaps or its default value.

getEvaluator()pyspark.ml.evaluation.Evaluator

Gets the value of evaluator or its default value.

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.

getParallelism() → int

Gets the value of parallelism or its default value.

getParam(paramName: str)pyspark.ml.param.Param

Gets a param by its name.

getSeed() → int

Gets the value of seed or its default value.

getTrainRatio() → float

Gets the value of trainRatio 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.tuning.TrainValidationSplitReader

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.

setCollectSubModels(value: bool)pyspark.ml.tuning.TrainValidationSplit

Sets the value of collectSubModels.

setEstimator(value: pyspark.ml.base.Estimator)pyspark.ml.tuning.TrainValidationSplit

Sets the value of estimator.

setEstimatorParamMaps(value: List[ParamMap]) → TrainValidationSplit

Sets the value of estimatorParamMaps.

setEvaluator(value: pyspark.ml.evaluation.Evaluator)pyspark.ml.tuning.TrainValidationSplit

Sets the value of evaluator.

setParallelism(value: int)pyspark.ml.tuning.TrainValidationSplit

Sets the value of parallelism.

setParams(*, estimator: Optional[pyspark.ml.base.Estimator] = None, estimatorParamMaps: Optional[List[ParamMap]] = None, evaluator: Optional[pyspark.ml.evaluation.Evaluator] = None, trainRatio: float = 0.75, parallelism: int = 1, collectSubModels: bool = False, seed: Optional[int] = None) → TrainValidationSplit

setParams(self, *, estimator=None, estimatorParamMaps=None, evaluator=None, trainRatio=0.75, parallelism=1, collectSubModels=False, seed=None): Sets params for the train validation split.

setSeed(value: int)pyspark.ml.tuning.TrainValidationSplit

Sets the value of seed.

setTrainRatio(value: float)pyspark.ml.tuning.TrainValidationSplit

Sets the value of trainRatio.

write()pyspark.ml.util.MLWriter

Returns an MLWriter instance for this ML instance.

Attributes Documentation

collectSubModels = Param(parent='undefined', name='collectSubModels', doc='Param for whether to collect a list of sub-models trained during tuning. If set to false, then only the single best sub-model will be available after fitting. If set to true, then all sub-models will be available. Warning: For large models, collecting all sub-models can cause OOMs on the Spark driver.')
estimator = Param(parent='undefined', name='estimator', doc='estimator to be cross-validated')
estimatorParamMaps = Param(parent='undefined', name='estimatorParamMaps', doc='estimator param maps')
evaluator = Param(parent='undefined', name='evaluator', doc='evaluator used to select hyper-parameters that maximize the validator metric')
parallelism = Param(parent='undefined', name='parallelism', doc='the number of threads to use when running parallel algorithms (>= 1).')
params

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

seed = Param(parent='undefined', name='seed', doc='random seed.')
trainRatio = Param(parent='undefined', name='trainRatio', doc='Param for ratio between train and validation data. Must be between 0 and 1.')