Lecture 11 - Machine Learning with Spark

Updated 12 Nov 2026

Roadmap

  • Machine Learning Concept
  • Type of Learning
    • Supervised, Unsupervised
  • Evaluation Metrics
    • MSE, MAE, R2
    • Precision, Recall
  • Dataset for training
    • Training, Validation, Test
  • Spark ML Concept
  • ML Algorithm
  • Featurization
  • Pipeline
  • Persistence
  • Utilities

Implementation Cycle

  • Business Understanding — the starting point of the cycle
  • Data Acquisition & Understanding
    • Data Source: On-Premises vs Cloud, Database vs Files
    • Pipeline: Streaming vs Batch, Low vs High Frequency
    • Environment: On-premises vs Cloud, Database vs Data Lake vs .., Small vs Medium vs Big Data
    • Wrangling, Exploration & Cleaning: Structured vs Unstructured, Data Validation and Cleanup, Visualization
  • Modeling
    • Feature Engineering: Transform, Binning, Temporal, Text, Image, Feature Selection
    • Model Training: Algorithms, Ensemble, Parameter Tuning, Retraining, Model management
    • Model Evaluation: Cross Validation, Model Reporting, A/B Testing
  • Deployment
    • Model Store, Web Services, Intelligent Applications
    • Scoring, Performance monitoring, etc.
    • → Customer Acceptance → End
  • Source: https://peritaje.ai

It is a loop, not a straight line: like cooking a new dish for a restaurant — understand what customers want, buy and prep ingredients (data), try recipes (modeling), serve it (deployment), and go back to adjust whenever feedback says it's not right yet.


What is Machine Learning (ML)

  • It is the study of computer algorithms that improve automatically through experience. It is seen as a subset of artificial intelligence.
  • Machine learning algorithms build a mathematical model based on sample data, known as "training data", in order to make predictions or decisions without being explicitly programmed to do so.

Instead of writing rules like "if it has 4 wheels and windows, it's a car", you show the computer thousands of labeled photos and it figures out the rules by itself — like a child learning what a "car" is by seeing many examples.

  • Unsupervised Learning
    • Dimensionality Reduction: Structure Discovery, Feature Elicitation, Meaningful compression, Big data Visualisation
    • Clustering: Recommended Systems, Targetted Marketing, Customer Segmentation
  • Supervised Learning
    • Classification: Image Classification, Customer Retention, Fraud Detection, Diagnostics
    • Regression: Forecasting, Predictions, Process Optimization, New Insights
  • Reinforcement Learning
    • Real-Time Decisions, Robot Navigation, Game AI, Skill Acquisition, Learning Tasks

Type of Learning: Supervised Learning

  • Supervised learning: the training data you feed to the algorithm includes desired solutions, called labels
  • The classic example of supervised learning is a spam filter and image classification
  • Flow: Training Data → Learning Algorithm → Model → Test Data → Accuracy

Like studying with an answer key: you practice on questions that already have the correct answers, so on the real exam (new data) you can answer by yourself.


Supervised Learning: Classification and Regression

  • Regression: to predict the discrete or a continuous value. In some cases, the predicted value can be used to identify the linear relationship between the attributes.
    • Example: "What is the temperature going to be tomorrow?" → Prediction: 84°F
  • Classification: to predict the target class (Yes/No), can be binary and multi class classification
    • Example: "Will it be Cold or Hot tomorrow?" → Prediction: HOT

Regression = "how much?" (a number on a ruler). Classification = "which box?" (pick a category).


Type of Learning: Unsupervised Learning

  • Unsupervised learning: the training data is unlabeled; the system tries to learn without an answer
  • For example, clustering the similar customers, group objects
  • Goal: Find hidden structure in data

Like sorting a bag of mixed LEGO pieces without instructions — nobody tells you the names, but you naturally group them by color and shape.


Type of Learning: Reinforcement Learning

  • The learning system, called an agent in this context, can observe the environment, select and perform actions, and get rewards in return (or penalty)
  • It must then learn by itself what is the best strategy, called a policy, to get the most reward over time
  • For example, AlphaGo
  • Steps:
    1. Observe
    2. Select action using policy
    3. Action!
    4. Get reward or penalty
    5. Update policy (learning step)
    6. Iterate until an optimal policy is found

Like training a dog: no one gives it the answer, but it gets a treat (reward) for sitting and a "no!" (penalty) for chewing shoes, and over time it learns the best behavior.


ML Algorithms

  • START → Dimension Reduction?
    • Yes → Unsupervised Learning: Dimension Reduction
      • Topic Modelling? Yes → Probabilistic? Yes → Latent Dirichlet Analysis; No → Singular Value Decomposition
      • Topic Modelling? No → Principal Component Analysis
    • No → Labelled Data?
  • Labelled Data = No → Unsupervised Learning: Clustering
    • Hierarchical? Yes → Hierarchical
    • No → Need to Specify K? No → DBSCAN
    • Yes → Categorical Variables? Yes → K-modes
    • No → Prefer Probability? Yes → Gaussian Mixture Model; No → K-means
  • Labelled Data = Yes → Predicting Numeric?
    • No → Supervised Learning: Classification
      • Speed or Accuracy? Accuracy → Kernel SVM, Random Forest, Neural Network, Gradient Boosting Tree
      • Speed → Explainable? Yes → Decision Trees, Logistic Regression
      • No → Data is Too large? Yes → Naive Bayes; No → Linear SVM, Naive Bayes
    • Yes → Supervised Learning: Regression
      • Speed or Accuracy? Speed → Decision Trees, Linear Regression
      • Accuracy → Random Forest, Neural Network, Gradient Boosting Tree
  • Source: https://hackernoon.com/beat-the-heat-with-machine-learning-cheat-sheet-cg3u3yk3

Think of it like a "which tool should I use?" quiz: answer a few yes/no questions about your data, and it points you to a reasonable starting algorithm.


Steps of Making a Model in Machine Learning

  • Step 0: Define the problems
    • What is type of your problems?
    • What type of your data?
    • What is your goal?

  • Step 01 – Data collection: web scraping, questionnaire, text, audio, image, video
  • Step 02 – Data preparation: Features, Cleaning, Balancing, Training, Validation
  • Step 03 – Choosing a model: Supervised, Unsupervised, classification, Regression
  • Step 04 – Training: Adjust Weight, Cross Validation
  • Step 05 – Evaluation: Precision, Recall, Sensitivity, Specificity, Accuracy
  • Step 06 – Parameter tuning: Hyper Parameter, No. of cluster, Distance Function
  • Step 07 – Prediction

Like baking: decide what cake you want (Step 0), buy ingredients (collect), wash and measure them (prepare), pick a recipe (model), bake (train), taste it (evaluate), adjust sugar/oven temperature (tune), then serve it (predict).


