VAYULearn
Colour theme
Investigate a failure
VAYU Learn

Spark & PySpark

Building a Simple Classifier with Spark MLlib: From Data to Predictions

💡 When data meets decisions — Spark MLlib turns raw input into intelligent predictions.

Spark & PySpark

🚀 Introduction

Machine learning isn’t just about algorithms — it’s about pipelines that scale.
With Apache Spark MLlib, you can train models on massive datasets using a distributed framework, without worrying about infrastructure complexity.

In this tutorial, we’ll walk through building a simple binary classifier in Spark MLlib — step by step, from data loading to prediction.

We’ll predict whether a customer will churn based on attributes like tenure, charges, and service details.

💬 In real-world scenarios, such binary classifiers help businesses identify customers who are likely to leave — enabling proactive retention strategies through personalized offers or service improvements.

Along the way, you’ll learn how to:
✅ Prepare and preprocess data
✅ Build an ML pipeline using transformers and estimators
✅ Train and evaluate your model
✅ Save and reuse the trained model

Let’s dive in. ⚡


⚙️ 1. Setup and Data Loading

We’ll start by creating a sample dataset (customer_churn.csv) directly in Colab — you can replace it later with your real dataset.

# Step 1: Create a sample customer churn dataset
import pandas as pd

data = {
"customerID": ["001", "002", "003", "004", "005", "006", "007", "008"],
"gender": ["Male", "Female", "Female", "Male", "Female", "Male", "Male", "Female"],
"SeniorCitizen": [0, 1, 0, 0, 1, 0, 1, 0],
"Partner": ["Yes", "No", "Yes", "No", "No", "Yes", "No", "Yes"],
"Dependents": ["No", "No", "Yes", "No", "No", "Yes", "No", "Yes"],
"tenure": [1, 34, 2, 45, 5, 22, 50, 10],
"InternetService": ["DSL", "Fiber optic", "DSL", "Fiber optic", "DSL", "DSL", "Fiber optic", "DSL"],
"Contract": ["Month-to-month", "Two year", "Month-to-month", "One year", "Month-to-month", "One year", "Two year", "Month-to-month"],
"MonthlyCharges": [29.85, 56.95, 53.85, 42.30, 70.70, 55.00, 99.65, 35.50],
"TotalCharges": [29.85, 1889.50, 108.15, 1840.75, 353.60, 1215.00, 4999.80, 355.50],
"churn": [1, 0, 1, 0, 1, 0, 0, 1]
}

df_pd = pd.DataFrame(data)
df_pd.to_csv("customer_churn.csv", index=False)
print("✅ Sample dataset 'customer_churn.csv' created successfully!")
df_pd.head()
Code Snippet 1 - Data Loading(Creating Sample Data)

💬 You can use any CSV with similar structure — this is just a test dataset to ensure the pipeline runs correctly.


Load Dataset into Spark

from pyspark.sql import SparkSession

spark = SparkSession.builder.appName("SimpleClassifierExample").getOrCreate()
df = spark.read.csv("customer_churn.csv", header=True, inferSchema=True)

df.printSchema()
df.show(5)
Code Snippet 2 — Spark Session initialization and Loading Sample Data into Spark

💡 Pro Tip: Always inspect schema and data types — Spark MLlib expects numeric columns for most algorithms.


🧩 2. Feature Preparation

Before training, we must transform our raw data into machine-learning–ready format.

  • Categorical columns → encoded with StringIndexer
  • Numeric columns → combined into a single vector via VectorAssembler
from pyspark.ml.feature import StringIndexer, VectorAssembler

# Categorical and numeric columns
categorical_cols = ["gender", "Partner", "Dependents", "InternetService", "Contract"]
numeric_cols = ["SeniorCitizen", "tenure", "MonthlyCharges", "TotalCharges"]

# Index categorical columns
indexers = [StringIndexer(inputCol=col, outputCol=col + "_indexed", handleInvalid="keep")
for col in categorical_cols]

# Assemble all features
assembler_inputs = [col + "_indexed" for col in categorical_cols] + numeric_cols
assembler = VectorAssembler(inputCols=assembler_inputs, outputCol="features")
Code Snippet 3 — Converting raw input columns into a single vector of features

💬 This step converts multiple raw attributes into a unified numeric structure Spark can feed into ML algorithms.


🧱 3. Building the Pipeline

Now we combine preprocessing and modeling steps into a single Spark MLlib Pipeline.
This ensures reproducibility, modularity, and scalability.

from pyspark.ml.classification import LogisticRegression
from pyspark.ml import Pipeline

# Define classifier
lr = LogisticRegression(labelCol="churn", featuresCol="features")

# Combine all stages
stages = indexers + [assembler, lr]
pipeline = Pipeline(stages=stages)
Code Snippet 4 — Spark MLlib Pipeline — combining transformers and estimators
📊 Table 1: Components of the classification pipeline

