Data Science Complete Notes
Data Science Complete Notes
1
Data Science Tawqeer ul Islam
2
Data Science Tawqeer ul Islam
o Supply Chain Optimization: Improving efficiency and reducing costs in the supply
chain.
o Example: A factory using sensor data to predict when a machine part will fail,
allowing for proactive replacement.
7. Social Media:
o Content Recommendation: Suggesting posts, friends, or groups.
o Fake News Detection: Identifying and flagging misinformation.
o Influence Analysis: Identifying key influencers within a network.
o Example: Twitter suggesting accounts to follow.
3. Data Lifecycle
The data lifecycle describes the sequence of stages that data goes through from its initial
generation or acquisition to its eventual archival or deletion. While variations exist, a
common framework includes:
Phases of the Data Lifecycle:
1. Data Acquisition (or Generation/Collection):
o Description: The process of gathering raw data from various sources. This is the
starting point.
o Activities: Identifying data sources, collecting data (e.g., through sensors, surveys,
web scraping, APIs, databases).
o Considerations: Data relevance, quality, volume, velocity, variety, cost of
acquisition.
o Example: Collecting Twitter data via its API for sentiment analysis; extracting sales
records from a company's CRM.
2. Data Cleaning (or Preprocessing/Preparation):
o Description: Transforming raw data into a clean, usable, and understandable
format. This is often the most time-consuming phase.
o Activities:
▪ Handling Missing Values: Imputation (mean, median, mode, regression) or
deletion.
▪ Handling Outliers: Detection (Z-score, IQR) and treatment (removal,
transformation, capping).
▪ Data Transformation: Normalization, standardization, log transformation.
▪ Data Type Conversion: Ensuring data is in the correct format (e.g., string to
numeric).
▪ Removing Duplicates: Identifying and deleting redundant records.
3
Data Science Tawqeer ul Islam
4
Data Science Tawqeer ul Islam
5
Data Science Tawqeer ul Islam
o Example: A bank needing to explain to a customer why their loan application was
rejected by an AI model.
4. Accountability and Responsibility:
o Issue: Who is responsible when an AI system makes a harmful decision or error?
The developer, the user, the organization?
o Mitigation: Establishing clear lines of responsibility, robust testing and validation
processes, human oversight for critical decisions, mechanisms for redress.
o Example: Determining accountability if a self-driving car causes an accident due
to an algorithmic flaw.
5. Data Security:
o Issue: Protecting data from unauthorized access, use, disclosure, alteration, or
destruction.
o Mitigation: Implementing strong security measures (firewalls, intrusion detection
systems, encryption), regular security audits, employee training on data security
best practices.
o Example: Preventing hackers from accessing a database containing sensitive
medical records.
6. Informed Consent:
o Issue: Ensuring individuals understand how their data will be collected, used, and
shared, and that they willingly agree to it.
o Mitigation: Clear and concise privacy policies, explicit consent mechanisms,
allowing users to opt-out or control their data.
o Example: A mobile app clearly stating how location data will be used and asking
for user permission before collecting it.
7. Potential for Misuse:
o Issue: Data science tools and findings can be used for malicious purposes (e.g.,
surveillance, manipulation, spreading disinformation).
o Mitigation: Ethical guidelines for developers and practitioners, promoting
responsible innovation, public awareness and education.
o Example: Using AI to create deepfakes for spreading false information.
6
Data Science Tawqeer ul Islam
7
Data Science Tawqeer ul Islam
8
Data Science Tawqeer ul Islam
3. Tertiary Data Sources: (Less common in direct data science input, more for
background)
o Definition: Collections or summaries of primary and secondary sources.
o Examples: Encyclopedias, almanacs, literature reviews, indexes.
o Use: Primarily for finding primary or secondary sources, or for general
understanding.
B. Data Types:
How data is structured and its nature.
I. Based on Structure:
1. Structured Data:
o Definition: Highly organized data that conforms to a predefined data model or
schema. Typically stored in relational databases (SQL) in tables with rows and
columns.
o Characteristics: Easily searchable, manageable, and analyzable using traditional
tools.
o Examples:
▪ Relational database tables (e.g., customer information with fields
like CustomerID, Name, Address, Email).
▪ Spreadsheets (e.g., Excel files).
▪ CSV files.
o Pros: Easy to query and analyze, mature tools available.
o Cons: Rigid schema, less flexible for evolving data needs.
2. Unstructured Data:
o Definition: Data that does not have a predefined format or organization. It's often
qualitative and does not fit neatly into rows and columns.
o Characteristics: Difficult to process and analyze using traditional methods; requires
specialized techniques like NLP, image processing.
o Examples:
▪ Text documents (e.g., emails, articles, social media posts, PDF files).
▪ Images (e.g., JPEGs, PNGs).
▪ Audio files (e.g., MP3s, WAVs).
▪ Video files (e.g., MP4s, MOVs).
o Pros: Rich source of information, highly flexible.
o Cons: Difficult and resource-intensive to process and analyze, requires advanced
tools.
9
Data Science Tawqeer ul Islam
3. Semi-structured Data:
o Definition: Data that does not conform to the rigid structure of relational databases
but contains tags or markers to separate semantic elements and enforce hierarchies
of records and fields. It has some organizational properties but is not as strictly
defined as structured data.
o Characteristics: Easier to process than unstructured data but more flexible than
structured data.
o Examples:
▪ JSON (JavaScript Object Notation) files.
▪ XML (eXtensible Markup Language) files.
▪ NoSQL databases (some types, e.g., document databases like MongoDB).
▪ Log files.
o Pros: More flexible than structured data, easier to parse than unstructured data.
o Cons: Querying can be more complex than structured data.
Comparison Table: Structured vs. Unstructured vs. Semi-structured Data
II. Based on Nature (Measurement Scales - often associated with Statistical data types):
1. Qualitative Data (Categorical Data):
o Definition: Describes qualities or characteristics. It cannot be measured numerically
but can be categorized.
o Types:
▪ Nominal Data: Categories without any intrinsic order or ranking.
▪ Examples: Gender (Male, Female, Other), Colors (Red, Blue, Green),
Marital Status (Single, Married, Divorced).
▪ Operations: Counting, frequency, mode.
10
Data Science Tawqeer ul Islam
11
Data Science Tawqeer ul Islam
o Types:
▪ Closed-ended questions: Provide predefined answer choices (e.g., multiple-
choice, Likert scale). Easier to analyze.
▪ Open-ended questions: Allow respondents to answer in their own words.
Provide richer, qualitative insights but harder to analyze.
o Pros: Can collect data from a large sample, relatively inexpensive (especially
online), can gather both quantitative and qualitative data.
o Cons: Potential for response bias, low response rates, poorly designed questions
can lead to misleading data.
o Example: A company sending out an online survey to customers to gather feedback
on a new product.
2. Interviews:
o Description: Collecting data through direct verbal interaction with individuals.
Can be structured (predefined questions), semi-structured (guiding questions with
flexibility), or unstructured (conversational).
o Pros: Allows for in-depth information, clarification of responses, can capture non-
verbal cues.
o Cons: Time-consuming, expensive, potential for interviewer bias, results can be
hard to generalize.
o Example: Conducting one-on-one interviews with subject matter experts to
understand industry challenges.
3. Observations:
o Description: Collecting data by systematically watching and recording behaviors,
events, or characteristics in their natural setting or a controlled environment.
o Types: Participant (researcher is involved) vs. Non-participant (researcher is
detached), Covert vs. Overt.
o Pros: Provides direct information about behavior, captures context, can reveal
unstated needs.
o Cons: Potential for observer bias (Hawthorne effect if overt), can be time-
consuming, ethical concerns if covert.
o Example: A retail store observing how shoppers navigate aisles to optimize store
layout.
4. Experiments:
o Description: Collecting data by manipulating one or more independent variables
and observing the effect on a dependent variable, while controlling for other
extraneous variables.
o Key Elements: Control group, treatment group, randomization.
o Pros: Can establish cause-and-effect relationships, high level of control.
12
Data Science Tawqeer ul Islam
13
Data Science Tawqeer ul Islam
14
Data Science Tawqeer ul Islam
15
Data Science Tawqeer ul Islam
▪ Use: When algorithms don't assume a specific distribution (e.g., KNN, Neural
Networks).
▪ Standardization (Z-score Normalization): Rescales features to have zero mean
and unit variance. Formula: X_std = (X - mean(X)) / std_dev(X).
▪ Use: When algorithms assume data is centered around zero and has a
standard deviation of 1 (e.g., PCA, SVM, Logistic Regression).
▪ Log Transformation: Apply log(X) to reduce right skewness and the effect of
outliers.
▪ Binning/Discretization: Convert continuous variables into categorical bins
(e.g., age groups from age).
o Example: Standardizing 'Income' and 'Age' features before applying a K-Means
clustering algorithm.
4. Encoding Categorical Data:
o Problem: Most machine learning algorithms require numerical input.
o Techniques:
▪ Label Encoding: Assigns a unique integer to each category.
▪ Use: For ordinal data where order matters (e.g., Small=0, Medium=1,
Large=2).
▪ Caution: Can mislead algorithms into assuming an ordinal relationship for
nominal data.
▪ One-Hot Encoding (Dummy Variables): Creates new binary (0/1) columns for
each category.
▪ Use: For nominal data where no order exists (e.g., Color: Red -> [1,0,0],
Green -> [0,1,0], Blue -> [0,0,1]).
▪ Caution: Can lead to high dimensionality if many unique categories (curse of
dimensionality).
▪ Frequency Encoding: Replace categories with their frequencies in the dataset.
▪ Target Encoding (Mean Encoding): Replace categories with the mean of the
target variable for that category. (Risk of overfitting, often requires
regularization).
o Example: One-hot encoding a 'City' column (London, Paris, New York) into three new
binary columns.
5. Handling Duplicate Data:
o Problem: Identical or near-identical records can skew analysis and model training.
o Techniques: Identify and remove duplicate rows. For near-duplicates (e.g., slight
variations in addresses), techniques like fuzzy matching might be needed.
o Example: Removing a customer record that appears twice with the exact same
information.
16
Data Science Tawqeer ul Islam
17
Data Science Tawqeer ul Islam
18
Data Science Tawqeer ul Islam
Arrange the data in the increasing order and then find the mid value.
If we have even number of values in the data set then median is sum of mid two numbers
divided by 2
In we have odd number in the data set like below we have 9 heights the median will be
5th number value.
19
Data Science Tawqeer ul Islam
Mode: Mode is the number which occur most often in the data set. Here 150 is occurring
twice so this is our mode.
Variance: Variance is the numerical values that describe the variability of the observations
from its arithmetic mean and denoted by sigma-squared(σ2 )
Variance measure how far individuals in the group are spread out, in the set of data from
the mean.
Where
Xi : Elements in the data set
µ : the population mean
Step 1: This formula says that take each element from dataset(population) and subtract
from mean of data set. Later sum all the values.
Step 2: Take the sum in Step 1 and divide by total number of elements.
Square in the above formula will nullify the effect of negative sign(-).
20
Data Science Tawqeer ul Islam
21
Data Science Tawqeer ul Islam
22
Data Science Tawqeer ul Islam
3. Scatterplots
• Definition: Uses dots to show the relationship between two numerical variables
(one on X-axis, one on Y-axis).
• Shows: Relationship type (positive, negative, none), strength, form (linear, non-
linear), clusters, outliers.
• Use: Exploring relationships between two numerical variables, identifying
correlations.
• Read: Position of dots indicates paired values. Pattern of dots reveals relationship.
• Variations: Scatterplot Matrix (all pairs), Bubble Chart (size for 3rd variable),
color/shape for categorical variable, regression line.
• Pros: Clear relationship display, identifies patterns/outliers, can encode 3rd/4th
variable.
• Cons: Overplotting with large N, correlation ≠ causation, mainly for two primary
variables.
• Example: Relationship between hours studied and exam scores.
23
Data Science Tawqeer ul Islam
• Types/Techniques:
o Choropleth Maps: Areas shaded by variable value (e.g., population density
by state).
o Point Maps: Dots/symbols at coordinates representing events/features
(e.g., earthquake locations).
o Heatmaps (on Maps): Color intensity for density/magnitude in geographic
space (e.g., crime hot spots).
o Flow Maps: Lines/arrows showing movement between locations (e.g.,
migration routes).
o Contour Maps: Lines connecting points of equal value (e.g., elevation).
o Cartograms: Area distorted by a data variable (e.g., country size by
population).
• Pros: Intuitive for geo-data, powerful for spatial patterns, conveys much
information.
• Cons: Can be complex to create, choropleth issues (color choice, MAUP), map
projection distortions, overplotting.
• Example: Mapping disease cases by county to identify high-risk areas.
Visulaization in Matplotlib
Matplotlib is a powerful plotting library in Python used to create a wide variety of static,
animated, and interactive visualizations. It is especially well-known for its flexibility and
ability to produce publication-quality plots.
• Library Type: Data visualization
• Primary Module: pyplot
• Key Features:
o Supports line plots, scatter plots, bar charts, histograms, pie charts, and
more.
o Allows customization of plots, including colors, labels, and styles.
o Integrates with other Python libraries like NumPy and Pandas for data
handling.
2. Basic Usage
Matplotlib’s primary module is pyplot, usually imported as plt:
# Basic data
x = [1, 2, 3, 4]
y = [10, 20, 25, 30]
# Create plot
24
Data Science Tawqeer ul Islam
[Link](x, y)
[Link](x, y)
• Scatter Plot: Useful for showing relationships between two variables.
[Link](x, y)
[Link](x, y)
25
Data Science Tawqeer ul Islam
[Link](y, bins=10)
• Box Plot: A Box Plot (a.k.a. Box-and-Whisker Plot) is used to display the distribution of a
dataset based on:
o Median (Q2)
o First Quartile (Q1, 25th percentile)
o Third Quartile (Q3, 75th percentile)
o Interquartile Range (IQR = Q3 - Q1)
o Outliers (points outside 1.5 * IQR range)
[Link](y, vert=True, patch_artist=True,
boxprops=dict(facecolor='lightblue'))
26
Data Science Tawqeer ul Islam
• How to calculate:
o If odd number of elements → Middle value.
o If even number of elements → Average of the two middle values.
• In a Box Plot: Represented by the horizontal line inside the box.
Example:
Data: [2, 4, 7, 10, 15]
Median = 7 (middle value)
Hex Bin: A Hexbin Plot (Hexagonal Binning Plot) is useful for visualizing the density of points in a
2D space.
• Instead of scatter plots, where overlapping points are hard to interpret, Hexbin groups data into
hexagonal bins.
• The color intensity represents the density (number of points in each bin).
27
Data Science Tawqeer ul Islam
5. Customization
Matplotlib allows deep customization of almost every aspect of a plot.
[Link]([1, 2, 3, 4])
[Link]([10, 20, 30])
• Axis Limits: Set the range of the axes.
[Link]([0, 5])
[Link]([0, 35])
c. Line Style, Colors, and Markers
• Change line style, color, and marker:
[Link]('[Link]')
7. Working with Multiple Figures
You can create and manage multiple figures simultaneously:
# Create figure 1
[Link](1)
[Link](x, y)
# Create figure 2
[Link](2)
[Link](y, x)
Example:
import [Link] as plt
# Basic data
28
Data Science Tawqeer ul Islam
x = [1, 2, 3, 4, 5, 6]
y = [10, 20, 25, 30, 45, 43]
# Add annotations
for i, txt in enumerate(y):
[Link](txt, (x[i], y[i]), textcoords="offset points",
xytext=(0, 10), ha="center", fontsize=10, color="black")
# Add legend
[Link](loc="upper left", fontsize=10, edgecolor="black")
• Figure size
• Line style: Dashed (--), color: Dark blue, marker: Circles (o)
• Axis limits
29
Data Science Tawqeer ul Islam
30
Data Science Tawqeer ul Islam
31
Data Science Tawqeer ul Islam
32
Data Science Tawqeer ul Islam
33
Data Science Tawqeer ul Islam
34
Data Science Tawqeer ul Islam
is to predict whether someone will play tennis on a given day based on four weather
attributes.
The ID3 (Iterative Dichotomiser 3) algorithm, developed by Ross Quinlan, is a fundamental
decision tree learning algorithm. It uses the concept of Information Gain to greedily select
the best attribute for splitting the data at each node of the tree.
2. The Dataset
The dataset consists of 14 instances, each representing a day. There are four input
attributes (Outlook, Temperature, Humidity, Wind) and one target attribute (Play), which
is a binary classification (Yes or No).
35
Data Science Tawqeer ul Islam
where Values(A) is the set of unique values for attribute A, Sv is the subset of S where
attribute A has value v, ∣Sv∣ is the number of instances in Sv, and ∣S∣ is the total number of
instances in S. The ID3 algorithm selects the attribute with the highest Information Gain at
each step.
4. Building the Decision Tree: Step-by-Step
We start with the entire dataset (S) at the root node.
Step 1: Calculate the Entropy of the Root Node (Entropy of the 'Play' attribute)
Total instances = 14
Play = Yes: 9
Play = No: 5
P(Yes)=9/14≈0.643
P(No)=5/14≈0.357
2. Outlook = Overcast:
o Instances: 4 (D3, D7, D12, D13)
o Play = Yes: 4 (D3, D7, D12, D13)
36
Data Science Tawqeer ul Islam
o Play = No: 0
o
(Perfectly pure)
3. Outlook = Rain:
o Instances: 5 (D4, D5, D6, D10, D14)
Rain instances are D4, D5, D6, D10, D14. Among these, Yes are D4, D5 (2
instances). No are D6, D10, D14 (3 instances).
o Play = Yes: 2
o Play = No: 3
(Same as Sunny)
Now calculate the weighted average entropy for Outlook:
Attribute: Temperature
Values: Hot, Mild, Cool
1. Temperature = Hot: Instances: 4 (D1, D2, D3, D13). Play: Yes=2, No=2.
2. Entropy =
Temperature = Mild: Instances: 6 (D4, D8, D10, D11, D12, D14).
o Play: Yes=4, No=2
3. Temperature = Cool: Instances: 4 (D5, D6, D7, D9). Play: Yes=3 (D5, D7, D9), No=1
(D6).
37
Data Science Tawqeer ul Islam
Attribute: Humidity
Values: High, Normal
1. Humidity = High: Instances: 7 (D1, D2, D3, D4, D8, D12, D14). Play: Yes=3 (D3, D4,
D12), No=4 (D1, D2, D8, D14).
2. Humidity = Normal: Instances: 7. Yes: D5, D7, D9, D11, D13 (5 instances). No: D6,
D10 (2 instances).
Attribute: Wind
Values: Weak, Strong
1. Wind = Weak: Instances: 8 (D1, D3, D4, D5, D8, D9, D12, D13). Play: Yes=6 (D3, D4,
D5, D9, D12, D13), No=2 (D1, D8).
2. Wind = Strong: Instances: 6 Yes (D7, D11), No (D2, D6, D10, D14). Total 6 instances.
Yes=2, No=4.
38
Data Science Tawqeer ul Islam
39
Data Science Tawqeer ul Islam
40
Data Science Tawqeer ul Islam
Entropy ≈0.918≈0.918
▪ Weighted Entropy = (2/5)*1 + (3/5)*0.918
≈0.4+0.551=0.951≈0.4+0.551=0.951
▪ Gain(SRain, Humidity) = 0.971−0.951=0.020.971−0.951=0.02
o Gain on Wind for SRain:
▪ Weak (2 instances: D4, D5): 2 Yes, 0 No. Entropy = 0.
▪ Strong (3 instances: D6, D10, D14): 0 Yes, 3 No. Entropy = 0.
▪ Weighted Entropy = (2/5)*0 + (3/5)*0 = 0
▪ Gain(SRain, Wind) = 0.971−0=0.9710.971−0=0.971
o Comparing gains for
SRain : Temp (0.02), Humidity (0.02), Wind (0.971). Wind has the highest gain (0.971).
o Split the Rain branch on Wind.
o Child nodes for Wind: Weak and Strong.
▪ Wind = Weak (in Rain subset): {D4, D5}. All 2 instances are 'Yes'.
Pure. Leaf node "Yes".
▪ Wind = Strong (in Rain subset): {D6, D10, D14}. All 3 instances are
'No'. Pure. Leaf node "No".
o The Rain branch is now complete with leaf nodes.
6. The Final Decision Tree
Based on the steps above, the final ID3 decision tree for the Play Tennis problem is:
41
Data Science Tawqeer ul Islam
5. Rule Learners
• Definition: Machine learning algorithms that learn symbolic rules (often in the form
of IF-THEN statements) from data.
• Core Concept: Represent knowledge and make predictions using a set of logical
rules. These rules are typically easy for humans to understand.
• How it Works:
o From Decision Trees: Rules can be extracted directly from a trained decision tree
by traversing each path from the root to a leaf node. Each path corresponds to a
rule where the conditions are the tests at the internal nodes and the conclusion is
the class label at the leaf.
o Direct Rule Learning (e.g., Sequential Covering algorithms like Ripper, PART):
1. Learn a rule that covers a subset of the data.
2. Remove the data points covered by the rule.
3. Repeat until no or few data points remain, or a stopping criterion is met.
4. Post-process/prune the learned rules to improve performance and readability.
• Advantages:
o Highly interpretable (rules are easy to read).
o Can explicitly represent discovered patterns.
o Can handle symbolic data well.
• Disadvantages:
o Rule sets can become large and complex for high-dimensional data.
o May struggle with complex non-linear relationships compared to other methods.
• Example Problem: Learning rules to diagnose a medical condition based on
symptoms (e.g., IF (Fever is High) AND (Cough is Severe) THEN Class is Pneumonia).
• Numerical: (Rule learners primarily involve symbolic logic and counting
support/confidence, less direct numerical computation compared to other
algorithms' core mechanics). Example is more about the rule structure.
6. Linear Regression
• Definition: A supervised learning algorithm used for regression tasks. It models the
relationship between a dependent variable (target) and one or more independent
variables (features) by fitting a linear equation to the observed data.
• Core Concept: Assumes a linear relationship exists between the input features and
the target variable. The goal is to find the coefficients (weights) of this linear
equation that best fit the data.
• Mathematics:
42
Data Science Tawqeer ul Islam
43
Data Science Tawqeer ul Islam
To update B0 and B1, we take gradients from the cost function. To find these gradients,
we take partial derivatives for B0 and B1.
• Assumptions:
o Linearity: Linear relationship between features and target.
o Independence: Observations are independent.
o Homoscedasticity: Constant variance of errors.
o Normality: Errors are normally distributed (important for statistical inference, less
critical for prediction alone).
o No Multicollinearity: Features are not highly correlated with each other.
• Advantages:
o Simple and interpretable.
o Computationally efficient.
o Provides insights into the relationships between variables (magnitude and sign of
coefficients).
• Disadvantages:
44
Data Science Tawqeer ul Islam
• Mathematics:
o Linear Model Output (Log-Odds): z = b₀ + b₁ * x₁ + ... + bₙ * xₙ = wᵀx (in vector
form, including bias)
o Sigmoid Function:
45
Data Science Tawqeer ul Islam
46
Data Science Tawqeer ul Islam
47
Data Science Tawqeer ul Islam
o Interpretation:
▪ Ranges typically from 0 to 1 for a linear model fitted by OLS.
▪ R² = 0 means the model explains none of the variance (prediction is no
better than predicting the mean).
▪ R² = 1 means the model explains all the variance (perfect fit).
▪ R² < 0 is possible if the model fits the data worse than simply predicting the
mean (e.g., using non-linear models or inappropriate features).
o Use Case: Provides a measure of goodness-of-fit. Indicates how well the model
fits the data compared to a baseline model that just predicts the mean.
• Numerical Example (MSE, MAE, R-squared):
o Actual y: {2, 4, 5}
o Predicted ŷ: {2.1, 3.8, 4.9}
o Mean of y (ȳ) = (2 + 4 + 5) / 3 = 11/3 ≈ 3.67
48
Data Science Tawqeer ul Islam
49
Data Science Tawqeer ul Islam
• Example Problem (Classification): Classify a new fruit (by weight and color
intensity) based on its k nearest known fruits (apple, orange, banana).
• Numerical Example (Euclidean Distance & Classification):
o Training Data: (x, y, Class) -> (1, 1, A), (2, 2, A), (5, 5, B), (6, 6, B)
x y Class
1 1 A
2 2 A
5 5 B
6 6 B
50
Data Science Tawqeer ul Islam
o Margin: The distance between the hyperplane and the closest data points
from each class. These closest points are called Support Vectors.
o Goal (Linearly Separable Data - Hard Margin SVM): Find w and b such that
wᵀxᵢ + b ≥ +1 for data points xᵢ of class +1, and wᵀxⱼ + b ≤ -1 for data points
xⱼ of class -1. The region between wᵀx + b = +1 and wᵀx + b = -1 is the
margin. The width of the margin is 2 / ||w||. To maximize the margin, we
need to minimize ||w||² subject to the constraints. This is a convex
optimization problem.
o Goal (Non-Linearly Separable Data - Soft Margin SVM): Most real-world
data is not perfectly separable. Soft Margin SVM allows for some
misclassifications or points within the margin by introducing slack variables
(ξᵢ). The optimization problem then involves minimizing ||w||² + C * Σ ξᵢ,
where C is a regularization parameter (cost) that controls the trade-off
between maximizing the margin and minimizing misclassifications. A smaller
C allows more errors (wider margin); a larger C penalizes errors more
strictly (narrower margin).
▪ Common Kernels:
▪ Linear Kernel: K(xᵢ, xⱼ) = xᵢᵀxⱼ (original linear SVM)
▪ Polynomial Kernel: K(xᵢ, xⱼ) = (γ * xᵢᵀxⱼ + r)ᵈ
51
Data Science Tawqeer ul Islam
▪ Radial Basis Function (RBF) / Gaussian Kernel: K(xᵢ, xⱼ) = exp(-γ * ||xᵢ -
xⱼ||²) - very common, can map data into infinite dimensions. γ is a
parameter controlling the influence of single training examples.
• Advantages:
o Effective in high-dimensional spaces.
o Memory efficient, as it uses a subset of training points (support vectors) in
the decision function.
o Can handle non-linear relationships using kernels.
o Robust to outliers (due to soft margin).
• Disadvantages:
o Choice of kernel and parameters (C, γ, degree) significantly affects
performance.
o Training can be slow for large datasets (computationally intensive quadratic
programming problem).
o Difficulty in interpreting the model (especially with non-linear kernels).
o Doesn't directly provide probabilities (though extensions exist).
• Example Problem: Classifying emails as spam or not spam based on word
frequencies. Separating different types of cancer cells based on gene expression
data.
• SVM for Regression (SVR)
While SVM is commonly used for classification, it can also be used for regression. Instead of
finding a boundary between two classes, SVM in regression (called Support Vector Regression
(SVR)) tries to fit a line that predicts continuous values and stays within a certain margin of error.
Clustering
• Description: Clustering is an unsupervised machine learning task that involves
grouping a set of data points into subsets (clusters) such that points within the
same cluster are more similar to each other than to points in other clusters.
• Goal: To discover hidden patterns, structures, or natural groupings in data that
does not have predefined labels.
• Core Idea: Grouping objects based on their similarity, often measured using
distance metrics.
• Application: Customer segmentation, document analysis, image analysis, anomaly
detection.
Types of Clustering:
Different methods exist based on how they define clusters or the approach they take:
1. Partitioning Clustering (e.g., K-Means, K-Medoids):
52
Data Science Tawqeer ul Islam
53
Data Science Tawqeer ul Islam
54
Data Science Tawqeer ul Islam
o Goal: Minimize the within-cluster sum of squares (inertia), which is the sum
of squared distances between each point and its assigned centroid.
▪ Mathematics: Inertia = Σ_{κ=1 to K} Σ_{xᵢ ∈ Cκ} ||xᵢ - μκ||²
• Parameters:
o K: The number of clusters. This must be specified beforehand. Determining
the optimal K can be done using methods like the elbow method or
silhouette analysis.
o Initialization: The initial positions of centroids can affect the final
clustering (K-Means can converge to a local optimum). Running the
algorithm multiple times with different random initializations and choosing
the best result (lowest inertia) is common practice (e.g., K-Means++
initialization).
• Advantages:
o Relatively simple to understand and implement.
o Fast and computationally efficient, especially for large datasets (faster than
hierarchical clustering).
o Scales well to large numbers of samples.
• Disadvantages:
o Requires specifying K beforehand.
o Sensitive to initial centroid positions.
o Assumes clusters are spherical and equally sized, and have similar density.
o Sensitive to outliers.
o Can struggle with clusters of different shapes or densities, or non-convex
shapes.
• Example Problem: Segmenting customers based on purchasing behavior. Grouping
documents based on content similarity.
• Numerical Example:
o Data points (x, y): (1, 1), (1.5, 2), (3, 4), (5, 7), (3.5, 5), (4.5, 5), (3.5, 4.5)
o Let K=2.
o Assume Initial Centroids: μ₁ = (1, 1), μ₂ = (5, 7)
Given:
• Data points (P):
o P1: (1, 1)
o P2: (1.5, 2)
o P3: (3, 4)
o P4: (5, 7)
o P5: (3.5, 5)
55
Data Science Tawqeer ul Islam
o P6: (4.5, 5)
o P7: (3.5, 4.5)
• Number of clusters (K) = 2
• Initial Centroids:
o μ₁ = (1, 1)
o μ₂ = (5, 7)
We will use the Euclidean distance to measure the distance between points and centroids:
Distance = √((x₂ - x₁)² + (y₂ - y₁)²).
For simplicity in comparison, we can often use squared Euclidean distance, as it preserves
the order of distances.
Iteration 1
1. Assignment Step: Assign each data point to the nearest centroid.
• P1 (1, 1):
o Distance to μ₁ (1,1) = √((1-1)² + (1-1)²) = √(0² + 0²) = 0
o Distance to μ₂ (5,7) = √((5-1)² + (7-1)²) = √(4² + 6²) = √(16 + 36) = √52 ≈ 7.21
o P1 is closer to μ₁. Assign P1 to Cluster 1.
• P2 (1.5, 2):
56
Data Science Tawqeer ul Islam
2. Update Step: Recalculate the centroids based on the mean of the points in each
cluster.
• New Centroid μ₁:
o μ₁_x = (1 + 1.5 + 3) / 3 = 5.5 / 3 ≈ 1.833
o μ₁_y = (1 + 2 + 4) / 3 = 7 / 3 ≈ 2.333
o μ₁_new = (1.833, 2.333)
• New Centroid μ₂:
o μ₂_x = (5 + 3.5 + 4.5 + 3.5) / 4 = 16.5 / 4 = 4.125
o μ₂_y = (7 + 5 + 5 + 4.5) / 4 = 21.5 / 4 = 5.375
o μ₂_new = (4.125, 5.375)
The centroids have changed. We proceed to the next iteration.
57
Data Science Tawqeer ul Islam
Iteration 2
Current Centroids: μ₁ = (1.833, 2.333), μ₂ = (4.125, 5.375)
1. Assignment Step:
• P1 (1, 1):
o Dist to μ₁ = √((1-1.833)² + (1-2.333)²) = √((-0.833)² + (-1.333)²) = √(0.694 +
1.777) = √2.471 ≈ 1.57
o Dist to μ₂ = √((1-4.125)² + (1-5.375)²) = √((-3.125)² + (-4.375)²) = √(9.766 +
19.141) = √28.907 ≈ 5.38
o Assign P1 to Cluster 1.
• P2 (1.5, 2):
o Dist to μ₁ = √((1.5-1.833)² + (2-2.333)²) = √((-0.333)² + (-0.333)²) = √(0.111
+ 0.111) = √0.222 ≈ 0.47
o Dist to μ₂ = √((1.5-4.125)² + (2-5.375)²) = √((-2.625)² + (-3.375)²) = √(6.891
+ 11.391) = √18.282 ≈ 4.28
o Assign P2 to Cluster 1.
• P3 (3, 4):
o Dist to μ₁ = √((3-1.833)² + (4-2.333)²) = √((1.167)² + (1.667)²) = √(1.362 +
2.779) = √4.141 ≈ 2.03
o Dist to μ₂ = √((3-4.125)² + (4-5.375)²) = √((-1.125)² + (-1.375)²) = √(1.266 +
1.891) = √3.157 ≈ 1.78
o Assign P3 to Cluster 2. (Assignment changed from Iteration 1)
• P4 (5, 7):
o Dist to μ₁ = √((5-1.833)² + (7-2.333)²) = √((3.167)² + (4.667)²) = √(10.03 +
21.78) = √31.81 ≈ 5.64
o Dist to μ₂ = √((5-4.125)² + (7-5.375)²) = √((0.875)² + (1.625)²) = √(0.766 +
2.641) = √3.407 ≈ 1.85
o Assign P4 to Cluster 2.
• P5 (3.5, 5):
o Dist to μ₁ = √((3.5-1.833)² + (5-2.333)²) = √((1.667)² + (2.667)²) = √(2.779 +
7.113) = √9.892 ≈ 3.14
o Dist to μ₂ = √((3.5-4.125)² + (5-5.375)²) = √((-0.625)² + (-0.375)²) = √(0.391
+ 0.141) = √0.532 ≈ 0.73
o Assign P5 to Cluster 2.
• P6 (4.5, 5):
o Dist to μ₁ = √((4.5-1.833)² + (5-2.333)²) = √((2.667)² + (2.667)²) = √(7.113 +
7.113) = √14.226 ≈ 3.77
o Dist to μ₂ = √((4.5-4.125)² + (5-5.375)²) = √((0.375)² + (-0.375)²) = √(0.141 +
0.141) = √0.282 ≈ 0.53
o Assign P6 to Cluster 2.
• P7 (3.5, 4.5):
o Dist to μ₁ = √((3.5-1.833)² + (4.5-2.333)²) = √((1.667)² + (2.167)²) = √(2.779
+ 4.696) = √7.475 ≈ 2.73
58
Data Science Tawqeer ul Islam
Iteration 3
Current Centroids: μ₁ = (1.25, 1.5), μ₂ = (3.9, 5.1)
1. Assignment Step:
• P1 (1, 1):
o Dist to μ₁ = √((1-1.25)² + (1-1.5)²) = √((-0.25)² + (-0.5)²) = √(0.0625 + 0.25)
= √0.3125 ≈ 0.56
o Dist to μ₂ = √((1-3.9)² + (1-5.1)²) = √((-2.9)² + (-4.1)²) = √(8.41 + 16.81) =
√25.22 ≈ 5.02
o Assign P1 to Cluster 1.
• P2 (1.5, 2):
o Dist to μ₁ = √((1.5-1.25)² + (2-1.5)²) = √((0.25)² + (0.5)²) = √(0.0625 + 0.25)
= √0.3125 ≈ 0.56
o Dist to μ₂ = √((1.5-3.9)² + (2-5.1)²) = √((-2.4)² + (-3.1)²) = √(5.76 + 9.61) =
√15.37 ≈ 3.92
o Assign P2 to Cluster 1.
• P3 (3, 4):
o Dist to μ₁ = √((3-1.25)² + (4-1.5)²) = √((1.75)² + (2.5)²) = √(3.0625 + 6.25) =
√9.3125 ≈ 3.05
o Dist to μ₂ = √((3-3.9)² + (4-5.1)²) = √((-0.9)² + (-1.1)²) = √(0.81 + 1.21) =
√2.02 ≈ 1.42
o Assign P3 to Cluster 2.
• P4 (5, 7):
o Dist to μ₁ = √((5-1.25)² + (7-1.5)²) = √((3.75)² + (5.5)²) = √(14.0625 + 30.25)
= √44.3125 ≈ 6.66
o Dist to μ₂ = √((5-3.9)² + (7-5.1)²) = √((1.1)² + (1.9)²) = √(1.21 + 3.61) = √4.82
≈ 2.20
59
Data Science Tawqeer ul Islam
o Assign P4 to Cluster 2.
• P5 (3.5, 5):
o Dist to μ₁ = √((3.5-1.25)² + (5-1.5)²) = √((2.25)² + (3.5)²) = √(5.0625 + 12.25)
= √17.3125 ≈ 4.16
o Dist to μ₂ = √((3.5-3.9)² + (5-5.1)²) = √((-0.4)² + (-0.1)²) = √(0.16 + 0.01) =
√0.17 ≈ 0.41
o Assign P5 to Cluster 2.
• P6 (4.5, 5):
o Dist to μ₁ = √((4.5-1.25)² + (5-1.5)²) = √((3.25)² + (3.5)²) = √(10.5625 +
12.25) = √22.8125 ≈ 4.78
o Dist to μ₂ = √((4.5-3.9)² + (5-5.1)²) = √((0.6)² + (-0.1)²) = √(0.36 + 0.01) =
√0.37 ≈ 0.61
o Assign P6 to Cluster 2.
• P7 (3.5, 4.5):
o Dist to μ₁ = √((3.5-1.25)² + (4.5-1.5)²) = √((2.25)² + (3)²) = √(5.0625 + 9) =
√14.0625 ≈ 3.75
o Dist to μ₂ = √((3.5-3.9)² + (4.5-5.1)²) = √((-0.4)² + (-0.6)²) = √(0.16 + 0.36) =
√0.52 ≈ 0.72
o Assign P7 to Cluster 2.
Cluster Assignments after Iteration 3:
• Cluster 1: {P1(1,1), P2(1.5,2)}
• Cluster 2: {P3(3,4), P4(5,7), P5(3.5,5), P6(4.5,5), P7(3.5,4.5)}
2. Update Step:
• New Centroid μ₁:
o μ₁_x = (1 + 1.5) / 2 = 1.25
o μ₁_y = (1 + 2) / 2 = 1.5
o μ₁_new = (1.25, 1.5)
• New Centroid μ₂:
o μ₂_x = (3 + 5 + 3.5 + 4.5 + 3.5) / 5 = 19.5 / 5 = 3.9
o μ₂_y = (4 + 7 + 5 + 5 + 4.5) / 5 = 25.5 / 5 = 5.1
o μ₂_new = (3.9, 5.1)
The centroids are the same as in the previous iteration:
μ₁ = (1.25, 1.5)
μ₂ = (3.9, 5.1)
The cluster assignments are also the same as in the previous iteration.
Therefore, the K-Means algorithm has converged.
Final Result:
• Cluster 1:
o Points: {P1(1,1), P2(1.5,2)}
o Centroid (μ₁): (1.25, 1.5)
• Cluster 2:
o Points: {P3(3,4), P4(5,7), P5(3.5,5), P6(4.5,5), P7(3.5,4.5)}
60
Data Science Tawqeer ul Islam
61
Data Science Tawqeer ul Islam
62
Data Science Tawqeer ul Islam
12. DBSCAN
• Definition: A density-based unsupervised learning algorithm for clustering. It
groups together points that are closely packed together, marking points in low-
density regions as outliers.
• Core Concept: Clusters are defined as areas of high density separated by areas of
low density. It can find arbitrarily shaped clusters and is robust to noise.
• Key Concepts & Algorithm:
o ε (epsilon): A radius defining the neighbourhood around a point.
o MinPts: The minimum number of points required to form a dense region.
o Core Point: A point P is a core point if at least MinPts points (including P
itself) are within a distance ε of P.
63
Data Science Tawqeer ul Islam
• How it Works:
1. Arbitrarily pick an unvisited point.
2. If the point is a core point (has at least MinPts neighbours within ε):
▪ Start a new cluster with this point.
64
Data Science Tawqeer ul Islam
65
Data Science Tawqeer ul Islam
66
Data Science Tawqeer ul Islam
o Totals:
▪ Total Actual Positives = TP + FN
▪ Total Actual Negatives = FP + TN
▪ Total Predicted Positives = TP + FP
▪ Total Predicted Negatives = FN + TN
▪ Total Instances = TP + TN + FP + FN
67
Data Science Tawqeer ul Islam
• Accuracy:
o Definition: The ratio of correctly predicted instances to the total number of
instances.
o Formula: Accuracy = (TP + TN) / (TP + TN + FP + FN)
o Interpretation: Overall correctness.
o Use Case: Suitable for balanced datasets (where the number of instances in each
class is roughly equal).
o Limitations: Can be misleading for imbalanced datasets. If 95% of emails are
non-spam, a model that always predicts "non-spam" achieves 95% accuracy but is
useless.
• Precision (Positive Predictive Value):
o Definition: Of all instances predicted as Positive, how many were actually
Positive? Measures the exactness or quality of the positive predictions.
o Formula: Precision = TP / (TP + FP)
o Interpretation: Avoids false alarms. High precision means when the model
predicts positive, it is very likely correct.
o Use Case: When the cost of a False Positive is high (e.g., recommending a
harmful drug, marking a non-spam email as spam, wrongly arresting an innocent
person).
• Recall (Sensitivity, True Positive Rate):
o Definition: Of all instances that were actually Positive, how many were correctly
predicted as Positive? Measures the completeness or coverage of the positive
class.
o Formula: Recall = TP / (TP + FN)
o Interpretation: Avoids missing positive cases. High recall means the model finds
most of the positive instances.
o Use Case: When the cost of a False Negative is high (e.g., failing to detect a
disease, missing a fraudulent transaction, failing to detect an incoming missile).
• Specificity (True Negative Rate):
o Definition: Of all instances that were actually Negative, how many were
correctly predicted as Negative?
o Formula: Specificity = TN / (TN + FP)
o Interpretation: Correctly identifies negative cases.
o Note: Related to False Positive Rate (FPR = FP / (FP + TN) = 1 - Specificity).
• F1-Score:
o Definition: The harmonic mean of Precision and Recall. Provides a single score
that balances both metrics.
68
Data Science Tawqeer ul Islam
69
Data Science Tawqeer ul Islam
o Calculate Metrics:
▪ Accuracy = (10 + 75) / (10 + 5 + 10 + 75) = 85 / 100 = 0.85 (or 85%)
▪ Precision = 10 / (10 + 5) = 10 / 15 ≈ 0.67 (or 67%) - Of those predicted
positive, 67% were correct.
70
Data Science Tawqeer ul Islam
71
Data Science Tawqeer ul Islam
Probabilistic Models
1. Introduction to Probability
• Core Concept: Probability is the mathematical framework for quantifying
uncertainty. It deals with the likelihood of events occurring.
72
Data Science Tawqeer ul Islam
• Key Definitions:
o Experiment: A process that produces an outcome (e.g., flipping a coin, rolling a
die, drawing a card).
o Outcome: A single possible result of an experiment (e.g., Heads, rolling a 3,
drawing the King of Hearts).
o Sample Space (Ω or S): The set of all possible outcomes of an experiment (e.g.,
{Heads, Tails} for a coin flip; {1, 2, 3, 4, 5, 6} for a die roll).
o Event (E): A subset of the sample space. A collection of one or more outcomes
(e.g., rolling an even number {2, 4, 6}, drawing a red card).
• Probability of an Event P(E):
o Assuming equally likely outcomes: P(E) = (Number of outcomes in E) / (Total
number of outcomes in Ω).
o Properties:
▪ 0 ≤ P(E) ≤ 1
▪ P(Ω) = 1 (Probability of the sample space - something must happen)
▪ P(∅) = 0 (Probability of the empty set - nothing happens)
o If A and B are mutually exclusive events (cannot happen at the same time): P(A
or B) = P(A ∪ B) = P(A) + P(B)
o For any two events A and B: P(A or B) = P(A ∪ B) = P(A) + P(B) - P(A ∩ B)
• Types of Probability:
o Marginal Probability: The probability of a single event occurring, regardless of
any other events (e.g., P(drawing a King) from a deck).
o Joint Probability: The probability of two or more events occurring together
(e.g., P(drawing a King AND an Ace) with replacement, or P(drawing a King AND a
Heart) from a single draw). Denoted P(A and B) or P(A ∩ B).
o Conditional Probability: The probability of an event A occurring given that
another event B has already occurred. Denoted P(A | B).
• Probability Rules:
o Product Rule: Relates joint probability and conditional probability.
▪ P(A and B) = P(A | B) * P(B)
▪ P(A and B) = P(B | A) * P(A)
o Sum Rule (Law of Total Probability): If {B₁, B₂, ..., Bₙ} is a partition of the
sample space (mutually exclusive and exhaustive events), then P(A) = Σᵢ P(A | Bᵢ)
* P(Bᵢ). This is used to calculate the marginal probability of A by summing over all
possible conditions Bᵢ.
• Independence:
73
Data Science Tawqeer ul Islam
o Two events A and B are independent if the occurrence of one does not affect the
probability of the other.
o Mathematically:
▪ P(A | B) = P(A)
▪ P(B | A) = P(B)
▪ Equivalently, P(A and B) = P(A) * P(B) (This is often the definition
used).
• Example Problem: Drawing cards from a standard 52-card deck.
o Ω = 52 cards.
o Event A = Drawing a King. P(A) = 4/52 = 1/13.
o Event B = Drawing a Heart. P(B) = 13/52 = 1/4.
o Event A and B = Drawing the King of Hearts. P(A and B) = 1/52.
o Are A and B independent? P(A)P(B) = (1/13)(1/4) = 1/52. Yes, they are
independent in a standard deck (knowing it's a Heart doesn't change the
probability it's a King, among all cards).
o P(A | B) = P(King | Heart) = Probability of drawing a King given you drew a Heart.
There is 1 King of Hearts among 13 Hearts. So, P(A | B) = 1/13. This equals P(A),
confirming independence.
2. Rule of Bayes and Conditional Independence
• Bayes' Rule (Bayes' Theorem):
o Definition: A fundamental theorem in probability that describes how to
update the probability of a hypothesis based on new evidence.
o Formula:
P(A | B) = [ P(B | A) * P(A) ] / P(B)
o Terms:
▪ P(A | B): Posterior Probability - The probability of hypothesis A being true
given evidence B. This is what we want to find.
▪ P(B | A): Likelihood - The probability of observing evidence B given that
hypothesis A is true.
▪ P(A): Prior Probability - The initial probability of hypothesis A being true
before observing the evidence B.
▪ P(B): Evidence (or Marginal Likelihood) - The probability of observing
evidence B, regardless of the hypothesis. This acts as a normalizing
constant.
o Calculating Evidence P(B): Using the Law of Total Probability. If A and ¬A
(not A) are the only two possibilities for the hypothesis:
P(B) = P(B | A) * P(A) + P(B | ¬A) * P(¬A)
74
Data Science Tawqeer ul Islam
75
Data Science Tawqeer ul Islam
o Example:
▪ Event A: Person has a cough.
▪ Event B: Person has a fever.
▪ Event C: Person has the flu.
▪ A and B are not marginally independent (cough and fever are correlated).
P(Cough and Fever) ≠ P(Cough)P(Fever).
▪ However, A and B might be conditionally independent given C. P(Cough
and Fever | Flu) ≈ P(Cough | Flu) * P(Fever | Flu). If you know someone
has the flu, knowing they have a fever might not give you much additional
information about whether they have a cough, beyond what the flu itself
tells you.
3. Naive Bayes Classifier
• Definition: A probabilistic supervised learning algorithm used for classification. It's
based on Bayes' Rule and assumes naive conditional independence between
features given the class label.
• Core Concept: For a given instance with features x₁, x₂, ..., xₙ, it calculates the
probability that it belongs to each class Ck using Bayes' Theorem and picks the class
with the highest probability.
• Mathematics:
o We want to find P(Ck | x₁, x₂, ..., xₙ) for each class Ck.
o Using Bayes' Rule:
P(Ck | x₁, ..., xₙ) = [ P(x₁, ..., xₙ | Ck) * P(Ck) ] / P(x₁, ..., xₙ)
o Since the denominator P(x₁, ..., xₙ) is the same for all classes, we only need to
compare the numerator:
P(Ck | x₁, ..., xₙ) ∝ P(x₁, ..., xₙ | Ck) * P(Ck)
o The Naive Assumption: Features x₁, ..., xₙ are conditionally independent given
the class Ck.
P(x₁, ..., xₙ | Ck) = P(x₁ | Ck) * P(x₂ | Ck) * ... * P(xₙ | Ck)
o Classification Rule:
Classify x₁, ..., xₙ into the class Ck that maximizes:
P(Ck) * P(x₁ | Ck) * P(x₂ | Ck) * ... * P(xₙ | Ck)
o Training: The model learns by estimating the required probabilities from the
training data:
▪ Prior Probability P(Ck): Calculated as the frequency of class Ck in the
training data. P(Ck) = (Number of instances of class Ck) / (Total number of
instances).
▪ Conditional Probability P(xᵢ | Ck): Calculated as the frequency of feature
value xᵢ occurring among instances of class Ck. P(xᵢ | Ck) = (Count of
instances with feature xᵢ in class Ck) / (Count of instances in class Ck).
76
Data Science Tawqeer ul Islam
o Handling Zero Probabilities: If a feature value xᵢ does not appear with a class
Ck in the training data, P(xᵢ | Ck) would be 0. This would make the entire
product 0, regardless of other probabilities. Laplace Smoothing (Add-k
Smoothing) is used to prevent this by adding a small number (k, usually 1) to
the counts.
P(xᵢ | Ck) = (Count(xᵢ and Ck) + k) / (Count(Ck) + k * |Vocabulary|)
▪ k=1 is Add-one smoothing. |Vocabulary| is the number of possible values
for feature xᵢ.
• Advantages:
o Simple and fast to train and predict.
o Requires relatively little training data to estimate parameters.
o Works well with high-dimensional data (like text classification).
o Surprisingly effective in practice despite the strong assumption.
• Disadvantages:
o The naive independence assumption is rarely true in real-world data.
o While it often performs well as a classifier, the probability estimates it
produces may be inaccurate.
• Example Problem: Spam classification. Features are the words in an email. Classes
are "Spam" and "Not Spam".
• Numerical Example (Text Classification - Spam/Not Spam):
o Training Data:
▪ "Buy pharmaceuticals now" (Spam)
▪ "Buy painkillers" (Spam)
▪ "Nigeria pharmaceuticals" (Spam)
▪ "Nigeria now" (Not Spam)
o Vocabulary: {buy, pharmaceuticals, now, painkillers, Nigeria}
o Classes: Spam, Not Spam. P(Spam) = 3/4, P(Not Spam) = 1/4.
o Conditional Probabilities (using Laplace smoothing k=1):
▪ Count(Spam) = 3. Vocab Size = 5. Denominator = 3 + 1*5 = 8.
▪ Count(Not Spam) = 1. Vocab Size = 5. Denominator = 1 + 1*5 = 6.
▪ P(buy | Spam) = (Count("buy" in Spam) + 1) / 8 = (2 + 1) / 8 = 3/8
▪ P(pharmaceuticals | Spam) = (Count("pharmaceuticals" in Spam) + 1) / 8 =
(2 + 1) / 8 = 3/8
▪ P(now | Spam) = (Count("now" in Spam) + 1) / 8 = (1 + 1) / 8 = 2/8
▪ P(painkillers | Spam) = (Count("painkillers" in Spam) + 1) / 8 = (1 + 1) / 8
= 2/8
77
Data Science Tawqeer ul Islam
78
Data Science Tawqeer ul Islam
79
Data Science Tawqeer ul Islam
80
Data Science Tawqeer ul Islam
81
Data Science Tawqeer ul Islam
o Measures how often items in Y appear in transactions that contain X. It's the
conditional probability of finding Y given X.
o Formula: conf(X → Y) = supp(X ∪ Y) / supp(X)
▪ supp(X ∪ Y) is the support of the itemset containing all items in both
X and Y.
▪ supp(X) is the support of the antecedent X.
o Interpretation: The probability of finding itemset Y in a transaction, given
that the transaction also contains itemset X.
o Example: If supp({Milk, Bread, Butter}) = 0.2 and supp({Milk, Bread}) = 0.3,
then conf({Milk, Bread} → {Butter}) = 0.2 / 0.3 ≈ 0.67 or 67%. This means
that 67% of the transactions that contain Milk and Bread also contain Butter.
7. Lift (lift(X → Y)):
o Measures how much more likely Y is to be purchased when X is purchased,
compared to the likelihood of Y being purchased independently.
o Formula: lift(X → Y) = supp(X ∪ Y) / (supp(X) * supp(Y))
▪ Alternatively, lift(X → Y) = conf(X → Y) / supp(Y)
o Interpretation:
▪ lift(X → Y) = 1: X and Y are independent; no association.
▪ lift(X → Y) > 1: X and Y are positively correlated; the presence of X
increases the likelihood of Y.
▪ lift(X → Y) < 1: X and Y are negatively correlated; the presence of X
decreases the likelihood of Y.
o Example: If conf({Milk, Bread} → {Butter}) = 0.67 and supp({Butter}) = 0.4,
then lift({Milk, Bread} → {Butter}) = 0.67 / 0.4 = 1.675. This suggests a
positive association.
8. Minimum Support (min_sup) and Minimum Confidence (min_conf):
o User-defined thresholds used to filter out uninteresting itemsets and rules.
o Only itemsets with support ≥ min_sup are considered frequent.
o Only rules with confidence ≥ min_conf (and derived from frequent itemsets)
are considered interesting.
Goal of Association Rule Mining:
To find all association rules X → Y such that:
1. supp(X ∪ Y) ≥ min_sup
2. conf(X → Y) ≥ min_conf
Process:
Association rule mining is typically a two-step process:
82
Data Science Tawqeer ul Islam
1. Frequent Itemset Generation: Find all itemsets whose support is greater than or
equal to min_sup. This is the most computationally intensive step.
2. Rule Generation: From the frequent itemsets found in step 1, generate association
rules that satisfy the min_conf threshold.
Apriori Algorithm
The Apriori algorithm is a classic algorithm for mining frequent itemsets and learning
association rules. It uses a "bottom-up" approach, where frequent subsets are extended
one item at a time (candidate generation), and groups of candidates are tested against
the data.
Key Property (Apriori Property / Anti-Monotonicity of Support):
• "All non-empty subsets of a frequent itemset must also be frequent."
• Conversely, "If an itemset is infrequent, then all its supersets must also be
infrequent."
• This property is crucial for pruning the search space. If a candidate (k)-itemset is
found to be infrequent, we don't need to consider any of its (k+1)-itemset
supersets.
Steps of the Apriori Algorithm:
1. Initialization (k=1):
o Scan the transaction database to count the support of each individual item
(1-itemsets).
o Identify frequent 1-itemsets (L₁) by comparing their support to min_sup.
2. Iterative Frequent Itemset Generation (for k > 1):
Repeat for k = 2, 3, ... until no more frequent k-itemsets can be found:
o a. Candidate Generation (Cₖ):
▪ Generate candidate k-itemsets from frequent (k-1)-itemsets (Lₖ₋₁).
▪ This is typically done by joining Lₖ₋₁ with itself:
▪ Two frequent (k-1)-itemsets are joined if they share (k-2)
common items. For example, to generate 3-itemsets, join
two 2-itemsets {I1, I2} and {I1, I3} to form {I1, I2, I3}.
▪ Pruning (using Apriori property): After generating candidates,
prune any candidate k-itemset if any of its (k-1)-subsets are not in
Lₖ₋₁ (i.e., not frequent).
o b. Support Counting:
▪ Scan the transaction database. For each transaction, determine
which of the candidate k-itemsets (Cₖ) are contained in it.
▪ Increment the support count for these candidates.
83
Data Science Tawqeer ul Islam
Transaction ID Items
T1 I1, I3, I4
T2 I2, I3, I5, I6
T3 I1, I2, I3, I5
84
Data Science Tawqeer ul Islam
T4 I2, I5
T5 I1, I3, I5
The above dataset for the apriori algorithm numerical example contains five transactions
having transaction IDs T1, T2, T3, T4, and T5. In the transactions, it contains six different
items namely I1, I2, I3, I4, I5, and I6. Let us now use the apriori algorithm to find
association rules from the above dataset. For our numerical example, we will use the
minimum support count of 2 and minimum confidence of 75 percent.
To help us calculate the support of the itemsets, we will create a matrix representing the
presence of items in a transaction as shown below.
I1 I2 I3 I4 I5 I6
T1 1 0 1 1 0 0
T2 0 1 1 0 1 1
T3 1 1 1 0 1 0
T4 0 1 0 0 1 0
T5 1 0 1 0 1 0
Transaction Matrix
The above matrix contains Items on the horizontal axis and transaction IDs on the vertical
axis. If an item is present in a transaction, the corresponding cell is set to 1. Otherwise, it
is set to 0. We will use this matrix to calculate the support count of itemsets as it is easier
to scan this matrix compared to the transaction dataset.
To calculate the support count of any given itemset using the above matrix, we will
find the number of rows in which all the items in the given itemset are set to 1.
Create Frequent Itemsets With One Item
The Apriori algorithm starts by creating candidate itemsets with one item. For this, let us
calculate the support count of each item.
{I1} 3
{I2} 3
{I3} 4
{I4} 1
{I5} 4
{I6} 1
Candidate Itemsets with one item
The above table contains the support count of candidate itemsets with one item. Here,
you can observe that the itemsets {I4} and {I6} have support count 1 which is less than the
minimum support count 2. Hence, we will omit these itemsets from the above table. After
this, we will get the table containing frequent itemsets with a single item as shown below.
85
Data Science Tawqeer ul Islam
Now that we have created frequent itemsets containing a single item, we will move to
calculate the frequent itemsets with two items.
Create Frequent Itemsets With Two Items
To create frequent itemsets with two items, we will first create the candidate itemset
with two items. For this, we will join all the frequent itemsets with one item with each
other. After joining, we will get the following itemsets.
{I1,I2}, {I1,I3}, {I1,I5},{I2,I3},{I2,I5}, and {I3,I5}
After creating the itemsets with two items, we need to prune the itemsets having subsets
that are not frequent itemsets. As the {I1}, {I2}, {I3}, and {I5} all are frequent itemsets, no
itemsets will be removed from the above list while pruning.
As the next step, we will calculate the support count of each itemset having two items to
create the candidate itemset. The result is tabulated below.
86
Data Science Tawqeer ul Islam
87
Data Science Tawqeer ul Islam
88
Data Science Tawqeer ul Islam
Advantages of Apriori:
• Relatively simple and easy to understand.
• Uses the Apriori property effectively to prune a vast number of candidate itemsets.
Disadvantages of Apriori:
• Multiple Database Scans: Requires scanning the database multiple times (once for
each iteration k). This can be very costly for large databases.
• Large Number of Candidates: Can generate a huge number of candidate itemsets,
especially for dense datasets or low min_sup values, even with pruning. The "join"
and "prune" steps for candidate generation can be computationally intensive.
• Inefficient for long frequent patterns.
89
Data Science Tawqeer ul Islam
90