ML Pipelines help organize and automate machine learning steps in Spark. They make building and testing models easier and faster.
ML Pipelines in Spark in Apache Spark
from pyspark.ml import Pipeline from pyspark.ml.feature import Tokenizer, HashingTF from pyspark.ml.classification import LogisticRegression # Define stages tokenizer = Tokenizer(inputCol="text", outputCol="words") hashingTF = HashingTF(inputCol="words", outputCol="features") logReg = LogisticRegression(featuresCol="features", labelCol="label") # Create pipeline pipeline = Pipeline(stages=[tokenizer, hashingTF, logReg])
A pipeline is a sequence of stages, each stage is a transformer or an estimator.
Transformers change data, estimators train models.
from pyspark.ml.feature import StringIndexer indexer = StringIndexer(inputCol="category", outputCol="categoryIndex") pipeline = Pipeline(stages=[indexer])
from pyspark.ml.feature import VectorAssembler assembler = VectorAssembler(inputCols=["col1", "col2"], outputCol="features") pipeline = Pipeline(stages=[assembler])
This program creates a simple ML pipeline in Spark that tokenizes text, converts words to features, and trains a logistic regression model. Then it predicts labels on new text data.
from pyspark.sql import SparkSession from pyspark.ml import Pipeline from pyspark.ml.feature import Tokenizer, HashingTF from pyspark.ml.classification import LogisticRegression # Start Spark session spark = SparkSession.builder.appName("MLPipelineExample").getOrCreate() # Sample data training = spark.createDataFrame([ (0, "spark is great", 1.0), (1, "spark is fast", 1.0), (2, "hadoop is slow", 0.0), (3, "hadoop is old", 0.0) ], ["id", "text", "label"]) # Define stages tokenizer = Tokenizer(inputCol="text", outputCol="words") hashingTF = HashingTF(inputCol="words", outputCol="features") logReg = LogisticRegression(featuresCol="features", labelCol="label") # Create pipeline pipeline = Pipeline(stages=[tokenizer, hashingTF, logReg]) # Train model model = pipeline.fit(training) # Test data test = spark.createDataFrame([ (4, "spark is awesome"), (5, "hadoop is outdated") ], ["id", "text"]) # Make predictions predictions = model.transform(test) # Show results predictions.select("id", "text", "probability", "prediction").show() spark.stop()
Always define clear input and output columns for each stage.
Use Pipeline.fit() to train and PipelineModel.transform() to apply the model.
ML Pipelines help keep your code clean and reusable.
ML Pipelines chain data preparation and model training steps.
They automate workflows and reduce errors.
Use pipelines to easily apply the same process to new data.
Practice
ML Pipelines in Apache Spark?Solution
Step 1: Understand ML Pipelines concept
ML Pipelines are designed to combine multiple steps like data cleaning, feature extraction, and model training into a single workflow.Step 2: Identify the main purpose
This chaining helps automate the process and apply the same steps easily to new data.Final Answer:
To chain multiple data processing and machine learning steps into one workflow -> Option BQuick Check:
ML Pipelines = chaining steps [OK]
- Confusing pipelines with data visualization tools
- Thinking pipelines store data permanently
- Assuming pipelines are only for SQL queries
Solution
Step 1: Recall Spark ML Pipeline syntax
In Spark ML, the Pipeline constructor expects a parameter namedstageswhich is a list of transformers and estimators.Step 2: Match the correct parameter name
Only pipeline = Pipeline(stages=[tokenizer, hashingTF, lr]) usesstagescorrectly; others use incorrect parameter names.Final Answer:
pipeline = Pipeline(stages=[tokenizer, hashingTF, lr]) -> Option AQuick Check:
Use 'stages' to list pipeline steps [OK]
- Using 'steps' instead of 'stages'
- Using 'chain' or 'process' which are invalid
- Forgetting to pass a list of stages
model.transform(testData)?
from pyspark.ml import Pipeline from pyspark.ml.feature import Tokenizer, HashingTF from pyspark.ml.classification import LogisticRegression # Define stages tokenizer = Tokenizer(inputCol='text', outputCol='words') hashingTF = HashingTF(inputCol='words', outputCol='features') lr = LogisticRegression(maxIter=10, regParam=0.01) pipeline = Pipeline(stages=[tokenizer, hashingTF, lr]) # Fit the pipeline model = pipeline.fit(trainingData) # Transform test data result = model.transform(testData) print(type(result))
Solution
Step 1: Understand what model.transform returns
In Spark ML, callingtransform()on a PipelineModel returns a DataFrame with new columns added by the pipeline stages.Step 2: Identify the output type
The output is a Spark DataFrame, not a list, dict, or PipelineModel.Final Answer:
<class 'pyspark.sql.dataframe.DataFrame'> -> Option DQuick Check:
model.transform() returns DataFrame [OK]
- Thinking transform returns the model itself
- Expecting a Python list or dict instead of DataFrame
- Confusing fit() output with transform() output
from pyspark.ml import Pipeline
from pyspark.ml.feature import Tokenizer, HashingTF
tokenizer = Tokenizer(inputCol='text', outputCol='words')
hashingTF = HashingTF(inputCol='words', outputCol='features')
pipeline = Pipeline(stages=[tokenizer, hashingTF])
model = pipeline.fit(trainingData)
result = model.transform(testData)
print(result.select('prediction').show())Solution
Step 1: Check pipeline stages
The pipeline only has transformers (Tokenizer and HashingTF) but no estimator (like LogisticRegression) to train a model.Step 2: Understand fit() behavior
Fitting a pipeline without an estimator returns a PipelineModel but no trained model for prediction; this is valid but usually incomplete for ML tasks.Step 3: Identify the error
For supervised learning, missing an estimator means no model is trained, so the pipeline is incomplete.Final Answer:
Missing an estimator stage like LogisticRegression before fitting -> Option AQuick Check:
Estimator needed for training model [OK]
- Confusing inputCol names
- Thinking stages must be tuples
- Believing transform() can't be called on PipelineModel
Solution
Step 1: Understand pipeline reuse for batch and streaming
To apply the same transformations and model to streaming data, you must save the trained PipelineModel from batch training.Step 2: Best practice for streaming
Fit the pipeline on batch data, save the PipelineModel, then load it in streaming jobs to transform streaming data consistently.Step 3: Evaluate options
Build a Pipeline with Tokenizer, HashingTF, LogisticRegression; fit on batch data; save and load the PipelineModel for streaming transform follows this best practice. Other options either separate steps manually or train on streaming data first, which is less reliable.Final Answer:
Build a Pipeline with Tokenizer, HashingTF, LogisticRegression; fit on batch data; save and load the PipelineModel for streaming transform -> Option CQuick Check:
Save and reuse PipelineModel for streaming [OK]
- Training model separately from preprocessing
- Trying to train on streaming data first
- Not saving/loading PipelineModel for reuse
Ready to prove it?
Pass the test and this pattern moves unknown
