Importance of Distance Measures in Clustering
Importance of Distance Measures in Clustering
where,
• p and q are two data points
• and n is the number of dimensions.
Utilizing Euclidean Distance
import numpy as np
import [Link] as plt
point1 = [2, 3]
point2 = [5, 7]
distance = euclidean_distance(point1, point2)
print(f"Euclidean Distance: {distance}")
Implementation in Python
# Calculate Manhattan distance
def manhattan_distance(point1, point2):
return [Link]([Link]([Link](point1) - [Link](point2)))
Example in Python
# Calculate Cosine Similarity
def cosine_similarity(point1, point2):
dot_product = [Link](point1, point2)
norm1 = [Link](point1)
norm2 = [Link](point2)
return dot_product / (norm1 * norm2)
In the plot, the red and blue arrows represent the vectors of the two points from
the origin. The cosine similarity is related to the angle between these vectors.
Q2). Differentiate between K-Means and Kernel K-Means
algorithms.
Q3). Differentiate between KNN and K means
clustering
KNN (K-Nearest K-Means
Aspect
Neighbors) Clustering
Supervised learning Unsupervised
algorithm (used for learning algorithm
Type of Algorithm
classification & (used for
regression). clustering).
Classifies a data point
Groups unlabeled
based on the majority
Purpose data into k clusters
label of its nearest
based on similarity.
neighbors.
Requires labeled Works on
Input Data
data during training. unlabeled data.
Finds the k nearest
Randomly assigns
neighbors (using
cluster centers, then
distance measures
updates centroids
Working Principle like Euclidean,
iteratively to
Manhattan) and
minimize within-
assigns the majority
cluster variance.
class.
Predicts the class Produces k
label (for clusters with
Output
classification) or centroids but no
value (for regression). class labels.
KNN (K-Nearest K-Means
Aspect
Neighbors) Clustering
Needs training data No labeled data
Supervision with labels → required →
supervised. unsupervised.
Prediction phase can Training involves
be computationally iterative centroid
Computation expensive (distance updates but
from test point to all prediction is fast
training points). once trained.
Handwritten digit Customer
recognition, spam segmentation,
Examples of Use email detection, document
recommendation clustering, image
systems. compression.
In short:
• KNN → Supervised classification/regression (needs
labels, predicts categories).
• K-Means → Unsupervised clustering (no labels, just
groups similar data).
Q4). How does SVM work?
4. Margin Maximization
• Margin: The distance between the hyperplane
and the nearest data points of each class.
• SVM selects the hyperplane with the widest
margin, as a larger margin ensures better
generalization and reduces overfitting.
5. Types of SVM
1. Linear SVM:
o Works when the data is linearly separable.
o A straight line (or plane) can divide the
classes.
2. Non-Linear SVM (Kernel SVM):
o Used when data is not linearly separable.
o Applies the kernel trick (e.g., Polynomial
kernel, RBF kernel) to project data into a
higher dimension where it becomes
separable.
9. Conclusion
In summary, SVM works by finding the optimal
hyperplane that separates classes with the
maximum margin. It uses support vectors to
define this boundary and employs kernel
functions for handling complex, non-linear data.
Q5). Explain how k-fold cross-validation is applied
to evaluate a classification model.
5. Advantages
• Uses the entire dataset for both training and
testing (each point appears once in test set,
k−1k-1 times in training set).
• Reduces the problem of overfitting compared
to a single train-test split.
• Provides a more reliable estimate of model
performance.
6. Common Choices of k
• k=5k = 5 or k=10k = 10 are widely used in
practice.
• Larger k → lower bias, but higher
computational cost.
7. Conclusion
K-fold cross-validation is a robust evaluation
method where the dataset is divided into k folds,
and the model is trained and tested k times. The
average result gives a reliable estimate of the
classification model’s ability to generalize to
unseen data.
Q6). Analyze why ensemble methods often
outperform single models.
Example
Suppose we are classifying emails as spam or not
spam.
• A single decision tree may give 75% accuracy
because it may overfit the training data.
• But if we use a Random Forest (which
combines many decision trees), the accuracy
may rise to 90%.
This shows how ensembles reduce errors and
provide more reliable results than a single
model.
Conclusion
Ensemble methods often outperform single models
because they reduce variance, reduce bias,
cancel errors, improve generalization, and
make use of model diversity. They follow the
principle of the “wisdom of the crowd”—many
weak learners together can create a very strong
learner.
Thus, ensemble methods are widely used in
practice and generally give more accurate and
robust results than individual models.
Q7). What is the error between predicted and
actual output is called?
In machine learning, the error between the
predicted output (what the model gives) and the
actual output (true/expected value) is called the
Residual or simply Prediction Error.
Explanation
• When a model makes a prediction, it may not
always be exactly correct.
• The difference between the true value (y) and
the predicted value (ŷ) is the error:
� Answer (Exam-ready):
The error between predicted and actual output is
called the Residual (or Prediction Error),
defined as the difference between the true value
and the predicted value:
Error=y−y^
Q8). What is regression?
Regression
1. Introduction
Regression is a supervised machine learning
technique used to predict a continuous output
variable (also called the dependent variable) based
on one or more input variables (independent
variables).
It establishes a mathematical relationship between
input (X) and output (Y).
2. Definition
Regression is the process of finding a function that
maps input features to a continuous target
variable.
Formally:
Y=f(X)+ϵ
where:
• Y= dependent variable (target/output)
• X = independent variable(s) (features/input)
• ϵ = error term (difference between predicted
and actual values)
3. Purpose of Regression
• To predict future values based on historical
data.
• To understand relationships between
variables (how change in X affects Y).
• To estimate trends and make decisions.
4. Types of Regression
1. Linear Regression: Models relationship using
a straight line.
o Example: Predicting house price based on
area.
o Equation:
Y=aX+b
2. Multiple Linear Regression: Uses more than
one input variable.
o Example: Predicting salary using age,
experience, and education level.
3. Polynomial Regression: Uses higher-degree
polynomials to fit non-linear data.
4. Logistic Regression (special case): Used for
classification problems where output is
categorical (yes/no, 0/1).
5. Example
Suppose we want to predict the marks of students
based on hours studied.
• Data shows a positive trend: more hours
studied → higher marks.
• Regression line can be drawn to represent this
relationship.
• If a student studied 5 hours, regression can
predict their expected marks.
6. Conclusion
Regression is a fundamental technique in machine
learning and statistics that predicts a continuous
output variable based on input variables. It is
widely used in forecasting, economics, finance,
and real-world decision-making.
� Exam-Ready Short Answer:
Regression is a supervised learning method that
models the relationship between dependent and
independent variables, used to predict continuous
values such as prices, age, salary, or temperature.
3. Intuition
• In 2D data, the decision boundary is usually a
line or curve.
• In 3D data, it becomes a plane or surface.
• In higher dimensions, it is called a
hyperplane.
4. Example
• Suppose we are classifying emails as Spam or
Not Spam using two features (e.g., number of
links and number of words).
• The decision boundary could be a line that
separates the region of "Spam" from "Not
Spam".
• For Logistic Regression, the decision
boundary is a straight line.
• For SVM, it is a hyperplane with maximum
margin.
• For Decision Trees, the boundary may look
irregular and piecewise.
5. Importance
• Helps us understand how a model makes
predictions.
• Shows whether a model is too simple (linear
boundary) or flexible enough (non-linear
boundary).
• Visualizes how well the classes are separated.
6. Conclusion
A decision boundary is the dividing line (or
surface) in the feature space that determines the
class label assigned by a classifier. It plays a
crucial role in understanding the behavior and
performance of classification algorithms.
2. Definition
Overfitting occurs when a model performs very
well on training data but fails to give good
accuracy on new or testing data because it has
memorized the data instead of learning general
patterns.
3. Characteristics of Overfitting
• High accuracy on training set.
• Low accuracy on testing/validation set.
• Model is too complex (too many parameters,
deep trees, high-degree polynomials).
• Captures noise along with the actual pattern.
4. Example
Suppose we want to predict students’ marks based
on study hours:
• A simple model may draw a straight line
(generalizes well).
• An overfitted model may create a very zig-
zag curve that passes through every training
point.
o Training accuracy = 100%
o Testing accuracy = very poor
5. Causes of Overfitting
• Too complex models (deep decision trees,
high-degree polynomials).
• Too little training data.
• Training for too many iterations (in neural
networks).
• Lack of proper regularization.
6. Ways to Prevent Overfitting
• Use cross-validation (e.g., k-fold CV).
• Apply regularization (L1, L2 penalties).
• Reduce model complexity (pruning in decision
trees, fewer parameters).
• Collect more training data.
• Use techniques like dropout in neural networks.
• Early stopping during training.
7. Conclusion
Overfitting means the model has learned training data
too well, including noise, which reduces its ability to
generalize to unseen data. The solution is to find a
balance between underfitting and overfitting so the
model performs well on both training and testing data.
� In short:
• Training set → learning.
• Validation set → tuning.
• Testing set → final evaluation.
Q12). What are the kernel functions used in SVM?
Kernel Functions in SVM
1. Introduction
Support Vector Machines (SVM) can separate data
using a hyperplane. However, when data is not
linearly separable in the original feature space,
SVM uses a technique called the Kernel Trick.
• A kernel function maps data into a higher-
dimensional space where it can be linearly
separated.
• Instead of explicitly transforming the data, the
kernel computes similarity between points in
the transformed space efficiently.
2. Commonly Used Kernel Functions
1. Linear Kernel
o Formula:
K(x,y)=x⋅y
Used when data is linearly separable.
o Simple and less computationally
expensive.
o Example: Text classification problems.
2. Polynomial Kernel
o Formula:
4. Conclusion
Kernel functions in SVM help transform data into
higher dimensions where classes can be separated
easily. Common kernels include Linear,
Polynomial, RBF, and Sigmoid, each suitable for
different types of problems.
� Exam-ready short definition:
Kernel functions in SVM are mathematical tools
that transform data into higher dimensions to
handle non-linear classification. Examples include
Linear, Polynomial, RBF (Gaussian), and
Sigmoid kernels.
Confusion Matrix �
Confusion Matrix
1. Introduction
In classification problems, we often need to evaluate how well a
model performs. A confusion matrix is a performance measurement
tool that shows how many predictions were correct and how many
were wrong, broken down by class.
2. Definition
A confusion matrix is a tabular representation that compares the
actual class labels with the predicted class labels made by a
classification model.
• Rows → Actual values
• Columns → Predicted values
3. Structure of Confusion Matrix (for Binary Classification)
Predicted Positive Predicted Negative
Actual Positive True Positive (TP) False Negative (FN)
Actual Negative False Positive (FP) True Negative (TN)
4. Terms Explained
• True Positive (TP): Model correctly predicts positive class.
• True Negative (TN): Model correctly predicts negative class.
• False Positive (FP): Model predicts positive, but actually
negative (Type I error).
• False Negative (FN): Model predicts negative, but actually
positive (Type II error).
6. Example
Suppose we are classifying whether an email is Spam or Not Spam:
• Actual = Spam, Predicted = Spam → TP
• Actual = Not Spam, Predicted = Not Spam → TN
• Actual = Not Spam, Predicted = Spam → FP (false alarm)
• Actual = Spam, Predicted = Not Spam → FN (missed detection)
7. Conclusion
The confusion matrix provides a detailed breakdown of classification
performance, helping to identify not just accuracy but also where the
model is making mistakes (false positives and false negatives).
Purpose of Validation
1. Introduction
In machine learning, data is usually divided into three parts:
• Training set → used to train the model.
• Validation set → used to tune the model.
• Testing set → used to evaluate the final model.
Among these, the validation set plays a very important role in model
development.
2. Definition
Validation is the process of checking how well a trained model
performs on a separate dataset (validation set) that was not used
during training.
3. Purpose of Validation
1. Hyperparameter Tuning
o Helps select the best parameters (e.g., learning rate, depth
of a decision tree, number of clusters in K-means).
2. Model Selection
o Compares different models (e.g., SVM vs Decision Tree)
and chooses the one that performs best on validation data.
3. Prevent Overfitting
o If the model performs very well on training data but poorly
on validation data, it indicates overfitting.
o Helps in deciding whether to simplify the model.
4. Performance Estimation
o Provides an unbiased estimate of how the model might
perform on unseen data before using the test set.
5. Early Stopping (in Neural Networks)
o During training, if validation error starts increasing while
training error decreases, training is stopped early to avoid
overfitting.
4. Example
Suppose we train a neural network on a dataset:
• Training accuracy = 98%
• Validation accuracy = 78%
→ This indicates overfitting, and we may reduce complexity or
apply regularization.
5. Conclusion
The main purpose of validation is to fine-tune, compare, and
improve models without touching the test data. It ensures that the
final model chosen is more generalized and works well on unseen
data.
2. Definition
The KNN classifier is a non-parametric, instance-based learning
algorithm that classifies a new data point based on the majority class
of its ‘K’ nearest neighbors in the training dataset.
4. Example
Suppose we want to classify whether a fruit is an Apple or Orange
based on features (weight, texture):
• If K = 3 and among the 3 nearest neighbors, 2 are Apples and 1
is Orange → the fruit will be classified as Apple.
5. Important Parameters
• K value:
o Small K → model is sensitive to noise.
o Large K → model is more stable but may ignore local
patterns.
• Distance Metric:
o Euclidean Distance (common in continuous data).
o Manhattan Distance.
o Cosine similarity for text data.
6. Advantages of KNN
• Simple to understand and implement.
• No training phase → “lazy learner.”
• Works well with multi-class classification.
7. Disadvantages of KNN
• Computationally expensive for large datasets.
• Sensitive to irrelevant/noisy features.
• Requires feature scaling (normalization/standardization).
• Choice of K is critical.
9. Conclusion
The KNN classifier is a simple yet powerful algorithm that classifies
data points based on the majority class of their nearest neighbors. Its
performance largely depends on the choice of K and the distance
metric used.