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

  1. Training DataFrame with raw columns
  2. Define stages: indexers/encoders, VectorAssembler, model
  3. pipeline.fit(train): fit each Estimator in order
  4. Get a PipelineModel of fitted stages
  5. New data to score? Yes: model.transform(new_df) applies every stage. No: Save it with model.write().save(path).
  6. 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

Apache Spark topics

Spark Fundamentals

Spark Architecture

RDDs

DataFrames

Aggregations & Joins

Spark SQL

Window Functions

Cleaning & Complex Types

UDFs

Performance Tuning

Structured Streaming

MLlib & Ecosystem

Interview Prep

T
Tech Town
Log InSign Up Free
Home SQL Python DSA Power BI Snowflake Databricks Spark Gen AI Practice Problems Contest Blog

Master Apache Spark

PySpark and Spark SQL from the ground up: DataFrames, joins, window functions, partitions and performance tuning, Structured Streaming and more. Click any topic in the sidebar to open it right here.

{{ sectionCount }}
Sections
{{ topicCount }}
Topics
Free
Forever
Hands-on practice Practice PySpark Write real PySpark — DataFrames, joins, window functions and Spark SQL — in a live editor with hidden tests and instant checking. Start practising →
Section {{ sec.num }}

{{ sec.label }}

Spark  /  {{ current.sectionLabel }}  /  {{ current.name }}

{{ current.name }}

Theory

{{ current.def }}

Why we use it

{{ rich.why }}

When to use it

{{ rich.when }}

{{ sec.h }}

{{ sec.body }}

{{ sec.body }}

Diagram

{{ rich.dg.caption }}

{{ tb.title }}
{{ c.v }}
{{ rich.dg.op }}
➜
{{ rich.dg.output.title }}
{{ c.v }}
{{ nd.label }}
{{ nd.sub }}
{{ nd.label }}
{{ nd.sub }}
{{ rich.dg.left.title }}
{{ it }}
{{ rich.dg.right.title }}
{{ it }}
On screen — where to click

{{ rich.ui.title }}

{{ u.text }}
  1. {{ st.n }}{{ st.text }}
{{ rich.ui.title }}
{{ u.text }}
Flowchart — how it works
{{ nd.text }}
{{ nd.text }}
◇ {{ nd.text }}
Yes → {{ nd.yes }}
No → {{ nd.no }}
Syntax
{{ current.syntax }}
Example
{{ current.example }}
Want to run this yourself? Try the same API on Practice PySpark Online right in your browser, or run it locally after pip install pyspark (needs Java 17+), or paste it into a Databricks Free Edition notebook.
Key Points — click to check off as you learn
  • {{ pt.mark }} {{ pt.text }}

Share this topic