This is an automated email from the ASF dual-hosted git repository.
zhengruifeng pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/spark.git
The following commit(s) were added to refs/heads/master by this push:
new 59aaad0d641e [SPARK-61361][ML][PYTHON] Support configurable
intermediate storage levels in tree estimators
59aaad0d641e is described below
commit 59aaad0d641ee1869d5e7be22caf6faaa4afba6c
Author: Ruifeng Zheng <[email protected]>
AuthorDate: Wed Nov 11 08:51:09 2026 +0800
[SPARK-61361][ML][PYTHON] Support configurable intermediate storage levels
in tree estimators
### What changes were proposed in this pull request?
Add `intermediateStorageLevel` to the decision tree, random forest, and GBT
classifiers and regressors in Scala and PySpark. Apply it to intermediate
training data, node-ID caches, and GBT validation and prediction/error caches.
PySpark accepts the parameter in constructors, `setParams`, and setters.
### Why are the changes needed?
These estimators create cached RDDs internally, so persisting the input
DataFrame does not configure their storage. Users can now choose a level such
as `DISK_ONLY` to reduce memory pressure.
### Does this PR introduce _any_ user-facing change?
Yes. All six estimators expose `intermediateStorageLevel`. The default
remains `MEMORY_AND_DISK`; the existing shared validator rejects `NONE` and
invalid storage levels.
### How was this patch tested?
- All 104 tests in the six existing Scala estimator suites passed, along
with source/test style checks and MLlib MiMa.
- Extended existing Scala tests with simple getter/setter checks and
existing PySpark tests with constructor, `setParams`, setter, and
model-parameter checks.
- All 13 focused classic PySpark, Spark Connect, and Java/Python
parameter-parity checks passed.
- A Scala smoke check observed `DISK_ONLY` cached RDDs for all six
estimators with node caching and checkpointing enabled, including GBT
validation.
- Python lint and formatting checks passed.
### Was this patch authored or co-authored using generative AI tooling?
Generated-by: Codex (GPT-6)
Closes #60299 from zhengruifeng/tree-intermediate-storage.
Authored-by: Ruifeng Zheng <[email protected]>
Signed-off-by: Ruifeng Zheng <[email protected]>
skip-checks: true
---
.../ml/classification/DecisionTreeClassifier.scala | 11 +++++-
.../spark/ml/classification/GBTClassifier.scala | 13 +++++--
.../ml/classification/RandomForestClassifier.scala | 11 +++++-
.../ml/regression/DecisionTreeRegressor.scala | 8 +++-
.../apache/spark/ml/regression/GBTRegressor.scala | 12 ++++--
.../ml/regression/RandomForestRegressor.scala | 10 ++++-
.../spark/ml/tree/impl/GradientBoostedTrees.scala | 35 +++++++++--------
.../apache/spark/ml/tree/impl/RandomForest.scala | 15 +++++---
.../org/apache/spark/ml/tree/treeParams.scala | 2 +-
.../DecisionTreeClassifierSuite.scala | 6 ++-
.../ml/classification/GBTClassifierSuite.scala | 6 ++-
.../RandomForestClassifierSuite.scala | 6 ++-
.../ml/regression/DecisionTreeRegressorSuite.scala | 3 ++
.../spark/ml/regression/GBTRegressorSuite.scala | 3 ++
.../ml/regression/RandomForestRegressorSuite.scala | 3 ++
python/pyspark/ml/classification.py | 45 +++++++++++++++++++---
python/pyspark/ml/regression.py | 45 +++++++++++++++++++---
python/pyspark/ml/tests/test_classification.py | 24 ++++++++++++
python/pyspark/ml/tests/test_regression.py | 24 ++++++++++++
python/pyspark/ml/tree.py | 5 ++-
20 files changed, 237 insertions(+), 50 deletions(-)
diff --git
a/mllib/src/main/scala/org/apache/spark/ml/classification/DecisionTreeClassifier.scala
b/mllib/src/main/scala/org/apache/spark/ml/classification/DecisionTreeClassifier.scala
index d83df697a04a..fa0fc8dc9d03 100644
---
a/mllib/src/main/scala/org/apache/spark/ml/classification/DecisionTreeClassifier.scala
+++
b/mllib/src/main/scala/org/apache/spark/ml/classification/DecisionTreeClassifier.scala
@@ -37,6 +37,7 @@ import org.apache.spark.mllib.tree.model.{DecisionTreeModel
=> OldDecisionTreeMo
import org.apache.spark.sql._
import org.apache.spark.sql.functions.{col, udf}
import org.apache.spark.sql.types.StructType
+import org.apache.spark.storage.StorageLevel
/**
* Decision tree learning algorithm
(http://en.wikipedia.org/wiki/Decision_tree_learning)
@@ -98,6 +99,10 @@ class DecisionTreeClassifier @Since("1.4.0") (
@Since("1.4.0")
def setCheckpointInterval(value: Int): this.type = set(checkpointInterval,
value)
+ /** @group expertSetParam */
+ @Since("4.4.0")
+ def setIntermediateStorageLevel(value: String): this.type =
set(intermediateStorageLevel, value)
+
/** @group setParam */
@Since("1.4.0")
def setImpurity(value: String): this.type = set(impurity, value)
@@ -143,10 +148,12 @@ class DecisionTreeClassifier @Since("1.4.0") (
instr.logNumClasses(numClasses)
instr.logParams(this, labelCol, featuresCol, predictionCol,
rawPredictionCol,
probabilityCol, leafCol, maxDepth, maxBins, minInstancesPerNode,
minInfoGain, pruneTree,
- maxMemoryInMB, cacheNodeIds, checkpointInterval, impurity, seed,
thresholds)
+ maxMemoryInMB, cacheNodeIds, checkpointInterval, impurity, seed,
thresholds,
+ intermediateStorageLevel)
val trees = RandomForest.run(instances, strategy, numTrees = 1,
featureSubsetStrategy = "all",
- seed = $(seed), instr = Some(instr), parentUID = Some(uid))
+ seed = $(seed), instr = Some(instr), parentUID = Some(uid),
+ intermediateStorageLevel =
StorageLevel.fromString($(intermediateStorageLevel)))
trees.head.asInstanceOf[DecisionTreeClassificationModel]
}
diff --git
a/mllib/src/main/scala/org/apache/spark/ml/classification/GBTClassifier.scala
b/mllib/src/main/scala/org/apache/spark/ml/classification/GBTClassifier.scala
index 05e3d0ab2665..17aba9724fe2 100644
---
a/mllib/src/main/scala/org/apache/spark/ml/classification/GBTClassifier.scala
+++
b/mllib/src/main/scala/org/apache/spark/ml/classification/GBTClassifier.scala
@@ -37,6 +37,7 @@ import
org.apache.spark.mllib.tree.model.{GradientBoostedTreesModel => OldGBTMod
import org.apache.spark.sql._
import org.apache.spark.sql.functions._
import org.apache.spark.sql.types.StructType
+import org.apache.spark.storage.StorageLevel
/**
* Gradient-Boosted Trees (GBTs)
(http://en.wikipedia.org/wiki/Gradient_boosting)
@@ -108,6 +109,10 @@ class GBTClassifier @Since("1.4.0") (
@Since("1.4.0")
def setCheckpointInterval(value: Int): this.type = set(checkpointInterval,
value)
+ /** @group expertSetParam */
+ @Since("4.4.0")
+ def setIntermediateStorageLevel(value: String): this.type =
set(intermediateStorageLevel, value)
+
/**
* The impurity setting is ignored for GBT models.
* Individual trees are built using impurity "Variance."
@@ -189,17 +194,19 @@ class GBTClassifier @Since("1.4.0") (
instr.logParams(this, labelCol, weightCol, featuresCol, predictionCol,
leafCol,
impurity, lossType, maxDepth, maxBins, maxIter, maxMemoryInMB,
minInfoGain,
minInstancesPerNode, minWeightFractionPerNode, seed, stepSize,
subsamplingRate, cacheNodeIds,
- checkpointInterval, featureSubsetStrategy, validationIndicatorCol,
validationTol, thresholds)
+ checkpointInterval, featureSubsetStrategy, validationIndicatorCol,
validationTol,
+ thresholds, intermediateStorageLevel)
instr.logNumClasses(numClasses)
val categoricalFeatures =
MetadataUtils.getCategoricalFeatures(dataset.schema($(featuresCol)))
val boostingStrategy = super.getOldBoostingStrategy(categoricalFeatures,
OldAlgo.Classification)
+ val storageLevel = StorageLevel.fromString($(intermediateStorageLevel))
val (baseLearners, learnerWeights) = if (withValidation) {
GradientBoostedTrees.runWithValidation(trainDataset, validationDataset,
boostingStrategy,
- $(seed), $(featureSubsetStrategy), Some(instr))
+ $(seed), $(featureSubsetStrategy), Some(instr), storageLevel)
} else {
GradientBoostedTrees.run(trainDataset, boostingStrategy, $(seed),
$(featureSubsetStrategy),
- Some(instr))
+ Some(instr), storageLevel)
}
baseLearners.foreach(copyValues(_))
diff --git
a/mllib/src/main/scala/org/apache/spark/ml/classification/RandomForestClassifier.scala
b/mllib/src/main/scala/org/apache/spark/ml/classification/RandomForestClassifier.scala
index 26c5e2fc856d..6e42a5064db2 100644
---
a/mllib/src/main/scala/org/apache/spark/ml/classification/RandomForestClassifier.scala
+++
b/mllib/src/main/scala/org/apache/spark/ml/classification/RandomForestClassifier.scala
@@ -36,6 +36,7 @@ import org.apache.spark.mllib.tree.model.{RandomForestModel
=> OldRandomForestMo
import org.apache.spark.sql._
import org.apache.spark.sql.functions.{col, udf}
import org.apache.spark.sql.types.StructType
+import org.apache.spark.storage.StorageLevel
/**
* <a href="http://en.wikipedia.org/wiki/Random_forest">Random Forest</a>
learning algorithm for
@@ -100,6 +101,10 @@ class RandomForestClassifier @Since("1.4.0") (
@Since("1.4.0")
def setCheckpointInterval(value: Int): this.type = set(checkpointInterval,
value)
+ /** @group expertSetParam */
+ @Since("4.4.0")
+ def setIntermediateStorageLevel(value: String): this.type =
set(intermediateStorageLevel, value)
+
/** @group setParam */
@Since("1.4.0")
def setImpurity(value: String): this.type = set(impurity, value)
@@ -168,10 +173,12 @@ class RandomForestClassifier @Since("1.4.0") (
instr.logParams(this, labelCol, featuresCol, weightCol, predictionCol,
probabilityCol,
rawPredictionCol, leafCol, impurity, numTrees, featureSubsetStrategy,
maxDepth, maxBins,
maxMemoryInMB, minInfoGain, pruneTree, minInstancesPerNode,
minWeightFractionPerNode, seed,
- subsamplingRate, thresholds, cacheNodeIds, checkpointInterval, bootstrap)
+ subsamplingRate, thresholds, cacheNodeIds, checkpointInterval, bootstrap,
+ intermediateStorageLevel)
val trees = RandomForest
- .run(instances, strategy, getNumTrees, getFeatureSubsetStrategy,
getSeed, Some(instr))
+ .run(instances, strategy, getNumTrees, getFeatureSubsetStrategy,
getSeed, Some(instr),
+ intermediateStorageLevel =
StorageLevel.fromString($(intermediateStorageLevel)))
.map(_.asInstanceOf[DecisionTreeClassificationModel])
trees.foreach(copyValues(_))
diff --git
a/mllib/src/main/scala/org/apache/spark/ml/regression/DecisionTreeRegressor.scala
b/mllib/src/main/scala/org/apache/spark/ml/regression/DecisionTreeRegressor.scala
index dc9af406697b..d2fba954c5d7 100644
---
a/mllib/src/main/scala/org/apache/spark/ml/regression/DecisionTreeRegressor.scala
+++
b/mllib/src/main/scala/org/apache/spark/ml/regression/DecisionTreeRegressor.scala
@@ -37,6 +37,7 @@ import org.apache.spark.mllib.tree.model.{DecisionTreeModel
=> OldDecisionTreeMo
import org.apache.spark.sql._
import org.apache.spark.sql.functions._
import org.apache.spark.sql.types.StructType
+import org.apache.spark.storage.StorageLevel
/**
* <a href="http://en.wikipedia.org/wiki/Decision_tree_learning">Decision
tree</a>
@@ -91,6 +92,10 @@ class DecisionTreeRegressor @Since("1.4.0") (@Since("1.4.0")
override val uid: S
@Since("1.4.0")
def setCheckpointInterval(value: Int): this.type = set(checkpointInterval,
value)
+ /** @group expertSetParam */
+ @Since("4.4.0")
+ def setIntermediateStorageLevel(value: String): this.type =
set(intermediateStorageLevel, value)
+
/** @group setParam */
@Since("1.4.0")
def setImpurity(value: String): this.type = set(impurity, value)
@@ -134,7 +139,8 @@ class DecisionTreeRegressor @Since("1.4.0")
(@Since("1.4.0") override val uid: S
instr.logParams(this, params.toImmutableArraySeq: _*)
val trees = RandomForest.run(instances, strategy, numTrees = 1,
featureSubsetStrategy = "all",
- seed = $(seed), instr = Some(instr), parentUID = Some(uid))
+ seed = $(seed), instr = Some(instr), parentUID = Some(uid),
+ intermediateStorageLevel =
StorageLevel.fromString($(intermediateStorageLevel)))
trees.head.asInstanceOf[DecisionTreeRegressionModel]
}
diff --git
a/mllib/src/main/scala/org/apache/spark/ml/regression/GBTRegressor.scala
b/mllib/src/main/scala/org/apache/spark/ml/regression/GBTRegressor.scala
index c33ce2552b09..0ceb91f783fa 100644
--- a/mllib/src/main/scala/org/apache/spark/ml/regression/GBTRegressor.scala
+++ b/mllib/src/main/scala/org/apache/spark/ml/regression/GBTRegressor.scala
@@ -35,6 +35,7 @@ import
org.apache.spark.mllib.tree.model.{GradientBoostedTreesModel => OldGBTMod
import org.apache.spark.sql._
import org.apache.spark.sql.functions._
import org.apache.spark.sql.types.StructType
+import org.apache.spark.storage.StorageLevel
/**
* <a href="http://en.wikipedia.org/wiki/Gradient_boosting">Gradient-Boosted
Trees (GBTs)</a>
@@ -105,6 +106,10 @@ class GBTRegressor @Since("1.4.0") (@Since("1.4.0")
override val uid: String)
@Since("1.4.0")
def setCheckpointInterval(value: Int): this.type = set(checkpointInterval,
value)
+ /** @group expertSetParam */
+ @Since("4.4.0")
+ def setIntermediateStorageLevel(value: String): this.type =
set(intermediateStorageLevel, value)
+
/**
* The impurity setting is ignored for GBT models.
* Individual trees are built using impurity "Variance."
@@ -178,16 +183,17 @@ class GBTRegressor @Since("1.4.0") (@Since("1.4.0")
override val uid: String)
instr.logParams(this, labelCol, featuresCol, predictionCol, leafCol,
weightCol, impurity,
lossType, maxDepth, maxBins, maxIter, maxMemoryInMB, minInfoGain,
minInstancesPerNode,
minWeightFractionPerNode, seed, stepSize, subsamplingRate, cacheNodeIds,
checkpointInterval,
- featureSubsetStrategy, validationIndicatorCol, validationTol)
+ featureSubsetStrategy, validationIndicatorCol, validationTol,
intermediateStorageLevel)
val categoricalFeatures =
MetadataUtils.getCategoricalFeatures(dataset.schema($(featuresCol)))
val boostingStrategy = super.getOldBoostingStrategy(categoricalFeatures,
OldAlgo.Regression)
+ val storageLevel = StorageLevel.fromString($(intermediateStorageLevel))
val (baseLearners, learnerWeights) = if (withValidation) {
GradientBoostedTrees.runWithValidation(trainDataset, validationDataset,
boostingStrategy,
- $(seed), $(featureSubsetStrategy), Some(instr))
+ $(seed), $(featureSubsetStrategy), Some(instr), storageLevel)
} else {
GradientBoostedTrees.run(trainDataset, boostingStrategy,
- $(seed), $(featureSubsetStrategy), Some(instr))
+ $(seed), $(featureSubsetStrategy), Some(instr), storageLevel)
}
baseLearners.foreach(copyValues(_))
diff --git
a/mllib/src/main/scala/org/apache/spark/ml/regression/RandomForestRegressor.scala
b/mllib/src/main/scala/org/apache/spark/ml/regression/RandomForestRegressor.scala
index c642568b73f2..dcc31a4609cb 100644
---
a/mllib/src/main/scala/org/apache/spark/ml/regression/RandomForestRegressor.scala
+++
b/mllib/src/main/scala/org/apache/spark/ml/regression/RandomForestRegressor.scala
@@ -36,6 +36,7 @@ import org.apache.spark.mllib.tree.model.{RandomForestModel
=> OldRandomForestMo
import org.apache.spark.sql._
import org.apache.spark.sql.functions.{col, udf}
import org.apache.spark.sql.types.StructType
+import org.apache.spark.storage.StorageLevel
/**
* <a href="http://en.wikipedia.org/wiki/Random_forest">Random Forest</a>
@@ -94,6 +95,10 @@ class RandomForestRegressor @Since("1.4.0") (@Since("1.4.0")
override val uid: S
@Since("1.4.0")
def setCheckpointInterval(value: Int): this.type = set(checkpointInterval,
value)
+ /** @group expertSetParam */
+ @Since("4.4.0")
+ def setIntermediateStorageLevel(value: String): this.type =
set(intermediateStorageLevel, value)
+
/** @group setParam */
@Since("1.4.0")
def setImpurity(value: String): this.type = set(impurity, value)
@@ -154,10 +159,11 @@ class RandomForestRegressor @Since("1.4.0")
(@Since("1.4.0") override val uid: S
instr.logParams(this, labelCol, featuresCol, weightCol, predictionCol,
leafCol, impurity,
numTrees, featureSubsetStrategy, maxDepth, maxBins, maxMemoryInMB,
minInfoGain,
minInstancesPerNode, minWeightFractionPerNode, seed, subsamplingRate,
cacheNodeIds,
- checkpointInterval, bootstrap)
+ checkpointInterval, bootstrap, intermediateStorageLevel)
val trees = RandomForest
- .run(instances, strategy, getNumTrees, getFeatureSubsetStrategy,
getSeed, Some(instr))
+ .run(instances, strategy, getNumTrees, getFeatureSubsetStrategy,
getSeed, Some(instr),
+ intermediateStorageLevel =
StorageLevel.fromString($(intermediateStorageLevel)))
.map(_.asInstanceOf[DecisionTreeRegressionModel])
trees.foreach(copyValues(_))
diff --git
a/mllib/src/main/scala/org/apache/spark/ml/tree/impl/GradientBoostedTrees.scala
b/mllib/src/main/scala/org/apache/spark/ml/tree/impl/GradientBoostedTrees.scala
index 81ffa5c86a9f..788a517af917 100644
---
a/mllib/src/main/scala/org/apache/spark/ml/tree/impl/GradientBoostedTrees.scala
+++
b/mllib/src/main/scala/org/apache/spark/ml/tree/impl/GradientBoostedTrees.scala
@@ -49,18 +49,19 @@ private[spark] object GradientBoostedTrees extends Logging {
boostingStrategy: OldBoostingStrategy,
seed: Long,
featureSubsetStrategy: String,
- instr: Option[Instrumentation] = None):
+ instr: Option[Instrumentation] = None,
+ intermediateStorageLevel: StorageLevel = StorageLevel.MEMORY_AND_DISK):
(Array[DecisionTreeRegressionModel], Array[Double]) = {
val algo = boostingStrategy.treeStrategy.algo
algo match {
case OldAlgo.Regression =>
GradientBoostedTrees.boost(input, input, boostingStrategy, validate =
false,
- seed, featureSubsetStrategy, instr)
+ seed, featureSubsetStrategy, instr, intermediateStorageLevel)
case OldAlgo.Classification =>
// Map labels to -1, +1 so binary classification can be treated as
regression.
val remappedInput = input.map(x => Instance((x.label * 2) - 1,
x.weight, x.features))
GradientBoostedTrees.boost(remappedInput, remappedInput,
boostingStrategy, validate = false,
- seed, featureSubsetStrategy, instr)
+ seed, featureSubsetStrategy, instr, intermediateStorageLevel)
case _ =>
throw new IllegalArgumentException(s"$algo is not supported by
gradient boosting.")
}
@@ -84,13 +85,14 @@ private[spark] object GradientBoostedTrees extends Logging {
boostingStrategy: OldBoostingStrategy,
seed: Long,
featureSubsetStrategy: String,
- instr: Option[Instrumentation] = None):
+ instr: Option[Instrumentation] = None,
+ intermediateStorageLevel: StorageLevel = StorageLevel.MEMORY_AND_DISK):
(Array[DecisionTreeRegressionModel], Array[Double]) = {
val algo = boostingStrategy.treeStrategy.algo
algo match {
case OldAlgo.Regression =>
GradientBoostedTrees.boost(input, validationInput, boostingStrategy,
- validate = true, seed, featureSubsetStrategy, instr)
+ validate = true, seed, featureSubsetStrategy, instr,
intermediateStorageLevel)
case OldAlgo.Classification =>
// Map labels to -1, +1 so binary classification can be treated as
regression.
val remappedInput = input.map(
@@ -98,7 +100,7 @@ private[spark] object GradientBoostedTrees extends Logging {
val remappedValidationInput = validationInput.map(
x => Instance((x.label * 2) - 1, x.weight, x.features))
GradientBoostedTrees.boost(remappedInput, remappedValidationInput,
boostingStrategy,
- validate = true, seed, featureSubsetStrategy, instr)
+ validate = true, seed, featureSubsetStrategy, instr,
intermediateStorageLevel)
case _ =>
throw new IllegalArgumentException(s"$algo is not supported by the
gradient boosting.")
}
@@ -294,7 +296,8 @@ private[spark] object GradientBoostedTrees extends Logging {
validate: Boolean,
seed: Long,
featureSubsetStrategy: String,
- instr: Option[Instrumentation] = None):
+ instr: Option[Instrumentation] = None,
+ intermediateStorageLevel: StorageLevel = StorageLevel.MEMORY_AND_DISK):
(Array[DecisionTreeRegressionModel], Array[Double]) = {
val earlyStopModelSizeThresholdInBytes =
TreeConfig.trainingEarlyStopModelSizeThresholdInBytes
lastEarlyStoppedModelSize = 0
@@ -324,7 +327,7 @@ private[spark] object GradientBoostedTrees extends Logging {
// Prepare periodic checkpointers
// Note: this is checkpointing the unweighted training error
val predErrorCheckpointer = new PeriodicRDDCheckpointer[(Double, Double)](
- treeStrategy.getCheckpointInterval(), sc, StorageLevel.MEMORY_AND_DISK)
+ treeStrategy.getCheckpointInterval(), sc, intermediateStorageLevel)
timer.stop("init")
@@ -349,7 +352,7 @@ private[spark] object GradientBoostedTrees extends Logging {
// Cache input RDD for speedup during multiple passes.
val treePoints = TreePoint.convertToTreeRDD(
retaggedInput, splits, metadata)
- .persist(StorageLevel.MEMORY_AND_DISK)
+ .persist(intermediateStorageLevel)
.setName("binned tree points")
val firstCounts = BaggedPoint
@@ -359,7 +362,7 @@ private[spark] object GradientBoostedTrees extends Logging {
require(bagged.subsampleCounts.length == 1)
require(bagged.sampleWeight == bagged.datum.weight)
bagged.subsampleCounts.head
- }.persist(StorageLevel.MEMORY_AND_DISK)
+ }.persist(intermediateStorageLevel)
.setName("firstCounts at iter=0")
val firstBagged = treePoints.zip(firstCounts)
@@ -372,7 +375,8 @@ private[spark] object GradientBoostedTrees extends Logging {
metadata = metadata, bcSplits = bcSplits, strategy = treeStrategy,
numTrees = 1,
featureSubsetStrategy = featureSubsetStrategy, seed = seed, instr =
instr,
parentUID = None,
- earlyStopModelSizeThresholdInBytes = earlyStopModelSizeThresholdInBytes)
+ earlyStopModelSizeThresholdInBytes = earlyStopModelSizeThresholdInBytes,
+ intermediateStorageLevel = intermediateStorageLevel)
.head.asInstanceOf[DecisionTreeRegressionModel]
firstCounts.unpersist()
@@ -397,11 +401,11 @@ private[spark] object GradientBoostedTrees extends
Logging {
timer.start("init validation")
validationTreePoints = TreePoint.convertToTreeRDD(
validationInput.retag(classOf[Instance]), splits, metadata)
- .persist(StorageLevel.MEMORY_AND_DISK)
+ .persist(intermediateStorageLevel)
validatePredError = computeInitialPredictionAndError(
validationTreePoints, firstTreeWeight, firstTreeModel, loss, bcSplits)
validatePredErrorCheckpointer = new PeriodicRDDCheckpointer[(Double,
Double)](
- treeStrategy.getCheckpointInterval(), sc, StorageLevel.MEMORY_AND_DISK)
+ treeStrategy.getCheckpointInterval(), sc, intermediateStorageLevel)
validatePredErrorCheckpointer.update(validatePredError)
bestValidateError = computeWeightedError(validationTreePoints,
validatePredError)
timer.stop("init validation")
@@ -437,7 +441,7 @@ private[spark] object GradientBoostedTrees extends Logging {
// Update labels with pseudo-residuals
val newLabel = -loss.gradient(pred, bagged.datum.label)
(newLabel, bagged.subsampleCounts.head)
- }.persist(StorageLevel.MEMORY_AND_DISK)
+ }.persist(intermediateStorageLevel)
.setName(s"labelWithCounts at iter=$m")
val bagged = treePoints.zip(labelWithCounts)
@@ -451,7 +455,8 @@ private[spark] object GradientBoostedTrees extends Logging {
metadata = metadata, bcSplits = bcSplits, strategy = treeStrategy,
numTrees = 1, featureSubsetStrategy = featureSubsetStrategy,
seed = seed + m, instr = None, parentUID = None,
- earlyStopModelSizeThresholdInBytes =
earlyStopModelSizeThresholdInBytes - accTreeSize)
+ earlyStopModelSizeThresholdInBytes =
earlyStopModelSizeThresholdInBytes - accTreeSize,
+ intermediateStorageLevel = intermediateStorageLevel)
.head.asInstanceOf[DecisionTreeRegressionModel]
labelWithCounts.unpersist()
diff --git
a/mllib/src/main/scala/org/apache/spark/ml/tree/impl/RandomForest.scala
b/mllib/src/main/scala/org/apache/spark/ml/tree/impl/RandomForest.scala
index b3ca7f04c3de..527c8c05e2f5 100644
--- a/mllib/src/main/scala/org/apache/spark/ml/tree/impl/RandomForest.scala
+++ b/mllib/src/main/scala/org/apache/spark/ml/tree/impl/RandomForest.scala
@@ -125,7 +125,9 @@ private[spark] object RandomForest extends Logging with
Serializable {
seed: Long,
instr: Option[Instrumentation],
parentUID: Option[String] = None,
- earlyStopModelSizeThresholdInBytes: Long = 0): Array[DecisionTreeModel]
= {
+ earlyStopModelSizeThresholdInBytes: Long = 0,
+ intermediateStorageLevel: StorageLevel = StorageLevel.MEMORY_AND_DISK):
+ Array[DecisionTreeModel] = {
lastEarlyStoppedModelSize = 0
val timer = new TimeTracker()
timer.start("total")
@@ -173,7 +175,7 @@ private[spark] object RandomForest extends Logging with
Serializable {
// At first, all the rows belong to the root nodes (node Id == 1).
nodeIds = baggedInput.map { _ => Array.fill(numTrees)(1) }
nodeIdCheckpointer = new PeriodicRDDCheckpointer[Array[Int]](
- strategy.getCheckpointInterval(), sc, StorageLevel.MEMORY_AND_DISK)
+ strategy.getCheckpointInterval(), sc, intermediateStorageLevel)
nodeIdCheckpointer.update(nodeIds)
}
@@ -307,7 +309,9 @@ private[spark] object RandomForest extends Logging with
Serializable {
featureSubsetStrategy: String,
seed: Long,
instr: Option[Instrumentation],
- parentUID: Option[String] = None): Array[DecisionTreeModel] = {
+ parentUID: Option[String] = None,
+ intermediateStorageLevel: StorageLevel = StorageLevel.MEMORY_AND_DISK):
+ Array[DecisionTreeModel] = {
val earlyStopModelSizeThresholdInBytes =
TreeConfig.trainingEarlyStopModelSizeThresholdInBytes
val timer = new TimeTracker()
@@ -344,7 +348,7 @@ private[spark] object RandomForest extends Logging with
Serializable {
strategy.bootstrap,
(tp: TreePoint) => tp.weight,
seed = seed)
- .persist(StorageLevel.MEMORY_AND_DISK)
+ .persist(intermediateStorageLevel)
.setName("bagged tree points")
val trees = runBagged(
@@ -357,7 +361,8 @@ private[spark] object RandomForest extends Logging with
Serializable {
seed = seed,
instr = instr,
parentUID = parentUID,
- earlyStopModelSizeThresholdInBytes = earlyStopModelSizeThresholdInBytes)
+ earlyStopModelSizeThresholdInBytes = earlyStopModelSizeThresholdInBytes,
+ intermediateStorageLevel = intermediateStorageLevel)
baggedInput.unpersist()
bcSplits.destroy()
diff --git a/mllib/src/main/scala/org/apache/spark/ml/tree/treeParams.scala
b/mllib/src/main/scala/org/apache/spark/ml/tree/treeParams.scala
index 08dd0039a991..6ef79161146e 100644
--- a/mllib/src/main/scala/org/apache/spark/ml/tree/treeParams.scala
+++ b/mllib/src/main/scala/org/apache/spark/ml/tree/treeParams.scala
@@ -39,7 +39,7 @@ import org.apache.spark.sql.types.{DataType, DoubleType,
StructType}
* Note: Marked as private since this may be made public in the future.
*/
private[ml] trait DecisionTreeParams extends PredictorParams
- with HasCheckpointInterval with HasSeed with HasWeightCol {
+ with HasCheckpointInterval with HasSeed with HasWeightCol with
HasIntermediateStorageLevel {
/**
* Leaf indices column name.
diff --git
a/mllib/src/test/scala/org/apache/spark/ml/classification/DecisionTreeClassifierSuite.scala
b/mllib/src/test/scala/org/apache/spark/ml/classification/DecisionTreeClassifierSuite.scala
index db498cf2d6dc..523f3d724c1f 100644
---
a/mllib/src/test/scala/org/apache/spark/ml/classification/DecisionTreeClassifierSuite.scala
+++
b/mllib/src/test/scala/org/apache/spark/ml/classification/DecisionTreeClassifierSuite.scala
@@ -73,7 +73,11 @@ class DecisionTreeClassifierSuite extends MLTest with
DefaultReadWriteTest {
}
test("params") {
- ParamsSuite.checkParams(new DecisionTreeClassifier)
+ val classifier = new DecisionTreeClassifier
+ ParamsSuite.checkParams(classifier)
+ assert(classifier.getIntermediateStorageLevel === "MEMORY_AND_DISK")
+ classifier.setIntermediateStorageLevel("DISK_ONLY")
+ assert(classifier.getIntermediateStorageLevel === "DISK_ONLY")
val model = new DecisionTreeClassificationModel("dtc", new LeafNode(0.0,
0.0, null), 1, 2)
ParamsSuite.checkParams(model)
}
diff --git
a/mllib/src/test/scala/org/apache/spark/ml/classification/GBTClassifierSuite.scala
b/mllib/src/test/scala/org/apache/spark/ml/classification/GBTClassifierSuite.scala
index 6ce2108b1f7c..e6e096d51fc2 100644
---
a/mllib/src/test/scala/org/apache/spark/ml/classification/GBTClassifierSuite.scala
+++
b/mllib/src/test/scala/org/apache/spark/ml/classification/GBTClassifierSuite.scala
@@ -75,7 +75,11 @@ class GBTClassifierSuite extends MLTest with
DefaultReadWriteTest {
}
test("params") {
- ParamsSuite.checkParams(new GBTClassifier)
+ val classifier = new GBTClassifier
+ ParamsSuite.checkParams(classifier)
+ assert(classifier.getIntermediateStorageLevel === "MEMORY_AND_DISK")
+ classifier.setIntermediateStorageLevel("DISK_ONLY")
+ assert(classifier.getIntermediateStorageLevel === "DISK_ONLY")
val model = new GBTClassificationModel("gbtc",
Array(new DecisionTreeRegressionModel("dtr", new LeafNode(0.0, 0.0,
null), 1)),
Array(1.0), 1, 2)
diff --git
a/mllib/src/test/scala/org/apache/spark/ml/classification/RandomForestClassifierSuite.scala
b/mllib/src/test/scala/org/apache/spark/ml/classification/RandomForestClassifierSuite.scala
index 562cccedeef4..a446622797f3 100644
---
a/mllib/src/test/scala/org/apache/spark/ml/classification/RandomForestClassifierSuite.scala
+++
b/mllib/src/test/scala/org/apache/spark/ml/classification/RandomForestClassifierSuite.scala
@@ -77,7 +77,11 @@ class RandomForestClassifierSuite extends MLTest with
DefaultReadWriteTest {
}
test("params") {
- ParamsSuite.checkParams(new RandomForestClassifier)
+ val classifier = new RandomForestClassifier
+ ParamsSuite.checkParams(classifier)
+ assert(classifier.getIntermediateStorageLevel === "MEMORY_AND_DISK")
+ classifier.setIntermediateStorageLevel("DISK_ONLY")
+ assert(classifier.getIntermediateStorageLevel === "DISK_ONLY")
val model = new RandomForestClassificationModel("rfc",
Array(new DecisionTreeClassificationModel("dtc", new LeafNode(0.0, 0.0,
null), 1, 2)), 2, 2)
ParamsSuite.checkParams(model)
diff --git
a/mllib/src/test/scala/org/apache/spark/ml/regression/DecisionTreeRegressorSuite.scala
b/mllib/src/test/scala/org/apache/spark/ml/regression/DecisionTreeRegressorSuite.scala
index 349877b6b9eb..64169efd4fcb 100644
---
a/mllib/src/test/scala/org/apache/spark/ml/regression/DecisionTreeRegressorSuite.scala
+++
b/mllib/src/test/scala/org/apache/spark/ml/regression/DecisionTreeRegressorSuite.scala
@@ -67,6 +67,9 @@ class DecisionTreeRegressorSuite extends MLTest with
DefaultReadWriteTest {
.setMaxDepth(2)
.setMaxBins(100)
.setSeed(1)
+ assert(dt.getIntermediateStorageLevel === "MEMORY_AND_DISK")
+ dt.setIntermediateStorageLevel("DISK_ONLY")
+ assert(dt.getIntermediateStorageLevel === "DISK_ONLY")
val categoricalFeatures = Map(0 -> 3, 1 -> 3)
compareAPIs(categoricalDataPointsRDD, dt, categoricalFeatures)
}
diff --git
a/mllib/src/test/scala/org/apache/spark/ml/regression/GBTRegressorSuite.scala
b/mllib/src/test/scala/org/apache/spark/ml/regression/GBTRegressorSuite.scala
index 07a11fa92caf..2aaf782d8343 100644
---
a/mllib/src/test/scala/org/apache/spark/ml/regression/GBTRegressorSuite.scala
+++
b/mllib/src/test/scala/org/apache/spark/ml/regression/GBTRegressorSuite.scala
@@ -330,6 +330,9 @@ class GBTRegressorSuite extends MLTest with
DefaultReadWriteTest {
.setMaxDepth(2)
.setCheckpointInterval(5)
.setSeed(123)
+ assert(gbt.getIntermediateStorageLevel === "MEMORY_AND_DISK")
+ gbt.setIntermediateStorageLevel("DISK_ONLY")
+ assert(gbt.getIntermediateStorageLevel === "DISK_ONLY")
val model = gbt.fit(trainData.toDF())
model.trees.foreach (i => {
diff --git
a/mllib/src/test/scala/org/apache/spark/ml/regression/RandomForestRegressorSuite.scala
b/mllib/src/test/scala/org/apache/spark/ml/regression/RandomForestRegressorSuite.scala
index 15db8c5c2253..16a503220997 100644
---
a/mllib/src/test/scala/org/apache/spark/ml/regression/RandomForestRegressorSuite.scala
+++
b/mllib/src/test/scala/org/apache/spark/ml/regression/RandomForestRegressorSuite.scala
@@ -163,6 +163,9 @@ class RandomForestRegressorSuite extends MLTest with
DefaultReadWriteTest {
.setMaxBins(10)
.setNumTrees(3)
.setSeed(123)
+ assert(rf.getIntermediateStorageLevel === "MEMORY_AND_DISK")
+ rf.setIntermediateStorageLevel("DISK_ONLY")
+ assert(rf.getIntermediateStorageLevel === "DISK_ONLY")
val df = orderedLabeledPoints50_1000.toDF()
val model = rf.fit(df)
diff --git a/python/pyspark/ml/classification.py
b/python/pyspark/ml/classification.py
index fdd81c312ade..d6df33f48cee 100644
--- a/python/pyspark/ml/classification.py
+++ b/python/pyspark/ml/classification.py
@@ -1830,13 +1830,15 @@ class DecisionTreeClassifier(
weightCol: Optional[str] = None,
leafCol: str = "",
minWeightFractionPerNode: float = 0.0,
+ intermediateStorageLevel: str = "MEMORY_AND_DISK",
):
"""
__init__(self, \\*, featuresCol="features", labelCol="label",
predictionCol="prediction", \
probabilityCol="probability",
rawPredictionCol="rawPrediction", \
maxDepth=5, maxBins=32, minInstancesPerNode=1,
minInfoGain=0.0, pruneTree=True, \
maxMemoryInMB=256, cacheNodeIds=False, checkpointInterval=10,
impurity="gini", \
- seed=None, weightCol=None, leafCol="",
minWeightFractionPerNode=0.0)
+ seed=None, weightCol=None, leafCol="",
minWeightFractionPerNode=0.0, \
+ intermediateStorageLevel="MEMORY_AND_DISK")
"""
super().__init__()
self._java_obj = self._new_java_obj(
@@ -1868,13 +1870,15 @@ class DecisionTreeClassifier(
weightCol: Optional[str] = None,
leafCol: str = "",
minWeightFractionPerNode: float = 0.0,
+ intermediateStorageLevel: str = "MEMORY_AND_DISK",
) -> "DecisionTreeClassifier":
"""
setParams(self, \\*, featuresCol="features", labelCol="label",
predictionCol="prediction", \
probabilityCol="probability",
rawPredictionCol="rawPrediction", \
maxDepth=5, maxBins=32, minInstancesPerNode=1,
minInfoGain=0.0, pruneTree=True, \
maxMemoryInMB=256, cacheNodeIds=False,
checkpointInterval=10, impurity="gini", \
- seed=None, weightCol=None, leafCol="",
minWeightFractionPerNode=0.0)
+ seed=None, weightCol=None, leafCol="",
minWeightFractionPerNode=0.0, \
+ intermediateStorageLevel="MEMORY_AND_DISK")
Sets params for the DecisionTreeClassifier.
"""
kwargs = self._input_kwargs
@@ -1947,6 +1951,13 @@ class DecisionTreeClassifier(
"""
return self._set(checkpointInterval=value)
+ @since("4.4.0")
+ def setIntermediateStorageLevel(self, value: str) ->
"DecisionTreeClassifier":
+ """
+ Sets the value of :py:attr:`intermediateStorageLevel`.
+ """
+ return self._set(intermediateStorageLevel=value)
+
def setSeed(self, value: int) -> "DecisionTreeClassifier":
"""
Sets the value of :py:attr:`seed`.
@@ -2136,6 +2147,7 @@ class RandomForestClassifier(
minWeightFractionPerNode: float = 0.0,
weightCol: Optional[str] = None,
bootstrap: Optional[bool] = True,
+ intermediateStorageLevel: str = "MEMORY_AND_DISK",
):
"""
__init__(self, \\*, featuresCol="features", labelCol="label",
predictionCol="prediction", \
@@ -2143,7 +2155,8 @@ class RandomForestClassifier(
maxDepth=5, maxBins=32, minInstancesPerNode=1,
minInfoGain=0.0, pruneTree=True, \
maxMemoryInMB=256, cacheNodeIds=False, checkpointInterval=10,
impurity="gini", \
numTrees=20, featureSubsetStrategy="auto", seed=None,
subsamplingRate=1.0, \
- leafCol="", minWeightFractionPerNode=0.0, weightCol=None,
bootstrap=True)
+ leafCol="", minWeightFractionPerNode=0.0, weightCol=None,
bootstrap=True, \
+ intermediateStorageLevel="MEMORY_AND_DISK")
"""
super().__init__()
self._java_obj = self._new_java_obj(
@@ -2179,6 +2192,7 @@ class RandomForestClassifier(
minWeightFractionPerNode: float = 0.0,
weightCol: Optional[str] = None,
bootstrap: Optional[bool] = True,
+ intermediateStorageLevel: str = "MEMORY_AND_DISK",
) -> "RandomForestClassifier":
"""
setParams(self, featuresCol="features", labelCol="label",
predictionCol="prediction", \
@@ -2186,7 +2200,8 @@ class RandomForestClassifier(
maxDepth=5, maxBins=32, minInstancesPerNode=1,
minInfoGain=0.0, pruneTree=True, \
maxMemoryInMB=256, cacheNodeIds=False,
checkpointInterval=10, seed=None, \
impurity="gini", numTrees=20, featureSubsetStrategy="auto",
subsamplingRate=1.0, \
- leafCol="", minWeightFractionPerNode=0.0, weightCol=None,
bootstrap=True)
+ leafCol="", minWeightFractionPerNode=0.0, weightCol=None,
bootstrap=True, \
+ intermediateStorageLevel="MEMORY_AND_DISK")
Sets params for linear classification.
"""
kwargs = self._input_kwargs
@@ -2285,6 +2300,13 @@ class RandomForestClassifier(
"""
return self._set(checkpointInterval=value)
+ @since("4.4.0")
+ def setIntermediateStorageLevel(self, value: str) ->
"RandomForestClassifier":
+ """
+ Sets the value of :py:attr:`intermediateStorageLevel`.
+ """
+ return self._set(intermediateStorageLevel=value)
+
@since("3.0.0")
def setWeightCol(self, value: str) -> "RandomForestClassifier":
"""
@@ -2614,6 +2636,7 @@ class GBTClassifier(
leafCol: str = "",
minWeightFractionPerNode: float = 0.0,
weightCol: Optional[str] = None,
+ intermediateStorageLevel: str = "MEMORY_AND_DISK",
):
"""
__init__(self, \\*, featuresCol="features", labelCol="label",
predictionCol="prediction", \
@@ -2622,7 +2645,8 @@ class GBTClassifier(
lossType="logistic", maxIter=20, stepSize=0.1, seed=None,
subsamplingRate=1.0, \
impurity="variance", featureSubsetStrategy="all",
validationTol=0.01, \
validationIndicatorCol=None, leafCol="",
minWeightFractionPerNode=0.0, \
- weightCol=None)
+ weightCol=None, \
+ intermediateStorageLevel="MEMORY_AND_DISK")
"""
super().__init__()
self._java_obj = self._new_java_obj(
@@ -2658,6 +2682,7 @@ class GBTClassifier(
leafCol: str = "",
minWeightFractionPerNode: float = 0.0,
weightCol: Optional[str] = None,
+ intermediateStorageLevel: str = "MEMORY_AND_DISK",
) -> "GBTClassifier":
"""
setParams(self, \\*, featuresCol="features", labelCol="label",
predictionCol="prediction", \
@@ -2666,7 +2691,8 @@ class GBTClassifier(
lossType="logistic", maxIter=20, stepSize=0.1, seed=None,
subsamplingRate=1.0, \
impurity="variance", featureSubsetStrategy="all",
validationTol=0.01, \
validationIndicatorCol=None, leafCol="",
minWeightFractionPerNode=0.0, \
- weightCol=None)
+ weightCol=None, \
+ intermediateStorageLevel="MEMORY_AND_DISK")
Sets params for Gradient Boosted Tree Classification.
"""
kwargs = self._input_kwargs
@@ -2760,6 +2786,13 @@ class GBTClassifier(
"""
return self._set(checkpointInterval=value)
+ @since("4.4.0")
+ def setIntermediateStorageLevel(self, value: str) -> "GBTClassifier":
+ """
+ Sets the value of :py:attr:`intermediateStorageLevel`.
+ """
+ return self._set(intermediateStorageLevel=value)
+
@since("1.4.0")
def setSeed(self, value: int) -> "GBTClassifier":
"""
diff --git a/python/pyspark/ml/regression.py b/python/pyspark/ml/regression.py
index f3f780aa360c..82a36fbfd202 100644
--- a/python/pyspark/ml/regression.py
+++ b/python/pyspark/ml/regression.py
@@ -1126,13 +1126,15 @@ class DecisionTreeRegressor(
weightCol: Optional[str] = None,
leafCol: str = "",
minWeightFractionPerNode: float = 0.0,
+ intermediateStorageLevel: str = "MEMORY_AND_DISK",
):
"""
__init__(self, \\*, featuresCol="features", labelCol="label",
predictionCol="prediction", \
maxDepth=5, maxBins=32, minInstancesPerNode=1,
minInfoGain=0.0, \
maxMemoryInMB=256, cacheNodeIds=False, checkpointInterval=10,
\
impurity="variance", seed=None, varianceCol=None,
weightCol=None, \
- leafCol="", minWeightFractionPerNode=0.0)
+ leafCol="", minWeightFractionPerNode=0.0, \
+ intermediateStorageLevel="MEMORY_AND_DISK")
"""
super().__init__()
self._java_obj = self._new_java_obj(
@@ -1162,13 +1164,15 @@ class DecisionTreeRegressor(
weightCol: Optional[str] = None,
leafCol: str = "",
minWeightFractionPerNode: float = 0.0,
+ intermediateStorageLevel: str = "MEMORY_AND_DISK",
) -> "DecisionTreeRegressor":
"""
setParams(self, \\*, featuresCol="features", labelCol="label",
predictionCol="prediction", \
maxDepth=5, maxBins=32, minInstancesPerNode=1,
minInfoGain=0.0, \
maxMemoryInMB=256, cacheNodeIds=False,
checkpointInterval=10, \
impurity="variance", seed=None, varianceCol=None,
weightCol=None, \
- leafCol="", minWeightFractionPerNode=0.0)
+ leafCol="", minWeightFractionPerNode=0.0, \
+ intermediateStorageLevel="MEMORY_AND_DISK")
Sets params for the DecisionTreeRegressor.
"""
kwargs = self._input_kwargs
@@ -1240,6 +1244,13 @@ class DecisionTreeRegressor(
"""
return self._set(checkpointInterval=value)
+ @since("4.4.0")
+ def setIntermediateStorageLevel(self, value: str) ->
"DecisionTreeRegressor":
+ """
+ Sets the value of :py:attr:`intermediateStorageLevel`.
+ """
+ return self._set(intermediateStorageLevel=value)
+
def setSeed(self, value: int) -> "DecisionTreeRegressor":
"""
Sets the value of :py:attr:`seed`.
@@ -1429,6 +1440,7 @@ class RandomForestRegressor(
minWeightFractionPerNode: float = 0.0,
weightCol: Optional[str] = None,
bootstrap: Optional[bool] = True,
+ intermediateStorageLevel: str = "MEMORY_AND_DISK",
):
"""
__init__(self, \\*, featuresCol="features", labelCol="label",
predictionCol="prediction", \
@@ -1436,7 +1448,8 @@ class RandomForestRegressor(
maxMemoryInMB=256, cacheNodeIds=False, checkpointInterval=10,
\
impurity="variance", subsamplingRate=1.0, seed=None,
numTrees=20, \
featureSubsetStrategy="auto", leafCol=",
minWeightFractionPerNode=0.0", \
- weightCol=None, bootstrap=True)
+ weightCol=None, bootstrap=True, \
+ intermediateStorageLevel="MEMORY_AND_DISK")
"""
super().__init__()
self._java_obj = self._new_java_obj(
@@ -1469,6 +1482,7 @@ class RandomForestRegressor(
minWeightFractionPerNode: float = 0.0,
weightCol: Optional[str] = None,
bootstrap: Optional[bool] = True,
+ intermediateStorageLevel: str = "MEMORY_AND_DISK",
) -> "RandomForestRegressor":
"""
setParams(self, \\*, featuresCol="features", labelCol="label",
predictionCol="prediction", \
@@ -1476,7 +1490,8 @@ class RandomForestRegressor(
maxMemoryInMB=256, cacheNodeIds=False,
checkpointInterval=10, \
impurity="variance", subsamplingRate=1.0, seed=None,
numTrees=20, \
featureSubsetStrategy="auto", leafCol="",
minWeightFractionPerNode=0.0, \
- weightCol=None, bootstrap=True)
+ weightCol=None, bootstrap=True, \
+ intermediateStorageLevel="MEMORY_AND_DISK")
Sets params for linear regression.
"""
kwargs = self._input_kwargs
@@ -1562,6 +1577,13 @@ class RandomForestRegressor(
"""
return self._set(checkpointInterval=value)
+ @since("4.4.0")
+ def setIntermediateStorageLevel(self, value: str) ->
"RandomForestRegressor":
+ """
+ Sets the value of :py:attr:`intermediateStorageLevel`.
+ """
+ return self._set(intermediateStorageLevel=value)
+
def setSeed(self, value: int) -> "RandomForestRegressor":
"""
Sets the value of :py:attr:`seed`.
@@ -1782,6 +1804,7 @@ class GBTRegressor(
leafCol: str = "",
minWeightFractionPerNode: float = 0.0,
weightCol: Optional[str] = None,
+ intermediateStorageLevel: str = "MEMORY_AND_DISK",
):
"""
__init__(self, \\*, featuresCol="features", labelCol="label",
predictionCol="prediction", \
@@ -1790,7 +1813,8 @@ class GBTRegressor(
checkpointInterval=10, lossType="squared", maxIter=20,
stepSize=0.1, seed=None, \
impurity="variance", featureSubsetStrategy="all",
validationTol=0.01, \
validationIndicatorCol=None, leafCol="",
minWeightFractionPerNode=0.0,
- weightCol=None)
+ weightCol=None, \
+ intermediateStorageLevel="MEMORY_AND_DISK")
"""
super().__init__()
self._java_obj =
self._new_java_obj("org.apache.spark.ml.regression.GBTRegressor", self.uid)
@@ -1824,6 +1848,7 @@ class GBTRegressor(
leafCol: str = "",
minWeightFractionPerNode: float = 0.0,
weightCol: Optional[str] = None,
+ intermediateStorageLevel: str = "MEMORY_AND_DISK",
) -> "GBTRegressor":
"""
setParams(self, \\*, featuresCol="features", labelCol="label",
predictionCol="prediction", \
@@ -1832,7 +1857,8 @@ class GBTRegressor(
checkpointInterval=10, lossType="squared", maxIter=20,
stepSize=0.1, seed=None, \
impurity="variance", featureSubsetStrategy="all",
validationTol=0.01, \
validationIndicatorCol=None, leafCol="",
minWeightFractionPerNode=0.0, \
- weightCol=None)
+ weightCol=None, \
+ intermediateStorageLevel="MEMORY_AND_DISK")
Sets params for Gradient Boosted Tree Regression.
"""
kwargs = self._input_kwargs
@@ -1932,6 +1958,13 @@ class GBTRegressor(
"""
return self._set(checkpointInterval=value)
+ @since("4.4.0")
+ def setIntermediateStorageLevel(self, value: str) -> "GBTRegressor":
+ """
+ Sets the value of :py:attr:`intermediateStorageLevel`.
+ """
+ return self._set(intermediateStorageLevel=value)
+
@since("1.4.0")
def setSeed(self, value: int) -> "GBTRegressor":
"""
diff --git a/python/pyspark/ml/tests/test_classification.py
b/python/pyspark/ml/tests/test_classification.py
index ad3428bb4c87..94d49e04eef1 100644
--- a/python/pyspark/ml/tests/test_classification.py
+++ b/python/pyspark/ml/tests/test_classification.py
@@ -606,18 +606,26 @@ class ClassificationTestsMixin:
.sortWithinPartitions("weight")
)
+
self.assertEqual(DecisionTreeClassifier().getIntermediateStorageLevel(),
"MEMORY_AND_DISK")
dt = DecisionTreeClassifier(
maxDepth=2,
labelCol="label",
leafCol="leaf",
seed=1,
+ intermediateStorageLevel="DISK_ONLY",
)
+ self.assertEqual(dt.getIntermediateStorageLevel(), "DISK_ONLY")
+ dt.setParams(intermediateStorageLevel="MEMORY_ONLY")
+ self.assertEqual(dt.getIntermediateStorageLevel(), "MEMORY_ONLY")
+ dt.setIntermediateStorageLevel("DISK_ONLY")
+ self.assertEqual(dt.getIntermediateStorageLevel(), "DISK_ONLY")
self.assertEqual(dt.getMaxDepth(), 2)
self.assertEqual(dt.getSeed(), 1)
self.assertEqual(dt.getLabelCol(), "label")
self.assertEqual(dt.getLeafCol(), "leaf")
model = dt.fit(df)
+ self.assertEqual(model.getIntermediateStorageLevel(), "DISK_ONLY")
self.assertEqual(dt.uid, model.uid)
self.assertEqual(model.numClasses, 2)
self.assertEqual(model.numFeatures, 2)
@@ -672,13 +680,20 @@ class ClassificationTestsMixin:
.sortWithinPartitions("weight")
)
+ self.assertEqual(GBTClassifier().getIntermediateStorageLevel(),
"MEMORY_AND_DISK")
gbt = GBTClassifier(
maxIter=3,
maxDepth=2,
labelCol="label",
leafCol="leaf",
seed=1,
+ intermediateStorageLevel="DISK_ONLY",
)
+ self.assertEqual(gbt.getIntermediateStorageLevel(), "DISK_ONLY")
+ gbt.setParams(intermediateStorageLevel="MEMORY_ONLY")
+ self.assertEqual(gbt.getIntermediateStorageLevel(), "MEMORY_ONLY")
+ gbt.setIntermediateStorageLevel("DISK_ONLY")
+ self.assertEqual(gbt.getIntermediateStorageLevel(), "DISK_ONLY")
self.assertEqual(gbt.getMaxIter(), 3)
self.assertEqual(gbt.getMaxDepth(), 2)
self.assertEqual(gbt.getSeed(), 1)
@@ -686,6 +701,7 @@ class ClassificationTestsMixin:
self.assertEqual(gbt.getLeafCol(), "leaf")
model = gbt.fit(df)
+ self.assertEqual(model.getIntermediateStorageLevel(), "DISK_ONLY")
self.assertEqual(gbt.uid, model.uid)
self.assertEqual(model.numClasses, 2)
self.assertEqual(model.numFeatures, 2)
@@ -762,13 +778,20 @@ class ClassificationTestsMixin:
.sortWithinPartitions("weight")
)
+
self.assertEqual(RandomForestClassifier().getIntermediateStorageLevel(),
"MEMORY_AND_DISK")
rf = RandomForestClassifier(
numTrees=3,
maxDepth=2,
labelCol="label",
leafCol="leaf",
seed=1,
+ intermediateStorageLevel="DISK_ONLY",
)
+ self.assertEqual(rf.getIntermediateStorageLevel(), "DISK_ONLY")
+ rf.setParams(intermediateStorageLevel="MEMORY_ONLY")
+ self.assertEqual(rf.getIntermediateStorageLevel(), "MEMORY_ONLY")
+ rf.setIntermediateStorageLevel("DISK_ONLY")
+ self.assertEqual(rf.getIntermediateStorageLevel(), "DISK_ONLY")
self.assertEqual(rf.getNumTrees(), 3)
self.assertEqual(rf.getMaxDepth(), 2)
self.assertEqual(rf.getSeed(), 1)
@@ -776,6 +799,7 @@ class ClassificationTestsMixin:
self.assertEqual(rf.getLeafCol(), "leaf")
model = rf.fit(df)
+ self.assertEqual(model.getIntermediateStorageLevel(), "DISK_ONLY")
self.assertEqual(rf.uid, model.uid)
self.assertEqual(model.numClasses, 2)
self.assertEqual(model.numFeatures, 2)
diff --git a/python/pyspark/ml/tests/test_regression.py
b/python/pyspark/ml/tests/test_regression.py
index 929ded5d2761..7024bd45cd5f 100644
--- a/python/pyspark/ml/tests/test_regression.py
+++ b/python/pyspark/ml/tests/test_regression.py
@@ -455,18 +455,26 @@ class RegressionTestsMixin:
.sortWithinPartitions("weight")
)
+
self.assertEqual(DecisionTreeRegressor().getIntermediateStorageLevel(),
"MEMORY_AND_DISK")
dt = DecisionTreeRegressor(
maxDepth=2,
labelCol="label",
leafCol="leaf",
seed=1,
+ intermediateStorageLevel="DISK_ONLY",
)
+ self.assertEqual(dt.getIntermediateStorageLevel(), "DISK_ONLY")
+ dt.setParams(intermediateStorageLevel="MEMORY_ONLY")
+ self.assertEqual(dt.getIntermediateStorageLevel(), "MEMORY_ONLY")
+ dt.setIntermediateStorageLevel("DISK_ONLY")
+ self.assertEqual(dt.getIntermediateStorageLevel(), "DISK_ONLY")
self.assertEqual(dt.getMaxDepth(), 2)
self.assertEqual(dt.getSeed(), 1)
self.assertEqual(dt.getLabelCol(), "label")
self.assertEqual(dt.getLeafCol(), "leaf")
model = dt.fit(df)
+ self.assertEqual(model.getIntermediateStorageLevel(), "DISK_ONLY")
self.assertEqual(dt.uid, model.uid)
self.assertEqual(model.numFeatures, 2)
self.assertEqual(model.depth, 2)
@@ -524,13 +532,20 @@ class RegressionTestsMixin:
.sortWithinPartitions("weight")
)
+ self.assertEqual(GBTRegressor().getIntermediateStorageLevel(),
"MEMORY_AND_DISK")
gbt = GBTRegressor(
maxIter=3,
maxDepth=2,
labelCol="label",
leafCol="leaf",
seed=1,
+ intermediateStorageLevel="DISK_ONLY",
)
+ self.assertEqual(gbt.getIntermediateStorageLevel(), "DISK_ONLY")
+ gbt.setParams(intermediateStorageLevel="MEMORY_ONLY")
+ self.assertEqual(gbt.getIntermediateStorageLevel(), "MEMORY_ONLY")
+ gbt.setIntermediateStorageLevel("DISK_ONLY")
+ self.assertEqual(gbt.getIntermediateStorageLevel(), "DISK_ONLY")
self.assertEqual(gbt.getMaxIter(), 3)
self.assertEqual(gbt.getMaxDepth(), 2)
self.assertEqual(gbt.getSeed(), 1)
@@ -538,6 +553,7 @@ class RegressionTestsMixin:
self.assertEqual(gbt.getLeafCol(), "leaf")
model = gbt.fit(df)
+ self.assertEqual(model.getIntermediateStorageLevel(), "DISK_ONLY")
self.assertEqual(gbt.uid, model.uid)
self.assertEqual(model.numFeatures, 2)
self.assertEqual(model.treeWeights, [1.0, 0.1, 0.1])
@@ -622,13 +638,20 @@ class RegressionTestsMixin:
.sortWithinPartitions("weight")
)
+
self.assertEqual(RandomForestRegressor().getIntermediateStorageLevel(),
"MEMORY_AND_DISK")
rf = RandomForestRegressor(
numTrees=3,
maxDepth=2,
labelCol="label",
leafCol="leaf",
seed=1,
+ intermediateStorageLevel="DISK_ONLY",
)
+ self.assertEqual(rf.getIntermediateStorageLevel(), "DISK_ONLY")
+ rf.setParams(intermediateStorageLevel="MEMORY_ONLY")
+ self.assertEqual(rf.getIntermediateStorageLevel(), "MEMORY_ONLY")
+ rf.setIntermediateStorageLevel("DISK_ONLY")
+ self.assertEqual(rf.getIntermediateStorageLevel(), "DISK_ONLY")
self.assertEqual(rf.getNumTrees(), 3)
self.assertEqual(rf.getMaxDepth(), 2)
self.assertEqual(rf.getSeed(), 1)
@@ -636,6 +659,7 @@ class RegressionTestsMixin:
self.assertEqual(rf.getLeafCol(), "leaf")
model = rf.fit(df)
+ self.assertEqual(model.getIntermediateStorageLevel(), "DISK_ONLY")
self.assertEqual(rf.uid, model.uid)
self.assertEqual(model.numFeatures, 2)
self.assertEqual(model.treeWeights, [1.0, 1.0, 1.0])
diff --git a/python/pyspark/ml/tree.py b/python/pyspark/ml/tree.py
index 070a37944f85..68d4d9ff5c24 100644
--- a/python/pyspark/ml/tree.py
+++ b/python/pyspark/ml/tree.py
@@ -22,6 +22,7 @@ from pyspark.ml.linalg import Vector
from pyspark.ml.param import Params
from pyspark.ml.param.shared import (
HasCheckpointInterval,
+ HasIntermediateStorageLevel,
HasMaxIter,
HasSeed,
HasStepSize,
@@ -72,7 +73,9 @@ class _DecisionTreeModel(JavaPredictionModel[T]):
return self._call_java("predictLeaf", value)
-class _DecisionTreeParams(HasCheckpointInterval, HasSeed, HasWeightCol):
+class _DecisionTreeParams(
+ HasCheckpointInterval, HasSeed, HasWeightCol, HasIntermediateStorageLevel
+):
"""
Mixin for Decision Tree parameters.
"""
---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]