Random Forest

Setting Up a Random Forest Classifier

Note: Make sure you have your training and test data already vectorized and ready to go before you begin trying to fit the machine learning model to unprepped data.

Load in required libraries

1
from pyspark.ml.classification import RandomForestClassifier
2
from pyspark.ml.tuning import ParamGridBuilder, CrossValidator
3
from pyspark.ml.evaluation import BinaryClassificationEvaluator
Copied!

Initialize Random Forest object

1
rf = RandomForestClassifier(labelCol="label", featuresCol="features")
Copied!

Create a parameter grid for tuning the model

1
rfparamGrid = (ParamGridBuilder()
2
3
.addGrid(rf.maxDepth, [2, 5, 10])
4
5
.addGrid(rf.maxBins, [5, 10, 20])
6
7
.addGrid(rf.numTrees, [5, 20, 50])
8
.build())
Copied!

Define how you want the model to be evaluated

1
rfevaluator = BinaryClassificationEvaluator(rawPredictionCol="rawPrediction")
Copied!

Define the type of cross-validation you want to perform

1
# Create 5-fold CrossValidator
2
rfcv = CrossValidator(estimator = rf,
3
estimatorParamMaps = rfparamGrid,
4
evaluator = rfevaluator,
5
numFolds = 5)
Copied!

Fit the model to the data

1
rfcvModel = rfcv.fit(train)
2
print(rfcvModel)
Copied!

Score the testing dataset using your fitted model for evaluation purposes

1
rfpredictions = rfcvModel.transform(test)
Copied!

Evaluate the model

1
print('Accuracy:', rfevaluator.evaluate(rfpredictions))
2
print('AUC:', BinaryClassificationMetrics(rfpredictions['label','prediction'].rdd).areaUnderROC)
3
print('PR:', BinaryClassificationMetrics(rfpredictions['label','prediction'].rdd).areaUnderPR)
Copied!
Note: When you use the CrossValidator function to set up cross-validation of your models, the resulting model object will have all the runs included, but will only use the best model when you interact with the model object using other functions like evaluate or transform.