Define the Problems

  • Identify the business goal
    • What is the business problem?
    • What pain is it causing?
    • Why does this problem need to be resolved?
    • What will happen if you don't solve this problem?
    • How will you measure success?
  • Problem statement: Recently, AnyCompany (a car insurance provider) has seen an increase in global insurance fraud, which is costing them millions of dollars per year in financial losses, administrative overhead, and investigation activity.
  • Business goal: Improve our process to predict fraud for new claims by the end of the calendar year.

Key Steps in Framing the ML Problem

  • Determine what will be observed (feature) and what will be predicted (label)
  • Establish observable, quantifiable metrics
  • Create a strategy for data sourcing
  • Evaluate whether ML is the correct approach
  • Start with a simple model and iterate

  • Data engineer: collects data from data sources (Extract → Load) into the Amazon S3 data lake
  • Data scientist: pre-processes data and engineers features (Transform) — together called data wrangling

ML Data Concepts

  • Example data from classification: features and label
months_as_customerageumbrella_limitvehicle_claimIs this fraud?
32848052080
2284250000003510
13429500000023100
25641600000050720
2284460000004550
  • Sample = one row (e.g. 256, 41, 6000000, 50720)
  • Features = the input columns (months_as_customer, age, umbrella_limit, vehicle_claim)
  • Target (label) = the column to predict (Is this fraud?)

Features are the "clues" a detective looks at; the label is the "verdict" (fraud or not). Each sample is one case file.


Feature Creation and Transformation Generate New Features

  • One feature creation technique is called binning. With binning, you convert continuous data into groups, also called bins.
  • By grouping items, you provide a fixed set of values for the algorithm to work with, which is easier to handle.
  • Binning: Convert values that could fall in a continuous range to a fixed set of categories
ageRate group 1 (25–29)Rate group 2 (30–44)Rate group 3 (45–60)
48001
42010
29100
41010
44010
  • Age is converted into a set of three columns

Like clothing sizes: instead of listing everyone's exact height in cm, you group people into S / M / L — simpler to work with.


Feature Extraction and Selection Reduce Dimensionality

  • High-dimensional data is data in which the number of features is close to or larger than the number of data points. When a dataset has many dimensions (features) to sort through, models have a hard time finding the patterns you want them to identify.
  • Feature selection and dimensionality reduction may help reduce complexity while retaining useful information.
  • Remove features that don't provide measurable value to predict the outcome (e.g. umbrella_limit is crossed out)
months_as_customerageumbrella_limitvehicle_claimIs this fraud?
328480520801
22842500000035101
134295000000231000
256416000000507201
22844600000045500

Packing for a trip: if you bring everything you own, it's hard to find what you need. Keep only the items that actually matter.


Evaluation Metrics

  • Regression metrics: It has continuous output. So, it needs a metric based on calculating some sort of distance between predicted and ground truth.
    • Mean Absolute Error (MAE), Mean Squared Error (MSE)
    • Root Mean Squared Error (RMSE), R2R^2 (R-Squared)
  • Classification metrics: It has discrete output, so it needs a metric that compares discrete classes in some form. Classification Metrics evaluate a model's performance and tell you how good or bad the classification is, but each of them evaluates it in a different way.
    • Accuracy
    • Confusion Matrix (not a metric but fundamental to others)
    • Precision and Recall
    • F1-score

Regression Metrics: Mean Absolute Error (MAE)

  • Mean Absolute Error is the average of the difference between the ground truth and the predicted values. Mathematically, it's represented as:
MAE=1N∑j=1N∣yj−y^j∣\boxed{MAE = \frac{1}{N}\sum_{j=1}^{N} \left| y_j - \hat{y}_j \right|}
  • Where:
    • yjy_j : ground-truth value
    • y^j\hat{y}_j : predicted value from the regression model
    • NN : number of datums

If your GPS says you'll arrive in 30 min but you arrive in 35, the error is 5 min. MAE is simply "on average, how many minutes off was the GPS?" — every miss counts equally.


Regression Metrics: Mean Squared Error (MSE)

  • Mean squared error is perhaps the most popular metric used for regression problems. It essentially finds the average of the squared difference between the target value and the value predicted by the regression model.
MSE=1N∑j=1N(yj−y^j)2\boxed{MSE = \frac{1}{N}\sum_{j=1}^{N} \left( y_j - \hat{y}_j \right)^2}
  • Where:
    • yjy_j : ground-truth value
    • y^j\hat{y}_j : predicted value from the regression model
    • NN : number of datums

Squaring punishes big mistakes much more: being off by 10 costs 100, but being off by 1 costs only 1. Like a teacher who deducts a little for small mistakes but a LOT for a big blunder.


Regression Metrics: Root Mean Squared Error (RMSE)

  • Root Mean Squared Error corresponds to the square root of the average of the squared difference between the target value and the value predicted by the regression model. Basically, MSE\sqrt{MSE}. Mathematically it can be represented as:
RMSE=1N∑j=1N(yj−y^j)2\boxed{RMSE = \sqrt{\frac{1}{N}\sum_{j=1}^{N} \left( y_j - \hat{y}_j \right)^2}}
  • Where:
    • yjy_j : ground-truth value
    • y^j\hat{y}_j : predicted value from the regression model
    • NN : number of datums

MSE is in "squared units" (e.g. dollars²), which is hard to interpret. Taking the square root brings it back to the original unit (dollars), so you can say "the model is typically off by about X dollars".


Regression Metrics: R2R^2 Coefficient of Determination

  • R2R^2 is a measure that provides information about the goodness of fit of a model. It will be close to 1, meaning the regression was able to capture 100% of the variance in the target variable.
  • Total variation in Y (Variance of Y):
SE(Yˉ)=∑i=1N(yi−yˉ)2\boxed{SE(\bar{Y}) = \sum_{i=1}^{N} \left( y_i - \bar{y} \right)^2}
  • Squared error of the regression line:
SE(line)=∑j=1N(yj−y^j)2\boxed{SE(line) = \sum_{j=1}^{N} \left( y_j - \hat{y}_j \right)^2}
  • Percentage of variation described the regression line: SE(line)SE(Yˉ)\dfrac{SE(line)}{SE(\bar{Y})}
    • (more precisely, this ratio is the fraction of variation not explained by the line)
  • Finally, we have our formula for the coefficient of determination, which can tell us how good or bad the fit of the regression line is:
coeff(R2)=1−SE(line)SE(Yˉ)\boxed{coeff(R^2) = 1 - \frac{SE(line)}{SE(\bar{Y})}}
  • Where:
    • yjy_j : ground-truth value
    • yˉ\bar{y} (y_dash) : mean value
    • y^j\hat{y}_j : predicted value from the regression model
    • NN : number of datums
  • Note: the slide writes the total variation as SE(Y)SE(Y) and SE(Yˉ)SE(\bar{Y}) — both mean the same thing (squared error around the mean)

