Unit 3 Classification
Unit 3 Classification
Classification
Classification
Classification is a supervised learning method in which the computer learns from past data
and then predicts a category (class) for new data.
In classification, we give the computer many past examples where the correct answer (class)
is already known.
The computer learns patterns from these examples and creates rules.
Later, when we give new data, the computer uses those rules to predict the correct class.
• Spam
• Not Spam
For example:
✔ Spam
This is classification!
A classification problem means we want to predict a category (class) for a new item, based
on patterns learned from past data.
We have:
Examples:
Examples:
Example 10.1 – Retention in the mobile phone industry. Example 5.2 on the analysis of
customer loyalty in the mobile phone industry is a binary classification problem in which the
target attribute takes the value 1 if a customer has discontinued service and 0 otherwise. The
features of each customer, described in Table 5.3, represent the predictive attributes. The
purpose of a classification model is to derive general rules from the examples contained in
the dataset and to apply these rules in order to assign the class to new instances for which the
target value is unknown.
In this way, the classification model may prove useful in identifying those customers who are
likely to discontinue service, and therefore to drive a retention marketing campaign.
This is a binary classification problem because there are only two possible classes:
We want to predict whether a new customer will discontinue the service or continue using it.
How do we do it?
• Age
• Monthly bill
• Internet usage
• Customer complaints
• Number of months with company
• Payment method
• Offers availed, etc.
Example
Customer Monthly Bill Complaints Months With Company Has Discontinued (Target)
These rules help the company identify customers who are at high risk of leaving and provide
special offers to retain them.
This is a multicategory classification problem, because customers are divided into more
than two classes.
• Class 0 → No calls
• Class 1 → 1 call
• Class 2 → 2 to 4 calls
• Class 3 → More than 4 calls
To understand customer behaviour based on how many times they call the call center.
Example
• Age
• Salary
• Number of calls
• Internet usage
• Test marks
• Temperature
• Colour, etc.
These data points come from an unknown real-world process, so we don’t know the exact
probability of how they are generated.
This is written as:
Example
You only know the marks, not how they were generated.
Example
Using the marks above, the supervisor may classify the student as:
• “Pass” (1)
• “Fail” (0)
So, the supervisor gives the correct answer for each input.
Example:
x = (80, 65, 70) → Supervisor says “Pass”
Example
Generator
So x = (features of email)
Supervisor
• Spam (1)
• Not spam (0)
Classifier
1. Training Phase
2. Test Phase
3. Prediction Phase
• In this phase, the model is given some examples whose class/label is already
known.
Example
Suppose you want a model to detect whether a customer will leave a mobile company
(“Yes” or “No”).
25 300 5 Yes
40 500 0 No
• After learning, the model is tested on new examples that it has never seen before.
• This part of the dataset is called the Test Set (V = D – T).
• We compare:
Simple Example
Test data:
30 350 4 Yes
To avoid fake accuracy, the training set must not include the test set. They should be
separate.
3. Prediction Phase
• The model applies the rules learned during the training phase.
Simple Example
22 250 6
1. Heuristic Models
2. Separation Models
3. Regression Models
4. Probabilistic Models
1. Heuristic Models
These are simple rule-based models like KNN and decision trees.
Methods:
• Classification Trees
• KNN:
“If you are similar to your neighbors, you belong to their group.”
Example:
If most neighbors near you are "Sports shoes buyers", you are predicted as a "Sports
shoes buyer".
• Decision Tree:
This model works like a “question-answer” tree.
Example:
These methods are easy, fast, and intuitive, like using common sense.
2. Separation Models (Models that separate data into regions)
These models try to divide the data space into different regions where each region
represents a class.
Methods:
• Perceptron
• Neural Networks
• Discriminant Analysis
Example:
To separate emails into Spam and Not Spam, SVM may draw a line or curve between them.
Think of it like:
3. Regression Models
These models assume there is a mathematical relationship between input attributes and
the target class. Logistic regression is used for binary classification.
Method:
Methods:
• Naive Bayes
• Bayesian Networks
When we build a classification model, we must check how good the model is. To do this, we
evaluate it using different criteria:
1. Accuracy
• Accuracy means how correctly the model predicts the class of new data.
• We compare different models using their accuracy and select the one with the best
performance.
Example:
A model predicts whether an email is Spam or Not Spam.
If out of 100 test emails, it predicts 90 correctly → Accuracy = 90%
2. Speed
Speed means how fast a classification model learns and makes predictions.
• Some models take less time to train and are good for large datasets.
• Sometimes we train the model using a small portion of the data (random sampling)
to reduce training time.
3. Scalability
• A scalable model should still work well even when the amount of data increases a
lot.
Example:
A model that works with 1,000 records should also work with 1 million records without
becoming too slow.
4. Interpretability
• Interpretability means how easily humans can understand the model’s rules.
• If the goal is not just prediction but also explaining how decisions are made, the
model should be simple and clear.
• Experts or users should be able to understand how the model is making decisions.
Example:
A decision tree is easy to understand, but a neural network is difficult to explain.
The Holdout Method is the simplest way to check how good a classification model is.
How it works:
• Generally:
Accuracy Calculation
• The accuracy value may be higher or lower depending on which data happened to go into V.
o Test it on Vk
Advantages
Disadvantages
• There is no control over how many times each observation appears in training or test sets.
• An outlier may appear too often in training/test sets and affect the result.
10.2.3 Cross-Validation
2. Perform r iterations:
o In iteration k:
Mathematically,
𝑉𝑘 = 𝐿𝑘
𝑇𝑘 = ⋃ 𝐿𝑙
𝑙≠𝑘
• Perform 10 rounds:
o …
✔ Advantage:
✖ Disadvantage:
When classes are imbalanced, we must ensure that each fold has the same class proportion as the
whole dataset.
Example:
If in full data:
It helps us understand how many predictions are correct and how many are wrong, and what type
of errors the model is making.
For binary classification (Yes/No, 1/0, Positive/Negative), the confusion matrix is a 2 × 2 table.
Structure
• Correct prediction
Example:
Patient has a disease → model says disease present
Example:
Patient is healthy → model says healthy
• Wrong prediction
Example:
Patient is healthy → model says disease present
• Wrong prediction
Example:
Patient has disease → model says healthy
4. Numerical Example
Problem
Disease (Yes) 40 10
No Disease 5 45
So:
• TP = 40
• FN = 10
• FP = 5
• TN = 45
1. Accuracy
Definition
Formula
𝑇𝑃 + 𝑇𝑁
𝐴𝑐𝑐𝑢𝑟𝑎𝑐𝑦 =
𝑇𝑃 + 𝑇𝑁 + 𝐹𝑃 + 𝐹𝑁
Calculation
40 + 45
𝐴𝑐𝑐𝑢𝑟𝑎𝑐𝑦 = = 0.85 = 85%
100
Limitation:
Accuracy can be misleading when data is imbalanced.
2. Error Rate
Definition
Formula
𝐹𝑃 + 𝐹𝑁
𝐸𝑟𝑟𝑜𝑟 𝑅𝑎𝑡𝑒 =
𝑇𝑜𝑡𝑎𝑙
Calculation
5 + 10
𝐸𝑟𝑟𝑜𝑟 = = 15%
100
3. Precision
Definition
Formula
𝑇𝑃
𝑃𝑟𝑒𝑐𝑖𝑠𝑖𝑜𝑛 =
𝑇𝑃 + 𝐹𝑃
Calculation
40
𝑃𝑟𝑒𝑐𝑖𝑠𝑖𝑜𝑛 = = 0.89 = 89%
40 + 5
Definition
Out of all actual positives, how many did the model correctly detect?
Formula
𝑇𝑃
𝑅𝑒𝑐𝑎𝑙𝑙 =
𝑇𝑃 + 𝐹𝑁
Calculation
40
𝑅𝑒𝑐𝑎𝑙𝑙 = = 0.80 = 80%
40 + 10
Definition
Formula
𝑇𝑁
𝑆𝑝𝑒𝑐𝑖𝑓𝑖𝑐𝑖𝑡𝑦 =
𝑇𝑁 + 𝐹𝑃
Calculation
45
𝑆𝑝𝑒𝑐𝑖𝑓𝑖𝑐𝑖𝑡𝑦 = = 0.90 = 90%
45 + 5
Formula
𝐹𝑃
𝐹𝑃𝑅 =
𝐹𝑃 + 𝑇𝑁
Calculation
5
𝐹𝑃𝑅 = = 10%
50
Formula
𝐹𝑁
𝐹𝑁𝑅 =
𝐹𝑁 + 𝑇𝑃
Calculation
10
𝐹𝑁𝑅 = = 20%
50
8. F1-Score
Definition
Formula
2 × 𝑃𝑟𝑒𝑐𝑖𝑠𝑖𝑜𝑛 × 𝑅𝑒𝑐𝑎𝑙𝑙
𝐹1 =
𝑃𝑟𝑒𝑐𝑖𝑠𝑖𝑜𝑛 + 𝑅𝑒𝑐𝑎𝑙𝑙
Calculation
2 × 0.89 × 0.80
𝐹1 = ≈ 0.84
0.89 + 0.80
ROC (Receiver Operating Characteristic) curve is a graph used to check how good a classification
model is.
It helps us:
Axis Meaning
• No false positives
• Perfect model
(0, 0)
(1, 1)
Trade-Off Concept
Problem
Model Behavior
• If model is strict → fewer false positives but may miss sick patients
• If model is lenient → more sick patients detected but more false alarms
0.9 Excellent
0.7 Good
A classification tree is a popular machine learning method used in data mining to classify data into
different groups or classes.
• Data is split step-by-step using a top-down approach. This method is called Top-Down
Induction of Decision Trees
1. Root Node
2. Branching
• Example:
4. Leaf Node
• No further splitting
Classification Rule
• Example:
IF age ≤ 45 AND residence = north THEN class = Yes
1. Binary Trees
• Example:
o Yes / No
o True / False
2. Multi-Split Trees
• Example:
3. Univariate Trees
• Example:
o Age
o Area
o Authorized communication
1. Binary Attribute
• Example:
• Example:
3. Numerical Attribute
• Numbers
• Example:
Stopping Criteria
• Continue splitting OR
Types of Pruning:
1. Pre-pruning
2. Post-pruning
Neural Networks
Neural networks are computer models that learn patterns directly from data, without needing
fixed or pre-written rules. They work in a way similar to the human brain.
1. Neurons
• Each neuron:
o Applies a threshold
2. Connections
4. Propagation Functions
o To output layer
5. Learning Rule
1. Input Layer: This is where the network receives its input data. Each input neuron in the layer
corresponds to a feature in the input data.
2. Hidden Layers: These layers perform most of the computational heavy lifting. A neural
network can have one or multiple hidden layers. Each layer consists of units (neurons) that
transform the inputs into something that the output layer can use.
3. Output Layer: The final layer produces the output of the model. The format of these outputs
varies depending on the specific task like classification, regression.
Once we decide the mathematical model of a neuron, the next step is to connect neurons together
to form a neural network.
There are two main types of neural networks based on how neurons are connected.
• Data moves:
Input layer → Hidden layer(s) → Output layer
Layered Structure
Example:
• Useful for:
o Time-series data
o Speech recognition
o Sequence prediction
• Inputs pass through one or more hidden layers before reaching the output.
4. Robust to Overfitting:
By focusing on the points closest to the boundary (support vectors), SVM
is less likely to overfit, especially in smaller datasets.
5. Requires Tuning:
SVM requires careful tuning of parameters (like the choice of kernel and
regularization) to achieve optimal performance, which can be time-
consuming.
SVM is defined such that it is defined in terms of the support vectors only,
we don’t have to worry about other observations since the margin is made
using the points which are closest to the hyperplane (support vectors),
whereas in logistic regression the classifier is defined over all the points.
Hence SVM enjoys some natural speed-ups.
dataset that has two classes (green and blue). We want to classify that the new
NOTE: Since we are plotting the data points in a 2-dimensional graph we call this decision boundary
a straight line but if we have more dimensions, we call this decision boundary a “hyperplane”
The best hyperplane is that plane that has the maximum distance from both the classes, and this is
the main aim of SVM. This is done by finding different hyperplanes which classify the labels in the
best way then it will choose the one which is farthest from the data points or the one which has a
maximum margin.
1. Works well with complex data: SVM is great for datasets where the separation between
categories is not clear. It can handle both linear and non-linear data effectively.
2. Effective in high-dimensional spaces: SVM performs well even when there are more
features (dimensions) than samples, making it useful for tasks like text classification or
image recognition.
3. Avoids overfitting: SVM focuses on finding the best decision boundary (margin) between
classes, which helps in reducing the risk of overfitting, especially in high-dimensional data.
4. Versatile with kernels: By using different kernel functions (like linear, polynomial, or radial
basis function), SVM can adapt to various types of data and solve complex problems.
5. Robust to outliers: SVM is less affected by outliers because it focuses on the support vectors
(data points closest to the margin), which helps in creating a more generalized model.
1. Slow with large datasets: SVM can be computationally expensive and slow to train,
especially when the dataset is very large.
2. Difficult to tune: Choosing the right kernel and parameters (like C and gamma) can be tricky
and often requires a lot of trial and error.
3. Not suitable for noisy data: If the dataset has too many overlapping classes or noise, SVM
may struggle to perform well because it tries to find a perfect separation.
4. Hard to interpret: Unlike some other algorithms, SVM models are not easy to interpret or
explain, especially when using non-linear kernels.
5. Memory-intensive: SVM requires storing the support vectors, which can take up a lot of
memory, making it less efficient for very large datasets.
Clustering
Clustering is an unsupervised machine learning technique that groups similar data points together
into clusters based on their characteristics, without using any labeled data. The objective is to ensure
that data points within the same cluster are more similar to each other than to those in different
clusters, enabling the discovery of natural groupings and hidden patterns in complex datasets.
• How: Data points are assigned to clusters based on similarity or distance measures.
• Output: Each group is assigned a cluster ID, representing shared characteristics within the
cluster.
Example:-
Customer Segmentation
Customers are categorized by using clustering algorithms according to their purchasing behavior or
interests to develop focused marketing campaigns.
Imagine you have 10M customers, and you want to develop customized or focused marketing
campaigns. It is unlikely that you will develop 10M marketing campaigns, so what do we do? We
could use clustering to group 10M customers into 25 clusters and then design 25 marketing
campaigns instead of 10M.
Types of Clustering Methods
Clustering methods can be classified on the basis of how they form clusters,
Centroid-based clustering organizes data points around central prototypes called centroids, where
each cluster is represented by the mean (or medoid) of its members. The number of clusters is
specified in advance and the algorithm allocates points to the nearest centroid, making this
technique efficient for spherical and similarly sized clusters but sensitive to outliers and initialization.
Algorithms:
• K-medoids: Similar to K-means but uses actual data points (medoids) as centers, robust to
outliers.
Pros:
Cons:
Density-based clustering defines clusters as contiguous regions of high data density separated by
areas of lower density. This approach can identify clusters of arbitrary shapes, handles noise well
and does not require predefining the number of clusters, though its effectiveness depends on
chosen density parameters.
Algorithms:
• DBSCAN (Density-Based Spatial Clustering of Applications with Noise): Groups points with
sufficient neighbors; labels sparse points as noise.
• OPTICS (Ordering Points To Identify Clustering Structure): Extends DBSCAN to handle varying
densities.
Pros:
Cons:
Connectivity-based (or hierarchical) clustering builds nested groupings of data by evaluating how
data points are connected to their neighbors. It creates a dendrogram a tree-like structure that
reflects relationships at various granularity levels and does not require specifying cluster numbers in
advance, but can be computationally intensive.
Approaches:
• Agglomerative (Bottom-up): Start with each point as a cluster; iteratively merge closest
clusters.
• Divisive (Top-down): Start with one cluster; iteratively split into smaller clusters.
Pros:
Cons:
4. Distribution-based Clustering
Distribution-based clustering assumes data is generated from a mixture of probability distributions,
such as Gaussian distributions and assigns points to clusters based on statistical likelihood. This
method supports clusters with flexible shapes and overlaps, but usually requires specifying the
number of distributions.
Algorithm:
• Gaussian Mixture Model (GMM): Fits data as a weighted mixture of Gaussian distributions;
assigns data points based on likelihood.
Pros:
Cons:
• Sensitive to initialization.
Partition methods
• K-means algorithm
a) During the initialization phase, K observations are arbitrarily chosen in D as the centroids of
the clusters.
b) Each observation is iteratively assigned to the cluster whose centroid is the most similar to
the observation, in the sense that it minimizes the distance from the record.
c) If no observation is assigned to a different cluster with respect to the previous iteration, the
algorithm stops.
d) For each cluster, the new centroid is computed as the mean of the values of the observations
o The K-medoids algorithm, also known as partitioning around medoids, is a variant of the
K-means method. It is based on the use of medoids instead of the means of the
observations belonging to each cluster, with the purpose of mitigating the sensitivity of
the partitions generated with respect to the extreme values in the dataset.
o Given a cluster Ch, a medoid uh is the most central observation, in a sense that will be
formally defined, among those that are assigned to Ch. Once the medoid representing
each cluster has been identified, the K-medoids algorithm proceeds like the K-means
o Medoids are most commonly used on data when a mean or centroid cannot be defined, such
as graphs. They are also used in contexts where the centroid is not representative of the
dataset
o similar to the k-means algorithm but works when a mean or centroid is not definable.
Hierarchical methods
• Hierarchical clustering methods are based on a tree structure. Unlike partition methods, they do
not require the number of clusters to be determined in advance. Hence, they receive as input a
dataset D containing m observations and a matrix of distances dist(xi , xk) between all pairs of
observations.
• In order to evaluate the distance between two clusters, most hierarchical algorithms resort to one
of five alternative measures: minimum distance, maximum distance, mean distance, distance
o Minimum distance. According to the criterion of minimum distance, also called the single
linkage criterion, the dissimilarity between two clusters is given by the minimum distance
among all pairs of observations such that one belongs to the first cluster and the other to
o Maximum distance. According to the criterion of maximum distance, also called the
complete linkage criterion, the dissimilarity between two clusters is given by the
maximum distance among all pairs of observations such that one belongs to the first
o Mean distance. The mean distance criterion expresses the dissimilarity between two
clusters via the mean of the distances between all pairs of observations belonging to the
two clusters,
o Distance between centroids. The criterion based on the distance between centroids
determines the dissimilarity between two clusters through the distance between the
o Ward distance. The criterion of Ward distance, based on the analysis of the variance of
the Euclidean distances between the observations
o Hierarchical methods can be subdivided into two main groups: agglomerative and
divisive methods
initially represents a distinct cluster. These clusters are then aggregated during
algorithm is stopped when a single cluster including all the observations has been
reached.
• Agglomerative algorithm
a) In the initialization phase, each observation constitutes a cluster. The distance
b) The minimum distance between the clusters is then computed, and the two
clusters Ch and Cf with the minimum distance are merged, thus deriving a new
merger is recorded.
c) The distance between the new cluster Ce, resulting from the merger between Ch
d) If all the observations are included into a single cluster, the procedure stops.
single cluster. This is then subdivided into clusters of smaller size, so that the
correspond to an actual regular pattern in the data. It is therefore appropriate to apply other
clustering algorithms and to compare the results obtained by different methods. In this way it is
also possible to evaluate if the number of identified clusters is robust with respect to the different
techniques applied.