DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Last call! Secure your stack and shape the future! Help dev teams across the globe navigate their software supply chain security challenges.

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workloads.

Releasing software shouldn't be stressful or risky. Learn how to leverage progressive delivery techniques to ensure safer deployments.

Avoid machine learning mistakes and boost model performance! Discover key ML patterns, anti-patterns, data strategies, and more.

Related

  • Automating Data Pipelines: Generating PySpark and SQL Jobs With LLMs in Cloudera
  • Recursive Feature Elimination in Practice
  • Text Clustering With Deepseek Reasoning
  • Personalized Product Recommendations in E-Commerce Using ML

Trending

  • Why High-Performance AI/ML Is Essential in Modern Cybersecurity
  • Docker Model Runner: Streamlining AI Deployment for Developers
  • A Modern Stack for Building Scalable Systems
  • Kubeflow: Driving Scalable and Intelligent Machine Learning Systems
  1. DZone
  2. Data Engineering
  3. AI/ML
  4. Building a Machine Learning Pipeline Using PySpark

Building a Machine Learning Pipeline Using PySpark

This article discusses building an efficient ML pipeline with PySpark, covering data loading, preprocessing, model training, and evaluation for large datasets.

By 
Abhishek Trehan user avatar
Abhishek Trehan
·
Jan. 30, 25 · Tutorial
Likes (1)
Comment
Save
Tweet
Share
3.8K Views

Join the DZone community and get the full member experience.

Join For Free

In this article, we will look at an example of a complete machine learning (ML) pipeline using Python and PySpark. This pipeline includes data loading, preprocessing, feature engineering, model training, and evaluation. 

The main idea here is to provide you with a jump start on building your own ML pipelines. We will use Spark capabilities to build the pipeline. PySpark offers ML libraries that are very powerful and efficient when it comes to processing large volumes of data. 

PySpark ML Pipeline

This is the code for the PySpark ML Pipeline:

Plain Text
 
from pyspark.sql import SparkSession
from pyspark.ml import Pipeline
from pyspark.ml.feature import StringIndexer, VectorAssembler, StandardScaler
from pyspark.ml.classification import LogisticRegression
from pyspark.ml.evaluation import MulticlassClassificationEvaluator
# Initialize Spark session
spark = SparkSession.builder \
.appName("PySpark ML Pipeline") \
.getOrCreate()
# Load data
data_path = "path/to/your/data.csv" # Replace with your data file
df = spark.read.format("csv") \
.option("header", "true") \
.option("inferSchema", "true") \
.load(data_path)
# Show data schema
df.printSchema()
# Select features and target column
feature_cols = ["feature1", "feature2", "feature3"] # Replace with actual column names
target_col = "target" # Replace with actual target column name
# Preprocessing: Convert target column to numeric using StringIndexer
label_indexer = StringIndexer(inputCol=target_col, outputCol="label")
# Assemble features into a single vector
assembler = VectorAssembler(inputCols=feature_cols, outputCol="raw_features")
# Standardize features
scaler = StandardScaler(inputCol="raw_features", outputCol="features")
# Model: Logistic Regression
lr = LogisticRegression(featuresCol="features", labelCol="label")
# Create a pipeline
pipeline = Pipeline(stages=[label_indexer, assembler, scaler, lr])
# Split data into training and testing sets
train_df, test_df = df.randomSplit([0.8, 0.2], seed=42)
# Train the model
model = pipeline.fit(train_df)
# Make predictions
predictions = model.transform(test_df)
# Evaluate the model
evaluator = MulticlassClassificationEvaluator(
labelCol="label",
predictionCol="prediction",
metricName="accuracy"
)
accuracy = evaluator.evaluate(predictions)
print(f"Test Accuracy: {accuracy:.2f}")
# Stop the Spark session
spark.stop()


Explanation of Components

1. Data Loading

This loads a CSV dataset using Spark’s DataFrame API with schema inference.

2. Preprocessing

  • StringIndexer: This converts categorical labels (target column) to numeric indices for compatibility with ML algorithms.
  • VectorAssembler: This combines multiple feature columns into a single vector.
  • StandardScaler: This normalizes the feature vector for better model performance.

3. Model

A Logistic Regression classifier is used for binary or multiclass classification.

4. Pipeline

Combines all preprocessing steps and the model into a single pipeline for streamlined processing.

5. Training and Testing

  • Splits the data into training (80%) and testing (20%) sets.
  • Fits the pipeline on the training data and evaluates it on the testing data.

6. Evaluation

Uses MulticlassClassificationEvaluator to calculate the accuracy of predictions.

Extending the Pipeline

  • Feature engineering: Add more stages, like PCA for dimensionality reduction or OneHotEncoder for categorical features.
  • Hyperparameter tuning: Use Spark’s CrossValidator or TrainValidationSplit for hyperparameter optimization.
  • Model persistence: Save the pipeline model using model.write().overwrite().save(“model_path”).

Conclusion

The key takeaway here is if you are working in a Spark environment, avoid converting the Spark data frame to a numpy or pandas as those are resource and time-intensive operations, and you will lose the Spark performance edge. Having tested various versions of this code, this one stands out as the most efficient. You can gain further efficiency if you decide to read the source data in parquet format instead of CSV.

Overall, this pipeline is modular and scalable, suitable for large datasets, and easily adaptable to different machine learning problems. This is a quick and effective implementation that can easily scale with your changing needs. We used logistic regression as an example in this article, but you can easily extend this pipeline to use linear regression and other supervised learning techniques.

Data structure Machine learning Pipeline (software) pyspark

Opinions expressed by DZone contributors are their own.

Related

  • Automating Data Pipelines: Generating PySpark and SQL Jobs With LLMs in Cloudera
  • Recursive Feature Elimination in Practice
  • Text Clustering With Deepseek Reasoning
  • Personalized Product Recommendations in E-Commerce Using ML

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!