Compare your model against the laziest possible guess: "always predict the average". If your model's errors are tiny compared with that lazy guess, R2≈1R^2 \approx 1. If your model is no better than guessing the average, R2≈0R^2 \approx 0.


Classification Metrics: Confusion Matrix

  • Confusion Matrix is a tabular visualization of the ground-truth labels versus model predictions. Each row of the confusion matrix represents the instances in a predicted class and each column represents the instances in an actual class. It is not exactly a performance metric but sort of a basis on which other metrics evaluate the results.
Ground truth +Ground truth −
Predicted +True positive (TP)False positive (FP)
Predicted −False negative (FN)True negative (TN)
  • Precision: It is the number of correct positive results divided by the number of positive results predicted.
Precision=TPTP+FP\boxed{Precision = \frac{TP}{TP + FP}}
  • Recall: It is the number of correct positive results divided by the number of all relevant samples (all samples that should have been identified as positive).
Recall=TPTP+FN\boxed{Recall = \frac{TP}{TP + FN}}
  • Accuracy:
Accuracy=TP+TNTP+FP+TN+FN\boxed{Accuracy = \frac{TP + TN}{TP + FP + TN + FN}}
  • F1 (F-Score):
F1=2×Precision×RecallPrecision+Recall\boxed{F1 = 2 \times \frac{Precision \times Recall}{Precision + Recall}}

Fishing analogy: Precision = "of all the things I pulled out of the lake, how many were actually fish (not old boots)?" Recall = "of all the fish in the lake, how many did I catch?" F1 balances the two.


Classification Metrics: Confusion Matrix (Example)

  • Classify animal and not animal

  • True Positives = 2
  • True Negatives = 3
  • False Positives = 0
  • False Negatives = 1
MetricValueCalculationFormula
Accuracy83%2+32+3+1+0\frac{2+3}{2+3+1+0}(TP + TN) / (TP + TN + FN + FP)
Precision100%22+0\frac{2}{2+0}TP / (TP + FP)
Recall67%22+1\frac{2}{2+1}TP / (TP + FN)
F1 score80%2⋅1⋅0.671+0.672 \cdot \frac{1 \cdot 0.67}{1 + 0.67}2 * (Precision * Recall) / (Precision + Recall)

The model never called a non-animal an "animal" (precision 100%), but it missed one real animal (recall 67%) — it is careful but a bit shy.


Why Accuracy Can Be Misleading

  • Accuracy may be misleading when the dataset contains highly imbalanced classes.
  • A model that predicts every claim as legitimate achieves 98% accuracy but fails to detect any fraud.
  • Precision measures how many predicted fraud cases are actually fraudulent.
  • Recall measures how many actual fraud cases are successfully detected.
  • Example: Insurance Fraud Detection: 1,000 claims with 20 Fraud items (2%).
    • Model A — Predicts all claims as legitimate
      • 98% Accuracy
      • 0% Fraud Recall
    • Model B — Detects 16 of 20 fraud cases, with 40 false alarms
      • 95.6% Accuracy
      • 80% Fraud Recall
  • Worked check (Model B): TP=16TP = 16, FN=4FN = 4, FP=40FP = 40, TN=980−40=940TN = 980 - 40 = 940
    • Accuracy =16+9401000=95.6%= \frac{16 + 940}{1000} = 95.6\%
    • Recall =1616+4=80%= \frac{16}{16 + 4} = 80\%
    • Precision =1616+40≈28.6%= \frac{16}{16 + 40} \approx 28.6\% (not on slide)

A smoke detector that NEVER beeps is "correct" 99.9% of the days — but it's useless, because it misses the one day there is a real fire. For rare events, look at recall, not just accuracy.


Underfitting, Overfitting, and Generalization

  • Generalization refers to a model's ability to make accurate predictions on data that was not used during training.
  • Underfitting occurs when a model is too simple to capture the underlying patterns in the data. It typically performs poorly on both training and unseen data.
  • Overfitting occurs when a model learns the training data too closely, including noise and irrelevant patterns. It may perform very well on training data but poorly on unseen data. (training loss << validation loss)

Studying for an exam: underfitting = only reading the chapter titles (fail everything); overfitting = memorizing last year's exact answers (ace the practice test, fail the new questions); good fit = actually understanding the concepts.


Dataset for Training the Model

  • Training set is a subset of the dataset used to build predictive models.
  • Validation set is a subset of the dataset used to assess the performance of the model built in the training phase. It provides a test platform for fine-tuning a model's parameters and selecting the best performing model.
  • Test set, or unseen data, is a subset of the dataset used to assess the likely future performance of a model. If a model fits to the training set much better than it fits the test set, overfitting is probably the cause.

Training set = textbook exercises; validation set = practice/mock exam (used to adjust how you study); test set = the real final exam that you must never peek at beforehand.


Dataset for Training the Model – Cross Validation

  • Cross-Validation has two main steps: splitting the data into subsets (called folds) and rotating the training and validation among them.
  • Cross validation is applied over the Train + Validation part (the Test set stays separate)

  • Model accuracy on each validation set:
Round 1Round 2Round 3Round 4Round 5Round 6
93 %91 %83 %94 %90 %95 %
Accuracy=mean(93,91,83,94,90,95)=91 (%)\boxed{Accuracy = \text{mean}(93, 91, 83, 94, 90, 95) = 91\ (\%)}
  • General form (kk folds) (not on slide):
CVscore=1k∑i=1kscorei\boxed{CV_{score} = \frac{1}{k}\sum_{i=1}^{k} score_i}

Like rotating who sits out in a team practice: every player gets a turn being "the tester", so the final score isn't lucky or unlucky because of one particular split.


Roadmap — From Machine Learning Concepts to Distributed Machine Learning

  • Spark ML Concept
  • ML Algorithm
  • Featurization
  • Pipeline
  • Persistence
  • Utilities
  • Spark on local machine

What is Spark ML (MLlib)

  • MLlib is Spark's scalable machine learning library designed for distributed data processing and machine learning, consisting of common learning algorithms and utilities, including classification, regression, and clustering, as well as underlying optimization for parallel and distributed computing.
  • pyspark.ml is the DataFrame-based API for machine learning in Spark. (Primary)
  • pyspark.mllib is the RDD-based API
  • Why Spark ML?
    • Machine Learning Scaling Challenges
    • Easy Data Transformation
    • Scalable Processing of Large Datasets
    • Ease of Creating Pipelines
  • Spark ML – Machine Learning Tools:
    • ML Algorithms
    • Featurization
    • Pipelines
    • Persistence
    • Utilities

