MLlib Pipelines: Transformers & Estimators
Apache Spark · MLlib & Ecosystem
Theory
MLlib is Spark's machine learning library; the DataFrame-based API lives in pyspark.ml. It is built from two kinds of stages. A Transformer turns one DataFrame into another with transform(), for example VectorAssembler packs numeric columns into a single features vector. An Estimator learns from data with fit() and returns a Transformer called a Model: StringIndexer.fit() learns which category gets which index, and LogisticRegression.fit() learns coefficients.
A Pipeline chains stages in order, such as StringIndexer -> VectorAssembler -> LogisticRegression. Calling pipeline.fit(train) fits every estimator in sequence and returns a PipelineModel, which applies the exact same steps to new data with transform(test). Because preprocessing and model travel together, there is no risk of encoding test data differently from training data. You can save and reload the whole PipelineModel.
Why we use it
Real ML needs several preprocessing steps before the model, and they must be applied identically at training and prediction time. Pipelines package those steps with the model, run them distributed on Spark DataFrames, and make tuning and saving the whole workflow simple.
When to use it
Use MLlib pipelines when training data is too big for one machine or the features are built in Spark already, for classic models such as linear models, trees, gradient-boosted trees, clustering and recommendation. For small data or deep learning, train with scikit-learn or a deep learning framework and use Spark for feature preparation or batch scoring.
How it works
- Training DataFrame with raw columns
- Define stages: indexers/encoders, VectorAssembler, model
- pipeline.fit(train): fit each Estimator in order
- Get a PipelineModel of fitted stages
- New data to score? Yes: model.transform(new_df) applies every stage. No: Save it with model.write().save(path).
- Predictions with consistent preprocessing
Syntax
from pyspark.ml import Pipeline, PipelineModel
from pyspark.ml.feature import StringIndexer, VectorAssembler
from pyspark.ml.classification import LogisticRegression
pipe = Pipeline(stages=[indexer, assembler, lr])
model = pipe.fit(train) # Estimator -> PipelineModel
model.transform(test) # Transformer
model.write().overwrite().save(path); PipelineModel.load(path)Example
from pyspark.sql import SparkSession, functions as F
spark = SparkSession.builder.appName("techtown-spark").getOrCreate()
# 200 customers with simple behaviour features and a churn label (1 = churned)
cities = ["Jaipur", "Pune", "Delhi", "Mumbai"]
segments = ["Retail", "Corporate", "SMB"]
rows = []
for i in range(200):
orders_90d = (i * 7) % 9
days_since_last = (i * 13) % 60
avg_amount = float(1000 + (i * 1733) % 50000)
churned = 1 if days_since_last > 5 * orders_90d + 10 else 0 # recent, frequent buyers stay
rows.append((100 + i, cities[i % 4], segments[i % 3], orders_90d, days_since_last, avg_amount, churned))
customers = spark.createDataFrame(rows,
"customer_id INT, city STRING, segment STRING, orders_90d INT, days_since_last INT, avg_amount DOUBLE, label INT")
import tempfile
from pyspark.ml import Pipeline, PipelineModel
from pyspark.ml.feature import StringIndexer, VectorAssembler
from pyspark.ml.classification import LogisticRegression
indexer = StringIndexer(inputCol="segment", outputCol="segment_idx") # Estimator
assembler = VectorAssembler(inputCols=["segment_idx", "orders_90d", "days_since_last"],
outputCol="features") # Transformer
lr = LogisticRegression(featuresCol="features", labelCol="label", maxIter=50) # Estimator
pipeline = Pipeline(stages=[indexer, assembler, lr])
model = pipeline.fit(customers) # fits indexer, then lr, in order
print([type(s).__name__ for s in model.stages]) # fitted stages: models + transformers
scored = model.transform(customers)
scored.select("customer_id", "segment", "segment_idx", "features", "prediction").show(5, truncate=False)
path = tempfile.mkdtemp() + "/churn_pipeline"
model.write().overwrite().save(path)
reloaded = PipelineModel.load(path)
print("same predictions after reload:",
reloaded.transform(customers).select("prediction").collect() == scored.select("prediction").collect())
# Output:
# ['StringIndexerModel', 'VectorAssembler', 'LogisticRegressionModel']
# +-----------+---------+-----------+--------------+----------+
# |customer_id|segment |segment_idx|features |prediction|
# +-----------+---------+-----------+--------------+----------+
# |100 |Retail |1.0 |[1.0,0.0,0.0] |0.0 |
# |101 |Corporate|0.0 |[0.0,7.0,13.0]|0.0 |
# |102 |SMB |2.0 |[2.0,5.0,26.0]|0.0 |
# |103 |Retail |1.0 |[1.0,3.0,39.0]|1.0 |
# |104 |Corporate|0.0 |[0.0,1.0,52.0]|1.0 |
# +-----------+---------+-----------+--------------+----------+
# only showing top 5 rows
# same predictions after reload: True
Key points
- Transformer: transform(df) -> df. Estimator: fit(df) -> Model (a Transformer)
- A Pipeline is an Estimator; fitting it returns a PipelineModel
- The PipelineModel applies identical preprocessing to new data
- Most models expect one vector column of features: use VectorAssembler
- Save and load the whole PipelineModel, not just the final model