💡 Pro Tip: Pipelines allow easy swapping — replace Logistic Regression with DecisionTree, RandomForest, or GBTClassifier without changing preprocessing logic.


🔥 4. Model Training

Split your data and train the model:

train_data, test_data = df.randomSplit([0.8, 0.2], seed=42)
model = pipeline.fit(train_data)
Code Snippet 5 — Training the classification model in Spark’s distributed environment

💬 Spark automatically parallelizes training across worker nodes — perfect for large-scale data.


🧮 5. Evaluation

Let’s test the model’s performance on unseen data.

predictions = model.transform(test_data)
predictions.select("customerID", "churn", "prediction", "probability").show(5, truncate=False)
Code Snippet 6 — Model predictions with probabilities for churn

Now compute evaluation metrics using BinaryClassificationEvaluator:

from pyspark.ml.evaluation import BinaryClassificationEvaluator

evaluator = BinaryClassificationEvaluator(labelCol="churn")
accuracy = evaluator.evaluate(predictions)
print(f"Model Accuracy: {accuracy:.2f}")

Code Snippet 7: Model evaluation results — accuracy score displayed
💬 Note:
Since this is a very small demo dataset created for illustration, both accuracy and AUC appear perfect (100%).
In real-world scenarios with larger, more diverse data, expect these metrics to be significantly lower — often between 70–95%, depending on feature quality, data balance, and model tuning.

💡 Pro Tip: For deeper insight, also check AUC-ROC and Precision-Recall metrics:

auc = evaluator.setMetricName("areaUnderROC").evaluate(predictions)
print(f"AUC-ROC: {auc:.2f}")
Code Snippet 8 : AUC-ROC result displayed

💾 6. Saving and Loading the Model

Persist your trained model for reuse:

model.save("models/customer_churn_model")

from pyspark.ml.pipeline import PipelineModel
loaded_model = PipelineModel.load("models/customer_churn_model")
Code Snippet 9 — Trained model saved and reloaded for reuse

💬 This enables smooth deployment — load the model for batch predictions or integrate it with APIs.


🌍 7. Real-World Use Cases

Classification models power real-world business intelligence systems.
Here are a few examples of how MLlib-based pipelines are applied at scale 👇

📊 Table 2: Real-world Classification Applications Powered by Spark MLlib

⚡ 8. Optimization Tips

Get more out of your Spark MLlib classifiers:

📊 Table 3: Optimization Tips for Spark MLlib Models

💡 Pro Tip: Combine CrossValidator with TrainValidationSplit for faster tuning on large datasets — Spark’s distributed evaluation makes hyperparameter search highly efficient.

🧠 How CrossValidator Works:
Spark’s CrossValidator automates model tuning by dividing your training data into multiple folds. It trains models on different parameter combinations and evaluates them across folds using metrics like accuracy or AUC. The best-performing model configuration is automatically selected — ensuring your final model generalizes well to unseen data.

🧭 9. Summary

✅ Built a complete MLlib classification pipeline — from raw data → feature engineering → model → evaluation → saving.
✅ Learned how Spark MLlib abstracts distributed training and transformation.
✅ The same structure scales seamlessly from small CSVs to billions of rows in production.

💬 Whether you’re detecting churn, fraud, or spam — Spark MLlib makes machine learning at scale both simple and powerful.


🧪10. Try It Yourself in Google Colab

Want to experiment with the full working notebook?
Run all the code examples from this blog interactively on Google Colab — no setup needed.

👉 Open in Colab: 🔗 Run “Building a Simple Classifier with Spark MLlib” on Colab

💬 This Colab includes:

  • Pre-created sample dataset (customer_churn.csv)
  • End-to-end Spark MLlib pipeline code
  • Model training, evaluation, and saving

💡 Pro Tip: Fork the notebook and modify feature columns or algorithms (e.g., RandomForestClassifier) to see how accuracy and AUC change in real-time.


🧩 11. Conclusion

Spark MLlib empowers data engineers and ML practitioners to collaborate effectively — turning raw data into actionable insights.
By mastering pipelines and classification, you’re setting a foundation for hyperparameter tuning, model monitoring, and deployment at scale.


🧠 Key Takeaways

  • MLlib pipelines = modular, scalable, and reusable
  • Logistic Regression is a great baseline classifier
  • Spark distributes both computation and storage seamlessly
  • Models can be easily evaluated, tuned, and saved

🧭 What’s Next?

📘 Next Blog: “Recommendation Systems with Spark (MovieLens Example)”
We’ll explore how Spark MLlib powers personalized recommendations at scale — using collaborative filtering on the popular MovieLens dataset.
Get ready to see how data becomes personal insight! 🎬


🔔 Follow for More

If you enjoyed this, follow TheDataForge for your daily Spark in Data Engineering & Machine Learning.
💬 Comment below what kind of models you want covered next!

#ApacheSpark #MachineLearning #BigData #DataEngineering #MLlib #TheDataForge