scikit-learn is like a single chef cooking in one kitchen; Spark ML is a restaurant chain where the same recipe is cooked in many kitchens (machines) at once — great when the data is too big for one computer.


Spark ML: ML Algorithms

  • These include common learning algorithms such as classification, regression, clustering, and collaborative filtering. MLlib standardizes APIs to make it easier to combine multiple algorithms into a single pipeline.
  • Different learning tasks require different algorithms, input features, and evaluation methods.

  • Predict Category
    • Unlabeled Data → Clustering → ml.clustering
    • Labeled Data → Classification → ml.classification
  • Predict Quantity
    • Regression → ml.regression
  • Predict Similarity
    • Basket Based → Association Rules → ml.fpm
    • User Based → Collaborative Filtering → ml.recommendation

ML Algorithms: Classification

  • Example for Decision Tree Classifier
from pyspark.ml.feature import VectorAssembler
from pyspark.ml.classification import DecisionTreeClassifier
 
data = spark.read.csv("data/insurance_claims.csv", header=True, inferSchema=True) # Load the dataset
train, test = data.randomSplit([0.7, 0.3], seed=42) # Split the dataset
 
# Combine input features into a vector
assembler = VectorAssembler(inputCols=["age", "months_as_customer", "vehicle_claim"],outputCol="features")
trainingData = assembler.transform(train)
testData = assembler.transform(test)
 
# Train a Decision Tree classifier
dt = DecisionTreeClassifier(labelCol="label", featuresCol="features", maxDepth=4)
model = dt.fit(trainingData)
 
predictions = model.transform(testData) # Make predictions
predictions.select("label", "prediction").show(2)
  • Input dataset (insurance_claims.csv):
+---------+---+------------------+--------------+-------------+-----+
| claim_id|age|months_as_customer|umbrella_limit|vehicle_claim|label|
+---------+---+------------------+--------------+-------------+-----+
|CLM000001| 37|               199|             0|        23200|    0|
|CLM000002| 71|               103|             0|         7600|    0|
|CLM000003| 23|                49|             0|        61600|    1|
|CLM000004| 23|                11|        500000|         6900|    1|
|CLM000005| 27|                33|       1000000|        11800|    0|
+---------+---+------------------+--------------+-------------+-----+
  • After VectorAssembler (new features column):
+---------+---+------------------+--------------+-------------+-----+--------------------+
| claim_id|age|months_as_customer|umbrella_limit|vehicle_claim|label|            features|
+---------+---+------------------+--------------+-------------+-----+--------------------+
|CLM000001| 37|               199|             0|        23200|    0|[37.0,199.0,23200.0]|
|CLM000002| 71|               103|             0|         7600|    0| [71.0,103.0,7600.0]|
|CLM000004| 23|                11|        500000|         6900|    1|  [23.0,11.0,6900.0]|
|CLM000005| 27|                33|       1000000|        11800|    0| [27.0,33.0,11800.0]|
|CLM000006| 69|                22|             0|        44700|    0| [69.0,22.0,44700.0]|
+---------+---+------------------+--------------+-------------+-----+--------------------+
  • Predictions output:
+-----+----------+
|label|prediction|
+-----+----------+
|    1|       0.0|
|    0|       0.0|
+-----+----------+
  • Key points:
    • randomSplit([0.7, 0.3], seed=42) → 70% train / 30% test (seed makes the split reproducible)
    • VectorAssembler combines several numeric columns into one vector column (features) — Spark ML models need features in a single vector column
    • fit() trains the model (Estimator → Model); transform() applies it and adds a prediction column

VectorAssembler is like packing each customer's info (age, months, claim) into one lunchbox so the model can carry it as a single item.


ML Algorithms: Classification (with Evaluator)

  • Example for Decision Tree Classifier with Evaluator
from pyspark.ml.evaluation import MulticlassClassificationEvaluator
 
# Select (prediction, true label) and compute test error
accuracyEvaluator = MulticlassClassificationEvaluator(
    labelCol="label", predictionCol="prediction", metricName="accuracy")
 
f1Evaluator = MulticlassClassificationEvaluator(
    labelCol="label", predictionCol="prediction", metricName="f1")
 
accuracy = accuracyEvaluator.evaluate(predictions)
f1 = f1Evaluator.evaluate(predictions)
 
print(f"Accuracy: {accuracy:.4f}")
print(f"Weighted F1-score: {f1:.4f}")
  • MulticlassClassificationEvaluator compares the label column vs the prediction column
  • metricName chooses which metric: "accuracy", "f1" (weighted F1), etc.

ML Algorithms: Clustering

  • Example for KMeans
from pyspark.ml.clustering import KMeans
from pyspark.ml.evaluation import ClusteringEvaluator
#Load the data
raw_dataset = spark.read.format("csv").load("/data/sample_data.csv", header=True, inferSchema=True)
 
assembler = VectorAssembler(inputCols=["col1", "col2"], outputCol="features")
dataset = assembler.transform(raw_dataset)
 
kmeans = KMeans().setK(2).setSeed(1)
model = kmeans.fit(dataset) #Trains a k-means model.
 
predictions = model.transform(dataset) #Make predictions
 
#Evaluate clustering by computing Silhouette score
evaluator = ClusteringEvaluator()
silhouette = evaluator.evaluate(predictions)
print("Silhouette with squared euclidean distance = " + str(silhouette))
 
centers = model.clusterCenters() #Shows the result.
print("Cluster Centers: ")
for center in centers: print(center)
  • setK(2) → number of clusters k=2k = 2; setSeed(1) → reproducible random initialization
  • ClusteringEvaluator computes the Silhouette score (using squared Euclidean distance) — closer to 1 = well-separated clusters
  • clusterCenters() returns the center point of each cluster

K-Means is like placing kk pizza shops in a city: each house goes to its nearest shop, then each shop moves to the middle of its customers, repeat until nothing moves.


Spark ML: Feature Engineering

  • It transforms raw data into representations that machine learning algorithms can process.
  • It may include extracting new features, encoding categorical variables, handling missing values, scaling numerical values, and selecting relevant features.
CategorySpark ML ComponentsPurpose
Feature ExtractionTF-IDF, Word2VecExtract numerical representations from raw data
Feature TransformationTokenizer, StringIndexer, OneHotEncoder, VectorAssemblerConvert features into model-compatible representations
Missing Value HandlingImputerReplace missing numerical values
Feature ScalingStandardScaler, MinMaxScalerAdjust the scale of numerical features
Feature SelectionChiSqSelectorSelect relevant features based on statistical criteria

Feature engineering is the "prep cook" of ML: chopping, washing and measuring raw ingredients so the "chef" (algorithm) can actually cook with them.


