Decision Tree
Setting Up a Decision Tree Classifier
Load in required libraries
from pyspark.ml.classification import DecisionTreeClassifier
from pyspark.ml.tuning import ParamGridBuilder, CrossValidator
from pyspark.ml.evaluation import BinaryClassificationEvaluator
Initialize Decision Tree object
dt = DecisionTreeClassifier(labelCol="label", featuresCol="features")
Create a parameter grid for tuning the model
dtparamGrid = (ParamGridBuilder()
.addGrid(dt.maxDepth, [2, 5, 10])
.addGrid(dt.maxBins, [10, 20])
.build())
Define how you want the model to be evaluated
dtevaluator = BinaryClassificationEvaluator(rawPredictionCol="rawPrediction")
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('Accuracy:', dtevaluator.evaluate(dtpredictions))
print('AUC:', BinaryClassificationMetrics(dtpredictions['label','prediction'].rdd).areaUnderROC)
print('PR:', BinaryClassificationMetrics(dtpredictions['label','prediction'].rdd).areaUnderPR)
Last updated
Was this helpful?