ML Unit 2
ML Unit 2
√ Euclidean distance
√ Cosine similarity
√ Jaccard similarity
√ Hamming distance
D(x,y)=(x1−y1)2+(x2−y2)2+ +(xn−yn)2
Imagine two points on a map: A(1, 1) and B(4, 5). The Euclidean distance between
them is: √((4 - 1)² + (5 - 1)²) = √(3² + 4²) = √25 = 5 units
Cosine similarity: Cosine similarity is a measure of similarity between two non-zero
vectors defined in an inner product space. It's commonly used in text analysis to
determine how similar documents are based on the frequency of shared terms.
1
Cosine Similarity : cos(θ)= x ⋅ y x⋅y
x=(2,1),y=(4,2)
x =22+12=5, y =42+22=20
Distance Measures
1. Minkowski Distance :
Minkowski distance is a metric in a normed vector space that generalizes both
Euclidean and Manhattan distances. It provides a way to measure the distance
between two points in a multi-dimensional space, with the flexibility to adjust the
distance calculation based on a parameter p. he Minkowski Distance is a
generalization of both the Euclidean distance and the Manhattan distance.
L 1/k
D(x,y) = ∑ k=1 |P k -q k |
Where r is the parameter tht determines the type of metric.
P and Q are l –dimensional vectors.
Mathematical Properties
L norm Here r = and d(p,q) = maximum k = (|p(k) - q(k)), K € {1,2,3,….L}.
2)1/2
L2 norm Here r = 2 d(p,q) = | It is called as Euclidean distance
L1 norm Here r=1 and d (p,q) = |) It is known as city block distance / Manhattan
distance
Fractional norm : It is possible that r is a fraction. As a result distance is called as
fractional norm.
3
Consider two points in 3D space:
A = (2, 5, 8), B = (3, 1, 6)
For Manhattan Distance (p = 1)
D(A,B)= 2−3 + 5−1 + 8−6 =1+4+2=7D(A,B)= 2−3 + 5−1 + 8−6 =1+4+2=7
For Euclidean Distance (p = 2)
D(A,B)=(2−3)2+(5−1)2+(8−6)2D(A,B)=(2−3)2+(5−1)2+(8−6)2
D(A,B)=1+16+4=21≈4.58D(A,B)=1+16+4=21≈4.58
For Chebyshev Distance (p→∞)
D(A,B)=max( 2−3 , 5−1 , 8−6 )=max(1,4,2)=4D(A,B)=max( 2−3 , 5−1 , 8−6 )=max(1,4,2)=4
The importance of different norms will be examined while explaining the nearest
neighbor classifiers. Manhalanobis distance is another popular distance measure that
is used in classification. The squared Manhalanobis distance is given by distance
2 t -1
D (x,y) = (x - y) ∑ (x - y)
Real- Life Applications
1. Machine Learning & Clustering
4
2. Image Processing
3. Finance & Risk Analysis
4. Robotics & Path Planning
3. Weighted Distance Measure
A weighted distance measure assigns different importance (weights) to different
dimensions or components when calculating the distance between two data points.
It's a generalization of standard distance metrics like Euclidean or Hamming distance,
where each component contributes equally. This is useful when some features are
more important than others in determining similarity or distance.
n r 1/r
D(x,y)=( k =1 ∑ wik * (xk−yk) )
th
Where wk represents the weight associated with the k dimension or feature.
Let: x=(2,3) y=(5,7) Weights: w=(0.6,0.4) p =2 (Weighted Euclidean)
2
D(x,y)=0.6⋅(2−5)2+0.4⋅(3−7)
√0.6⋅9+0.4⋅16 =√5.4+6.4 =11.8 ≈3.435
4. Non - Metric Similarity Functions
The category includes similarity functions that do not obey the triangular or symmetry. They
are commonly used for image or string data and they are resistant to outliers or extremely
noisy data. The squard Euclidean distance is an example of a non – metric, but it provides the
same ranking as the Euclidean distance metric. It does not fulfill all properties of a distance
metric , such as:
Non- negativity
Identity of indiscernibles (d(x, x) = 0)
Symmetry (d(x, y) = d(y, x))
Triangle inequality (d(x, z) ≤ d(x, y) + d(y, z))
2. Jaccard Similarity
For sets A and B:
Jaccard(A,B) = |A∩B| / | A∩B|
Used for binary or set data.
Jaccard distance can be derived but Jaccard similarity itself is not a metric.
5. Mutual Information
Measures how much knowing one variable reduce uncertainty about another.
Violates symmetry.
Applications:
6
Document similarity (Cosine)
Gene similarity (Mutual Information)
Recommendation systems (Jaccard)
Clustering non- metric data (e.g., hierarchical clustering with similarity matrices)
4. Levenshtein Distance
Levenshtein Distance is also known as edit distance. It measure the distance
between two strings. It is determined by calculating the minimum number of
mutations needed to transform strings s1 into string s2. The mutation can be one of
three operations changing a lettet, inserting a letter or deleting a letter. Mutation
means a change or alteration . The edit distance can be defined as.
1. Two empty strings match d(“ ”,” “)
2. Distance from an empty string d(s,” “) = d(“ ”,s) = ||s||
3. D(s1 + ch1, s2+ch2) = min [ d(s1,s2) + { if ch1 = ch2 then 0 else 1}
D(s1 + ch1, s2)+1, d(s1, s2+ch2) + 1]
Example:
Find the Levenshtein distance between:
"kitten" and "sitting"
Steps:
1. kitten → sitten (substitute 'k' with 's')
2. sitten → sittin (substitute 'e' with 'i')
3. sittin → sitting (insert 'g')
Levenshtein Distance = 3
Applications:
Spell checkers and autocorrect
DNA sequence comparison in bioinformatics
Plagiarism detection
Natural Language Processing (NLP)
Search algorithms with typo tolerance
Properties:
Non- negative
Symmetric
Satisfies triangle inequality
Hence, Levenshtein Distance is a metric
5. Mutual Neighborhood Distance (NMD)
Mutual Neighborhood Distance (NMD) between two data points x and y is based
on the common elements in their k-nearest neighbors .
Instead of directly computing distance (like Euclidean), NMD compares the
similarity of the neighborhood around two points.
7
It measures how similar the local environments (neighbors) of two data points are.
NMD is a distance-based similarity measure used in pattern recognition , classification,
and clustering tasks. If two data points x and y share many of the same nearest
neighbors, they are considered similar → hence, they have low NMD . If they have
very different neighbors , they are considered distant → higher NMD.
Mutual Neighborhood Distance (NMD) is defined as:
NMD(x,y)=1 − k Nk(x)∩Nk(y) k
1. For a given point x, find its k nearest neighbors → N_k(x)
2. For another point y, find its k nearest neighbors → N_k(y)
Nk(x)∩Nk(y) - number of common neighbors
k: the total number of neighbors considered
The value ranges from 0 (very similar) to 1 (completely different)
Properties:
NMD is not a metric :
o It may not satisfy triangle inequality
o It is based on set overlap , not geometric distance
Useful in non-Euclidean spaces
Effective in high-dimensional or noisy datasets
Example
Let’s say we have 5 data points: A, B, C, D, E
N₂(A) = [ B, C]
N₂(D) = [ C, E]
NMD(A,D )= 1 / − [ B,C] ∩[ C,E] | / 2 = 1- 1/ 2 = 0.5
So, the NMD between A and D is 0.5
NMD is Used in
Clustering (e.g., Mutual k- NN clustering)
Classification (k- NN- based classifiers)
Anomaly detection
When neighborhood structure is more important than absolute distance .
Hamming Distance
Hamming distance is the number of mismatching bits of the l –bit locations.
8
Counts the number of bit positions where the two binary vectors differ.
Lower value → more similar
Example:
X = [1, 0, 1, 1, 0]
Y = [1, 1, 0, 1, 0]
Difference: [0, 1, 1, 0, 0] → 2 positions differ
Hamming Distance = 2
2. Jaccard Similarity
Focuses only on the positions where at least one of the vectors is 1.
Formula:
Jaccard(X,Y) = f11 / f01 + f10 + f11
where:
o f11: number of positions where both X and Y are 1
o f01 : X=0, Y=1
o f10 : X=1, Y=0
Example:
X = [1, 0, 1, 1, 0]
Y = [ 1, 1, 0, 1, 0]
f11=2 (positions 1 and 4)
f01=1 (position 2)
f10=1 (position 3)
Jaccard = 2 / 2+1+1 = 2 / 4 = 0.5
where f00 is the number of positions where both are 0, and n is the total number of
bits.
Example:
f11=2, f00=2, n =5
1. Cosine Similarity
Treats binary vectors as vectors in space and computes cosine of the angle
between them.
9
In binary vectors, dot product counts f11
10
.
Most common dista nce is Euclidean Distance
d(x,xi) = ∑n(xj−xi)2
where
x = test point
xi = training point
n= number of features
Training Data Feature 1 Feature 2 Class
A 2 4 Red
B 4 6 Blue
C 1 3 Blue
11
Test point : (2.5, 3.5)
Compute distance to each point → Find nearest → Assign class label of nearest point.
Eg: Apple –Weight - 150g, Color - red
Banana –Weight –140g, Color –yellow
New data Weight 145g, color –red
So it is similar to red
Advantages:
Very simple to understand and implement
No training needed (lazy learner)
Works well with small datasets
Adapts easily to new data
Disadvantages:
Slow for large datasets
Sensitive to irrelevant or scaled features
Advantages of K- NN
1. Simple to Understand and Implement : K-NN is one of the most intuitive
algorithms, making it easy to understand and implement.
2. No Training Phase: K-NN is a lazy learner (also called a memory-based learner),
meaning it doesn't require training or model fitting. It just memorizes the
training dataset.
3. Non-parametric : K-NN doesn’t make any assumptions about the underlying
data distribution, making it useful for complex datasets with unknown
distributions.
4. Versatile: Can be used for both classification and regression tasks.
Disadvantages of K- NN
1. Computationally Expensive : Since it stores all the training data, making
13
predictions can be slow, especially with large datasets.
2. Sensitive to the Choice of K : The performance can vary greatly with different
values of K. Small values of K can lead to over fitting , while large values of K
can lead to under fitting .
3. Sensitive to Irrelevant Features : K-NN is sensitive to irrelevant features and noisy
data. If the features are not well- scaled, the algorithm may perform poorly.
4. Memory Intensive : K-NN requires storing all the training data, which can be
problematic with large datasets.
Let's say we have a simple dataset with three classes (Red, Blue, Green) and three
features (X, Y):
X Y Clas
s
1 2
Red
2 3 Blu
e
3 1 Gre
en
5 4 Blu
e
4 4 Gre
en
Now, we want to classify a new point (3, 2) using Weighted K-NN with K=3.
1. Calculate Distances:
o Calculate the Euclidean distance from (3, 2) to each point in the dataset.
2. Find K Nearest Neighbors :
o The 3 nearest neighbors based on the distances are: (2, 3) [Blue], (1, 2)
[ Red] , and (3, 1) [ Green] .
3. Assign Weights :
The weights will be:
o Weight of (2, 3) =0.71
o Weight of (1, 2) =0.50
o Weight of (3, 1) =1.00
15
4. Weighted Voting :
o The predicted class will be based on the weighted vote :
Blue has a weight of 0.71.
Red has a weight of 0.50.
Green has a weight of 1.00.
Based on the weighted vote, the Green class has the highest weight and will be
predicted as the class for the new point.
1 2 100
2 3 150
3 1 200
5 4 250
4 4 300
We want to predict the price for the new point (3, 2).
1. Calculate Distances:
o Calculate the Euclidean distance between the new point (3, 2) and all the
points in the dataset.
2. Find K Nearest Neighbors :
o The 3 nearest neighbors are: (2, 3) [Price = 150], (3, 1) [Price = 200], and
(4, 4) [ Price = 300] .
3. Assign Weights :
o Based on inverse distance, calculate the weights as before:
Weight of (2, 3) =0.71
Weight of (3, 1) =1.00
Weight of (4, 4) =0.45
4. Weighted Average :
o Calculate the weighted average of the prices for these 3 neighbors:
Predicted Price=(0.71×150)+(1.00×200)+(0.45×300)0.71+1.00+0.45
= 441.5 / 2.16
= 204.17
So, the predicted price for the new point (3, 2) is approximately 204.17.
16
Advantages of Weighted K- NN:
1. More Accurate Predictions : By weighting the neighbors based on their distance,
closer neighbors (which are more likely to be similar) have a larger influence on
the prediction.
2. Improves Performance for Non-Uniform Data : When the data has varying
densities, weighted K-NN can give better results by adjusting for local
variations.
3. Flexibility : You can use different weighting schemes (inverse distance, Gaussian
kernel, etc.) to further refine the model's performance.
Steps:
1. Choose a radius value r (e.g., 2.0).
2. For the test point, calculate the distance to each training point.
3. Select all training points whose distance ≤ r.
17
4. Among those selected:
o Do majority voting for classification.
5. If no points are found within radius:
o You may reject the classification, or
o Use the nearest neighbor , or
o Increase the radius dynamically.
For example: Imagine you're in a city and you want to know what most people around
you like to eat - Pizza, Burger, or Biryani).
You set a rule:
I’ll only ask people within 2 km of me.”
If: Most say Pizza, you choose Pizza.
If no one is around you within 2 km, you say: “I can’t decide” (or increase your
search area).
Applications:
Pattern recognition
Anomaly detection
Medical diagnosis
Recommender systems
Poi
nt Coordinates Class
A
(1, 2) 0
B (2, 3) 0
18
C (5, 5) 1
D (8, 8) 1
Now, we have a test point T = (2, 2)
Set radius r = 2
Distance from A = 1.0 within radius
Distance from B = 1.41 within radius
Distance from C = 4.24 outside radius
Distance from D = 8.48 outside radius
Only A and B are considered → Class 0 wins
So, test point T is classified as Class 0
5 Tree –Based Nearest Neighbor Algorithm
An FP-Tree helps to find frequently bought items together (frequent patterns)
without scanning the whole database again and again.
Steps
Step 1: Find Frequency of Items
Go through the entire transaction database once.
Count how many times each item appears .
This is called the support count .
Now, remove items that are less frequent (below the user-defined minimum
support).
Sort the remaining items in descending order of frequency.
Example:
Transactions: T1: {Milk, Bread, Butter}
T2: {Bread, Butter}
T3: {Milk, Bread}
T4: {Milk, Bread, Butter}
Frequencies:
Bread: 4
Milk: 3
Butter: 3
Sorted order: Bread > Milk > Butter
Step 2: Reorder Each Transaction
Step 3: Start Building the FP-Tree
Step 4: Add More Transactions
19
A (2, 3)
B (5, 4)
C (9, 6)
D (4, 7)
E (8, 1)
F (7, 2)
Advantages
Guarantees finding the optimal solution.
Reduces computational cost by pruning unnecessary branches.
Works well for small to medium- sized feature sets.
Limitations
Computationally expensive for very large feature spaces.
Performance depends on the quality of the bounding function.
Example
A (1,1)
B (2,8)
C (7,2)
D (8,9)
E (6,6)
All Points
/ \
Cluster 1 Cluster 2
(A,B) (C,D,E)
Cluster 1 Cluster 2
/ \ / \
A(1,1) B(2,8) C(7,2) (D,E)
/ \
D(8,9) E(6,6)
22
Step 2 - Search the Most Promising Cluster First
Cluster 1 (A,B) : is A(1,1) → min possible distance ≈ 5.66
Cluster 2 (C,D,E) : Closest point is E(6,6) → min possible distance ≈ 1.41
Final clusters:
Cluster 1: {2, 3} (leader = 2)
Cluster 2: {10, 12, 11} (leader = 10)
24
Cluster 3: {30} (leader = 30)
KNN Regression
KNN Regression (K-Nearest Neighbors Regression) is a supervised machine learning
algorithm used to predict numerical (continuous) values based on the values of the k
nearest neighbors in the training data. Instead of predicting a class label like in KNN
Classification, it predicts a number (e.g., house price, temperature, age).
Key Features
Non-parametric : KNN makes no assumptions about the underlying data
distribution.
Lazy Learning: It doesn't train a model explicitly; instead, it stores the dataset
and performs computation during prediction.
Versatile: Works well for both regression and classification tasks.
Advantages
Simple and easy to implement.
Effective for small datasets with low dimensionality.
No training phase, making it computationally inexpensive for training.
Disadvantages
Computationally expensive during prediction for large datasets.
Sensitive to the choice of k and distance metric.
25
Performance can degrade with high- dimensional data (curse of dimensionality).
Steps
1. Choose the value of k (number of neighbors to consider).
2. For a new data point, find the k closest data points in the training set using a
distance measure (e.g., Euclidean distance).
3. Take the average (or weighted average) of these neighbors’ values.
4. That average becomes the predicted value .
Example: Guess the temperature in a city today based on the temperatures of nearby
cities.
Step 1: Choose k k = 3
Step 2: Find nearest neighbors
City C → 29°C
City A → 30°C
City B → 32°C
Step 3: Average their temperatures
Predicted temperature =329+30+32 / 391=30.33 C
The estimated temperature for the target city is 30.33°C.
Performance of Classifiers
The performance of classifiers refers to how well a classification algorithm can correctly
predict the labels (categories) of unseen data. It is usually measured using metrics
that compare the model’s predictions with the actual (true) labels.
1. Confusion Matrix
A table showing how many predictions were correct and how many were wrong,
broken down into:
True Positive (TP) → Correctly predicted positive cases.
True Negative (TN) → Correctly predicted negative cases.
False Positive (FP) → Predicted positive but actually negative (Type I error).
False Negative (FN) → Predicted negative but actually positive (Type II error).
26
Accuracy=TP + TN / Total Predictions.
Example
Imagine a spam email classifier:
TP → Spam emails correctly marked as spam.
TN → Real emails correctly marked as not spam.
FP → Real emails wrongly marked as spam.
FN → Spam emails wrongly marked as real.
A high-performing classifier will have high TP and TN values while keeping FP and FN
low.
27
Preference of Regression Algorithm
The preference of a regression algorithm depends on the type of data you have, the
problem you’re solving, and the trade-offs you’re willing to accept between accuracy,
interpretability, and computation time.
Mean Squared Error (MSE)
It is a performance metric used to measure how far the predicted values are from the
actual values in regression problems .
Formula
n 2
MSE=1 / n∑ i=1(yi−y^i)
Where:
n = number of data points
yi = actual (true) value
y^ i = predicted value
The squared difference ensures all errors are positive and penalizes large errors
more heavily.
Steps
Take the difference between the real value and the predicted value .
Square it (to remove negatives and punish big mistakes).
Add all these squared errors.
Divide by the number of data points.
Example
Suppose the actual values are: [5, 6, 7]
Predicted values are: [ 4, 8, 6]
28
Step-by-
step:
Formula
n
MAE=1 / n ∑ i=1 yi−y^ i
Where:
Steps
Take the difference between real and predicted values.
Ignore whether the difference is positive or negative (use absolute value).
Add up all these absolute differences.
Divide by the number of data points.
Example
Actual values: [5, 6, 7]
Predicted values: [ 4, 8, 6]
1. Errors: 5 − 4 = 1 , 6 – 8 = −2, 7− 6 = 1
2. Absolute errors: 1 =1 , −2 =2 , 1 =1
3. Sum of absolute errors: 1+2+1=4
4. Divide by n=3
MAE = 4 / 3≈1.33
29