Featurization: Dense and Sparse Feature Vectors

  • ML algorithms in Spark commonly represent numerical input features as vectors.
  • DenseVector
    • Stores all feature values, including zeros.
    • Suitable when most feature values are nonzero.
    • Example: [0.0, 3.0, 0.0, 0.0, 2.0]
  • SparseVector
    • Stores the vector size and the indices and values of nonzero elements.
    • Efficient for high-dimensional data containing many zeros. Reduce memory consumption
    • Commonly used in text processing, TF-IDF, and one-hot encoding.
    • Example: (5, [1, 4], [3.0, 2.0])

  • DenseVector: stores every value, including zeros → [0, 3, 0, 0, 2, 0]
  • SparseVector: Size 6, Indices [1, 4], Values [3.0, 2.0]
    • Stores the vector size and the positions and values of nonzero entries.
  • Both representations describe the same six-dimensional vector. Indices start at 0.
  • Format: (size, [indices], [values])

A dense vector is like a full class attendance sheet listing every student, present or absent. A sparse vector only writes down "class size = 40; absent: #3, #17" — much shorter when most entries are the same (zero).


Featurization: TF-IDF

  • Example for Term frequency-inverse document frequency (TF-IDF): Tokenization
from pyspark.ml.feature import HashingTF, IDF, Tokenizer
 
sentenceData = spark.createDataFrame([
    (0.0, "Hi I heard about Spark"), (1.0, "Logistic regression models are neat")],
    ["label", "sentence"])
 
tokenizer = Tokenizer(inputCol="sentence", outputCol="words")
wordsData = tokenizer.transform(sentenceData) #split sentence, create word list
wordsData.select("sentence", "words").show(truncate=False)
+-----+-----------------------------------+------------------------------------------+
|label|sentence                           |words                                     |
+-----+-----------------------------------+------------------------------------------+
|0.0  |Hi I heard about Spark             |[hi, i, heard, about, spark]              |
|1.0  |Logistic regression models are neat|[logistic, regression, models, are, neat] |
+-----+-----------------------------------+------------------------------------------+
  • Tokenizer splits each sentence into a list of lowercase words

Featurization: TF-IDF (Step 2)

  • Step 2: Term Frequency and Inverse Document Frequency
#For each sentence, we use HashingTF to hash the sentence into a feature vector
hashingTF = HashingTF(inputCol="words", outputCol="rawFeatures", numFeatures=20)
featurizedData = hashingTF.transform(wordsData)
 
#Use IDF to rescale the feature vectors; this generally improves performance
idf = IDF(inputCol="rawFeatures", outputCol="features")
idfModel = idf.fit(featurizedData)
rescaledData = idfModel.transform(featurizedData)
rescaledData.select("label", "features").show()
+-----+-----------------------------------+------------------------------------------+--------------------------------------------+
|label|sentence                           |words                                     |rawFeatures                                 |
+-----+-----------------------------------+------------------------------------------+--------------------------------------------+
|0.0  |Hi I heard about Spark             |[hi, i, heard, about, spark]              |(20,[6,8,13,16],[1.0,1.0,1.0,2.0])          |
|1.0  |Logistic regression models are neat|[logistic, regression, models, are, neat] |(20,[3,4,6,11,19],[1.0,1.0,1.0,1.0,1.0])    |
+-----+-----------------------------------+------------------------------------------+--------------------------------------------+
+-----+---------------------------------------------------------------------------------------------+
|label|features                                                                                     |
+-----+---------------------------------------------------------------------------------------------+
|0.0  |(20,[6,8,13,16],[0.0,0.4054651081081644,0.4054651081081644,0.8109302162163288])              |
|1.0  |(20,[3,4,6,11,19],[0.4054651081081644,0.4054651081081644,0.0,0.4054651081081644,0.4054651081081644])|
+-----+---------------------------------------------------------------------------------------------+
  • HashingTF hashes each word into one of numFeatures=20 buckets and counts it → term frequency (TF) as a SparseVector
    • e.g. (20,[6,8,13,16],[1.0,1.0,1.0,2.0]) → size 20; bucket 16 got 2 words (hash collision)
  • IDF is an Estimator (fit → IDFModel) that rescales TF so words appearing in many documents get lower weight
  • Spark's IDF formula (not on slide), where mm = number of documents and DF(t)DF(t) = number of documents containing term tt:
IDF(t)=log⁡m+1DF(t)+1\boxed{IDF(t) = \log\frac{m + 1}{DF(t) + 1}} TFIDF(t,d)=TF(t,d)×IDF(t)\boxed{TFIDF(t, d) = TF(t, d) \times IDF(t)}
  • Check with the output: m=2m = 2
    • Bucket 6 appears in both sentences → log⁡33=0\log\frac{3}{3} = 0 → weight 0.0
    • A bucket in only one sentence → log⁡32≈0.4055\log\frac{3}{2} \approx 0.4055
    • Bucket 16 has TF=2TF = 2 → 2×0.4055≈0.81092 \times 0.4055 \approx 0.8109

TF-IDF is like finding a person's "signature words": "the" appears everywhere so it says nothing (low weight), but "Spark" appearing in only one document tells you what that document is about (high weight).


Featurization: Imputer

  • The Imputer estimator completes missing values in a dataset, using the mean, median or mode of the columns in which the missing values are located.
from pyspark.ml.feature import Imputer
 
df = spark.createDataFrame([
    (1.0, float("nan")),
    (2.0, float("nan")),
    (float("nan"), 3.0),
    (4.0, 4.0),
    (5.0, 5.0)
], ["a", "b"])
 
#Impute with mean value
imputer = Imputer(inputCols=["a", "b"], outputCols=["out_a", "out_b"])
model = imputer.fit(df)
 
model.transform(df).show()
  • Input:
ab
1.0Double.NaN
2.0Double.NaN
Double.NaN3.0
4.04.0
5.05.0
  • Output:
+---+---+-----+-----+
|  a|  b|out_a|out_b|
+---+---+-----+-----+
|1.0|NaN|  1.0|  4.0|
|2.0|NaN|  2.0|  4.0|
|NaN|3.0|  3.0|  3.0|
|4.0|4.0|  4.0|  4.0|
|5.0|5.0|  5.0|  5.0|
+---+---+-----+-----+
  • Default strategy = mean:
    • Mean of a (ignoring NaN) =1+2+4+54=3.0= \frac{1 + 2 + 4 + 5}{4} = 3.0 → fills the NaN in a
    • Mean of b (ignoring NaN) =3+4+53=4.0= \frac{3 + 4 + 5}{3} = 4.0 → fills the NaNs in b

Like filling in a missing exam score with the class average so the gradebook has no blanks.


