Implementing machine learning pipelines in PySpark
Instruction: Describe how you would build and evaluate a machine learning pipeline for a predictive modeling task using PySpark's MLlib.
Updated
For a binary prediction task, define the label and prediction-time feature contract before constructing a DataFrame-based pyspark.ml.Pipeline. Split by the relevant unit or time period so repeated users and future information do not leak into evaluation.
A typical pipeline is categorical indexing, one-hot encoding, numerical imputation, vector assembly and a classifier. Add scaling only when appropriate for the estimator and representation. StringIndexer, an imputer and a scaler learn from data: fit them inside the training pipeline, not on all rows before splitting. Define how missing and unseen categories are handled; mapping an unknown value to a bucket does not mean the model has learned its behavior.
Fit the entire pipeline on training data. When tuning, cross-validate the entire pipeline so each fold learns its preprocessing from that fold's training portion. Standard random folds are unsuitable when time or entity dependence requires a custom split. Keep a separate final test set after choosing hyperparameters and thresholds.
BinaryClassificationEvaluator reports area under ROC or PR curves from scores; it does not report every threshold-based metric. Compute precision, recall and a confusion matrix at the chosen operating threshold, and assess calibration and subgroup performance where relevant. A high ROC area alone does not guarantee useful precision for rare positives. Report sample sizes and compare with a simple baseline.
Save the fitted PipelineModel, schema/feature contract, label mapping, environment and training snapshot. Reload it and test fixed reference inputs before release. Batch scoring, micro-batch scoring and a low-latency service have different runtime requirements; a saved model is not itself a deployed endpoint. Monitor data quality, prediction behavior, delayed-label errors and latency, and retain a validated rollback artifact.