Decision Tree
Setting Up Decision Tree Regression
Load in required libraries
from pyspark.ml.regression import DecisionTreeRegressor
from pyspark.ml.tuning import ParamGridBuilder, CrossValidator
from pyspark.ml.evaluation import RegressionEvaluator
Initialize Decision Tree object
dt = DecisionTreeRegressor(labelCol="label", featuresCol="features")
Create a parameter grid for tuning the model
dtparamGrid = (ParamGridBuilder()
.addGrid(dt.maxDepth, [2, 5, 10, 20, 30])
#.addGrid(dt.maxDepth, [2, 5, 10])
.addGrid(dt.maxBins, [10, 20, 40, 80, 100])
#.addGrid(dt.maxBins, [10, 20])
.build())
Define how you want the model to be evaluated
dtevaluator = RegressionEvaluator(predictionCol="prediction", labelCol="label", metricName="rmse")
Define the type of cross-validation you want to perform
# Create 5-fold CrossValidator
dtcv = CrossValidator(estimator = dt,
estimatorParamMaps = dtparamGrid,
evaluator = dtevaluator,
numFolds = 5)
Fit the model to the data
dtcvModel = dtcv.fit(train)
print(dtcvModel)
Score the testing dataset using your fitted model for evaluation purposes
dtpredictions = dtcvModel.transform(test)
Evaluate the model
print('RMSE:', dtevaluator.evaluate(dtpredictions))
Last updated
Was this helpful?