Spark ML: Pipeline

  • MLlib makes it easier to combine multiple algorithms into a single pipeline, or workflow. The pipeline concept is mostly inspired by the scikit-learn.
  • Use DataFrame from Spark SQL as an ML dataset
  • A Pipeline chains multiple Transformers and Estimators together to specify an ML workflow.
  • Can be persisted (model)

A pipeline is like a car-wash tunnel: the car (DataFrame) enters, goes through soap → brushes → rinse → dry in a fixed order, and comes out finished. You set up the tunnel once and every car goes through the same steps.


Spark ML: Training a Pipeline

  • In Spark ML, each pipeline stage is either a Transformer or an Estimator.
  • Calling Pipeline.fit() produces a fitted PipelineModel.

  • Flow:
    • Training DataFrame → Pipeline: Imputer (Estimator) → VectorAssembler (Transformer) → DecisionTree (Estimator)
    • → PipelineModel = fitted preprocessing stages + trained model
    • Test Data → PipelineModel → Predictions

ML Pipeline: Why It Helps

  • Real-world machine learning workflows often involve multiple preprocessing, feature engineering, model training, and evaluation steps.
  • Managing these steps separately may lead to duplicated code, inconsistent transformations, and difficulties in model maintenance.
  • Pipelines help organize these operations into reusable and reproducible workflows.

Without a pipeline it's like cooking from sticky notes scattered around the kitchen — easy to forget a step or do it differently next time. A pipeline is the single written recipe card.


ML Pipeline: Transformer

  • A Transformer converts an input DataFrame into an output DataFrame using the transform() method. It may generate new feature columns, modify existing representations, or produce model predictions.
  • Example
    • Tokenizer: Converts text into tokens
    • VectorAssembler: Combines feature columns into a feature vector
    • ImputerModel: Replaces missing values using learned statistics
    • DecisionTreeClassificationModel: Generates predictions from input features

Transformer: DF1→ transform() DF2\boxed{\text{Transformer: } DF_1 \xrightarrow{\ \texttt{transform()}\ } DF_2}

A Transformer is like a stamp machine: paper goes in, the same paper comes out with something extra stamped on it (a new column). It doesn't need to "learn" anything first.


ML Pipeline: Estimator

  • An Estimator is a learning algorithm that fits a model to a DataFrame. The fit() method learns parameters or statistics from the training data and produces a Transformer.
  • Return a model, which is a type of transformer
  • Example
    • LogisticRegression.fit() ⇒ LogisticRegressionModel
    • DecisionTreeClassifier → DecisionTreeClassificationModel
    • StandardScaler → StandardScalerModel

Estimator: Data→ fit() Model (a Transformer)\boxed{\text{Estimator: } Data \xrightarrow{\ \texttt{fit()}\ } Model\ (\text{a Transformer})}
  • Example
from pyspark.ml.classification import LogisticRegression
 
lr = LogisticRegression(
    featuresCol="features",
    labelCol="label"
)
 
# Estimator.fit() returns a trained model
model = lr.fit(trainingData)
 
# The trained model is a Transformer
predictions = model.transform(testData)
  • Note: some "preprocessing" steps are also Estimators because they must learn statistics first (e.g. Imputer learns the mean, StandardScaler learns mean/std, IDF learns document frequencies, StringIndexer learns the label list)

An Estimator is a student who must study (fit) before the exam; after studying, the student becomes a "graduate" (Model) who can answer questions (transform).


ML Pipeline: Evaluator

  • An Evaluator measures model performance by comparing predictions with actual labels or by applying an appropriate unsupervised evaluation measure.
  • The evaluate() method returns a numerical performance metric.
  • Examples:
    • RegressionEvaluator: RMSE, MSE, MAE, R2R^2
    • MulticlassClassificationEvaluator: Accuracy, F1-score, Precision, Recall
    • BinaryClassificationEvaluator: ROC-AUC, PR-AUC
    • ClusteringEvaluator: Silhouette Score

  • Example
from pyspark.ml.evaluation import RegressionEvaluator
 
evaluator = RegressionEvaluator(
    labelCol="label",
    predictionCol="prediction",
    metricName="rmse"
)
 
rmse = evaluator.evaluate(predictions)
print("RMSE:", rmse)

The Evaluator is the teacher grading the exam: it compares the student's answers (prediction) with the answer key (label) and gives back one score.


ML Pipeline: How It Works

  • Training Phase: The pipeline is specified as a sequence of stages, and each stage is either a Transformer or an Estimator. These stages are run in order, and DataFrame is transformed as it passes through each stage. The result is a PipelineModel containing the fitted stages.
pipeline.fit(trainingData) → PipelineModel
  • Prediction Phase: PipelineModel.transform(newData) applies the fitted stages to new observations and generates predictions.
pipelineModel.transform(testData) → Predictions

  • During Pipeline.fit():
    • Transformer stages (Tokenizer, HashingTF) → just call transform() and pass the data on
    • Estimator stages (LogisticRegression) → call fit() → becomes a Model (LogisticRegressionModel)
  • The fitted PipelineModel contains only Transformers, so it can transform() new data in one call

ML Pipeline: Text Classification

  • Example for simple Text classification Pipeline
from pyspark.ml import Pipeline
from pyspark.ml.classification import LogisticRegression
from pyspark.ml.feature import HashingTF, Tokenizer
 
#Prepare training documents from a list of (id, text, label) tuples.
training = spark.createDataFrame([
    (0, "a b c d e spark", 1.0),
    (1, "b d", 0.0),
    (2, "spark f g h", 1.0),
    (3, "hadoop mapreduce", 0.0)
], ["id", "text", "label"])
 
#Configure an ML pipeline, which consists of three stages: tokenizer, hashingTF, and lr.
tokenizer = Tokenizer(inputCol="text", outputCol="words")
hashingTF = HashingTF(inputCol=tokenizer.getOutputCol(), outputCol="features")
lr = LogisticRegression(maxIter=10, regParam=0.001)
pipeline = Pipeline(stages=[tokenizer, hashingTF, lr])
 
# Fit the pipeline to training documents.
pipelineModel = pipeline.fit(training)
# Prepare test documents, which are unlabeled (id, text) tuples.
test = spark.createDataFrame([
    (4, "spark i j k"),
    (5, "l m n"),
    (6, "spark hadoop spark"),
    (7, "apache hadoop")
], ["id", "text"])
 
# Make predictions on test documents and print columns of interest.
prediction = pipelineModel.transform(test)
 
predictions.select("id", "text", "probability", "prediction").show(truncate=False)
  • Note: the slide assigns to prediction but then calls predictions.select(...) — the variable names should match (use predictions in both places)
