How do I call prediction function in pyspark?
Master System Design with Codemia
Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.
Introduction
In PySpark ML, you usually do not call a standalone predict function directly like some local libraries. Instead, you train an estimator to get a model, then call model.transform on a DataFrame to generate prediction columns. This DataFrame-first pattern is central to scalable prediction in Spark.
Train, Fit, and Transform Workflow
Spark ML separates workflow into three stages:
- Estimator, for example
LogisticRegression - Model produced by
fit - Predictions produced by
transform
Minimal binary classification example:
The prediction output is a new DataFrame with additional columns, usually prediction, probability, and rawPrediction.
Predict on New Data
For inference, prepare input schema exactly as training expected and run transform.
If feature columns or types differ, Spark may fail at runtime, so keep schema contracts explicit.
Use Pipeline for Cleaner Production Inference
Pipelines bundle preprocessing and model into one reusable object.
With a pipeline model, you call transform once and avoid manual step orchestration.
Save and Load Models for Reuse
For batch or streaming inference jobs, persist models and reload in separate processes.
Always version model artifacts together with feature engineering code and schema expectations.
Evaluate Prediction Quality in Spark
After scoring, validate output quality before shipping results to downstream systems. Spark evaluators let you measure accuracy without collecting full datasets to driver memory.
Including this check in pipelines catches model regressions early.
UDF-Based Prediction Is Usually a Last Resort
Some teams try to use Python UDFs for prediction because it resembles local inference APIs. This is usually slower and harder to manage than native Spark ML transforms. Prefer Spark ML transformers unless you must call an external model format unsupported by Spark.
If you must use UDF-based scoring, benchmark carefully and consider Pandas UDFs for better throughput.
Common Pitfalls
- Looking for
predict()method instead of usingmodel.transform(). - Scoring DataFrames without the same feature preparation used in training.
- Schema drift between training and inference datasets.
- Saving only model weights and forgetting preprocessing pipeline.
- Overusing Python UDF prediction when native Spark ML can handle the workload.
Summary
- In PySpark ML, prediction is performed through
model.transform. - Keep feature engineering consistent between training and inference.
- Pipelines simplify production scoring and reduce preprocessing mismatch.
- Persist and reload models with explicit versioning.
- Prefer native Spark ML transforms over custom UDF prediction paths.