(4, spark i j k) --> prob=[0.6292098489668488,0.37079015103315116], prediction=0.000000
(5, l m n) --> prob=[0.984770006762304,0.015229993237696027], prediction=0.000000
(6, spark hadoop spark) --> prob=[0.13412348342566147,0.8658765165743385], prediction=1.000000
(7, apache hadoop) --> prob=[0.9955732114398529,0.00442678856014711], prediction=0.000000
  • probability = [P(class 0), P(class 1)]; the prediction is the class with the higher probability
  • Training texts containing "spark" were labeled 1.0, so "spark hadoop spark" → 1.0; texts with "hadoop" / unknown words → 0.0

ML Pipeline: Decision Tree

  • Example for Decision Tree Pipeline (Previous Example, make it as pipeline)
from pyspark.ml import Pipeline
from pyspark.ml.classification import DecisionTreeClassifier
from pyspark.ml.feature import StringIndexer, VectorIndexer
from pyspark.ml.evaluation import MulticlassClassificationEvaluator
 
data = spark.read.format("libsvm").load("data/mllib/sample_libsvm_data.txt")
labelIndexer = StringIndexer(inputCol="label", outputCol="indexedLabel").fit(data)
featureIndexer = VectorIndexer(inputCol="features", outputCol="indexedFeatures").fit(data)
 
(trainingData, testData) = data.randomSplit([0.7, 0.3])
 
dt = DecisionTreeClassifier(labelCol="indexedLabel", featuresCol="indexedFeatures")
 
pipeline = Pipeline(stages=[labelIndexer, featureIndexer, dt]) #define pipeline
model = pipeline.fit(trainingData)
 
predictions = model.transform(testData)
predictions.select("prediction", "indexedLabel", "features").show(5)
  • StringIndexer → maps label values to indices (indexedLabel)
  • VectorIndexer → detects categorical features inside the feature vector and indexes them (indexedFeatures)
  • Both indexers are .fit(data) on the whole dataset so that all labels/categories are known before splitting

ML Pipeline: Decision Tree (Evaluation)

  • Example for Decision Tree Pipeline (Previous Example, make it as pipeline) — compute Precision and Recall
# Select (prediction, true label) and compute Precision, Recall
evPrecision = MulticlassClassificationEvaluator(
            labelCol="indexedLabel", predictionCol="prediction", metricName="precisionByLabel")
evRecall = MulticlassClassificationEvaluator(
            labelCol="indexedLabel", predictionCol="prediction", metricName="recallByLabel")
 
precision = evPrecision.evaluate(predictions)
recall = evRecall.evaluate(predictions)
 
print("Precision = %g " % (precision))
print("Recall = %g " % (recall))
Precision = 1
Recall = 0.916667
  • precisionByLabel / recallByLabel → precision/recall for one specific label (default metricLabel=0.0)
  • Result: Precision = 1 → no false positives; Recall ≈ 0.917 → about 1 in 12 actual positives was missed

End-to-End Spark ML Workflow

  • Spark ML Pipelines integrate data preparation, feature engineering, and model training into reusable workflows that can be evaluated and applied to unseen data.

  1. Load Data → DataFrame
  2. Pipeline
    • Preprocessing: Imputer
    • Features: VectorAssembler
    • Learning: DecisionTree
  3. Fitted PipelineModel
  4. Predictions → Evaluation Metrics
  5. Save and Reuse the Model

Hyperparameter Tuning in Spark ML

  • Hyperparameters control the behavior or complexity of a ML algorithm.
  • Spark ML provides ParamGridBuilder to define candidate hyperparameter values and CrossValidator to compare configurations using multiple validation folds.
from pyspark.ml.tuning import ParamGridBuilder, CrossValidator
from pyspark.ml.evaluation import MulticlassClassificationEvaluator
 
paramGrid = (ParamGridBuilder().addGrid(dt.maxDepth, [3, 5, 8]).build()) # dt = Decision Tree
 
evaluator = MulticlassClassificationEvaluator(labelCol="label", predictionCol="prediction",
    metricName="fMeasureByLabel", metricLabel=1.0)
 
cv = CrossValidator(
    estimator=pipeline,
    estimatorParamMaps=paramGrid,
    evaluator=evaluator,
    numFolds=3, seed=42)
 
cvModel = cv.fit(train) # return best model based on F-measure and multiple maxDepth
  • ParamGridBuilder().addGrid(dt.maxDepth, [3, 5, 8]) → try 3 candidate values of maxDepth
  • metricName="fMeasureByLabel", metricLabel=1.0 → choose the model by the F1 of class 1 (e.g. fraud)
  • CrossValidator(..., numFolds=3) → each candidate is trained/validated on 3 folds
  • Number of models trained (not on slide):
#models=(#param combinations)×k=3×3=9\boxed{\#\text{models} = (\#\text{param combinations}) \times k = 3 \times 3 = 9}
  • (plus one final refit of the best setting on the whole training set) → cvModel.bestModel

Like trying on shoes in sizes 3, 5 and 8 — and walking around the store 3 times in each — then buying the pair that felt best on average.


Spark ML: Persistence (Without Persistence)

  • Model persistence allows trained machine learning models to be saved and reused without retraining.
  • Without persistence: A trained model may need to be recreated before reuse.

  • Data Science side:
    • Prototype (Python/R)
    • Create Pipeline
      • Extract raw features
      • Transform features
      • Select key features
      • Fit multiple models
      • Combine results to make prediction
  • Software Engineering side:
    • Re-implement Pipeline for production (Java)
    • Deploy Pipeline
  • Problems:
    • Extra implementation work
    • Different code paths
    • Synchronization overhead

Spark ML: Persistence (With Persistence)

  • A fitted PipelineModel can be saved to storage and loaded for future predictions. It includes supported fitted preprocessing stages and trained model parameters.
  • It reduces the need to repeat training and helps maintain consistent transformations.

  • Data Science: Prototype (Python/R) → Create Pipeline
  • Persist model or Pipeline: model.save("s3n://...")
  • Software Engineering: Load Pipeline (Scala/Java) Model.load("s3n://…") → Deploy in production

Like saving a game: without saving, you have to replay from level 1 every time (retrain). With a save file, anyone — even on a different console (Scala/Java) — can load it and continue.


Pipeline vs. PipelineModel

  • A Pipeline defines the sequence of machine learning operations.
  • A PipelineModel is the result of fitting a Pipeline to training data.
  • Both objects can be persisted, but only the fitted PipelineModel contains the learned models required for prediction.
PipelinePipelineModel
Defines a machine learning workflowContains a fitted machine learning workflow
Includes Transformers and EstimatorsIncludes Transformers and fitted models
Has not necessarily learned model parametersContains parameters learned from training data
Uses fit() to trainUses transform() to predict
Can be saved as a workflow definitionCan be saved and reloaded for prediction
Pipeline.fit(trainingData)→PipelineModel\boxed{\texttt{Pipeline.fit(trainingData)} \rightarrow \texttt{PipelineModel}}

Pipeline = a blank recipe. PipelineModel = the cake already baked from that recipe. You can store both, but only the cake can be served (used for prediction).


Persistence: Read/Save Model

  • Saving a Pipeline preserves its workflow definition, while saving a PipelineModel preserves the fitted stages required for prediction.
from pyspark.ml import PipelineModel
...
dt = DecisionTreeClassifier(labelCol="indexedLabel", featuresCol="indexedFeatures")
pipeline = Pipeline(stages=[labelIndexer, featureIndexer, dt]) #define pipeline
 
trainedPipeline = pipeline.fit(trainingData) # Train a pipeline
 
#Save the pipeline definition
pipeline.write().overwrite().save("/models/fraud_pipeline_definition") # output as directory
 
#Save the fitted pipeline model
model.write().overwrite().save("/models/fraud_pipeline_fitted") # output as directory
 
# Load the fitted pipeline model
loadedModel = PipelineModel.load("/models/fraud_pipeline_fitted")
predictions = loadedModel.transform(test)
predictions.select(“label", "prediction").show(5)
  • Notes on the slide code:
    • The fitted pipeline is stored in trainedPipeline, but the save line uses model — use the same variable (e.g. trainedPipeline.write()...)
    • “label" uses a curly quote on the slide — in real Python it must be "label"
  • .write().overwrite().save(path) → saves as a directory (overwrites if it exists)
  • PipelineModel.load(path) → loads the fitted model back, ready for transform()

Statistical and Data Utilities in Spark

  • It provides statistical and data processing utilities that support data exploration, feature analysis, and machine learning preparation.
  • Statistical analysis helps identify patterns, understand feature distributions, and detect potential data quality issues before model training.
UtilityExample APIPurpose
Summary StatisticsSummarizerCompute numerical statistics for feature vectors
Correlation AnalysisCorrelation.corr()Measure relationships between numerical features
Data SamplingDataFrame.sample()Create random samples
Stratified SamplingDataFrame.sampleBy()Sample observations by category
Hypothesis TestingChiSquareTestTest statistical relationships
Dataset SplittingDataFrame.randomSplit()Split data into training and testing subsets

Summary Statistics for Feature Vectors

  • Calculate Statistics of the dataset (max, min, mean, sum, std, and total count)
from pyspark.ml.stat import Summarizer
from pyspark.sql import Row
from pyspark.ml.linalg import Vectors
 
 
df = spark.createDataFrame([ (Vectors.dense(1.0, 1.0, 1.0),),
                            (Vectors.dense(1.0, 2.0, 3.0),)], ["features"])
 
# create summarizer for multiple metrics
summarizer = Summarizer.metrics("mean","std","count","min","max","sum")
 
 
df.select(summarizer.summary(df.features).alias("summary")).select("summary.*").show(truncate=False)
  • Input:
+-------------+
|     features|
+-------------+
|[1.0,1.0,1.0]|
|[1.0,2.0,3.0]|
+-------------+
  • Output:
+-------------+---------------------------------------------+-----+-------------+-------------+-------------+
|mean         |std                                          |count|min          |max          |sum          |
+-------------+---------------------------------------------+-----+-------------+-------------+-------------+
|[1.0,1.5,2.0]|[0.0,0.7071067811865476,1.4142135623730951]  |2    |[1.0,1.0,1.0]|[1.0,2.0,3.0]|[2.0,3.0,4.0]|
+-------------+---------------------------------------------+-----+-------------+-------------+-------------+
  • Statistics are computed per position (column) of the vector
  • std is the sample standard deviation (divides by n−1n-1) (not on slide):
s=1n−1∑i=1n(xi−xˉ)2\boxed{s = \sqrt{\frac{1}{n-1}\sum_{i=1}^{n}\left(x_i - \bar{x}\right)^2}}
  • Check, 3rd position: values 1,31, 3 → xˉ=2\bar{x} = 2 → s=(1−2)2+(3−2)21=2≈1.414s = \sqrt{\frac{(1-2)^2 + (3-2)^2}{1}} = \sqrt{2} \approx 1.414

Utility: Correlations

  • Calculate Correlations of the dataset
from pyspark.ml.linalg import Vectors
from pyspark.ml.stat import Correlation
 
data = [(Vectors.sparse(4, [(0, 1.0), (3, -2.0)]),), #item, non-zero position, values => [1,0,0,-2]
        (Vectors.dense([4.0, 5.0, 0.0, 3.0]),),
        (Vectors.dense([6.0, 7.0, 0.0, 8.0]),),
        (Vectors.sparse(4, [(0, 9.0), (3, 1.0)]),)] #[9,0,0,1]
 
df = spark.createDataFrame(data, ["features"])
 
r1 = Correlation.corr(df, "features").head()
print("Pearson correlation matrix:\n" + str(r1[0]))
Pearson correlation matrix:
DenseMatrix([[1.        , 0.05564149,        nan, 0.40047142],
             [0.05564149, 1.        ,        nan, 0.91359586],
             [       nan,        nan, 1.        ,        nan],
             [0.40047142, 0.91359586,        nan, 1.        ]])
  • Vectors.sparse(4, [(0, 1.0), (3, -2.0)]) → size 4, position 0 = 1.0, position 3 = −2.0 → [1, 0, 0, -2]
  • The result is a 4 × 4 matrix: entry (i,j)(i, j) = correlation between feature ii and feature jj; the diagonal is always 1
  • Feature 2 is always 0 (no variance) → its correlation is nan (division by zero)
  • Features 1 and 3 have a strong positive correlation (0.9136)
  • Pearson correlation (default method) (not on slide):
rXY=∑i=1n(xi−xˉ)(yi−yˉ)∑i=1n(xi−xˉ)2 ∑i=1n(yi−yˉ)2\boxed{r_{XY} = \frac{\sum_{i=1}^{n}(x_i - \bar{x})(y_i - \bar{y})}{\sqrt{\sum_{i=1}^{n}(x_i - \bar{x})^2}\,\sqrt{\sum_{i=1}^{n}(y_i - \bar{y})^2}}}
  • r=+1r = +1 → perfect positive linear relationship, r=−1r = -1 → perfect negative, r=0r = 0 → no linear relationship

Correlation is like checking whether two friends' moods move together: if one is happy whenever the other is happy, rr is close to +1. A friend whose mood never changes (always 0) can't be compared at all → nan.


Summary

  • Machine Learning Concept
  • Type of Learning
    • Supervised, Unsupervised
  • Evaluation Metrics
    • MSE, MAE, R2
    • Precision, Recall
  • Dataset for training
    • Training, Validation, Test
  • Spark ML Concept
  • ML Algorithm
  • Featurization
  • Pipeline
  • Persistence
  • Utilities