ML Notes
ML Notes
Module 1
BAQ [ 2 Marks]
Q1. What is the importance of Linear Regression?
Linear Regression is a statistical and machine learning method used to model the relationship
between a dependent variable and one or more independent variables.
Key Points:
• Prediction: Helps predict future values based on past data (e.g., house price prediction).
• Simple and Interpretable: Easy to understand and interpret compared to complex ML models.
• Foundation for Advanced Models: Many algorithms like logistic regression and neural networks
are based on regression concepts.
• Analyzes Relationships: Shows how strongly independent variables influence the dependent
variable.
• Widely Used: Applied in finance, healthcare, marketing, and economics for forecasting and
analysis.
Key Points
• It maps any real number into the range 0 to 1.
Formula
1
𝜎(𝑧) =
1+𝑒 −𝑧
where
𝑧 = 𝛽0 + 𝛽1 𝑥
Q3. What is Maximum Likelihood Estimation (MLE)?
Maximum Likelihood Estimation (MLE) is a statistical method used to estimate model parameters
by choosing the values that maximize the probability of observing the given data.
Key Points
• It is used to estimate parameters of models such as 𝛽 0β0 and 𝛽 1β1 in logistic regression.
• It selects the parameters that make the observed data most probable.
where
𝑝 𝑖= predicted probability for observation 𝑖
MLE estimates parameters by maximizing the probability of observing the given data.
Key Points
• Ridge Regression (L2 Regularization):
Adds the square of coefficients as a penalty to shrink coefficient values.
• Feature Selection:
Lasso can shrink some coefficients exactly to zero, which automatically selects important features.
• Overfitting Control:
Both methods improve model generalization by reducing model complexity.
Penalty Terms
Ridge:
𝜆∑𝛽 2
Lasso:
𝜆∑ ∣ 𝛽 ∣
Key Points
• It measures how strongly an independent variable is correlated with other independent
variables.
• General rule:
· VIF = 1 → No correlation
· VIF > 5 → Moderate multicollinearity
· VIF > 10 → Severe multicollinearity
Formula
1
𝑉𝐼𝐹 =
1−𝑅 2
where
𝑅 2 = coefficient of determination when one independent variable is regressed against others.
VIF measures how well an independent variable is explained by other independent variables,
helping detect multicollinearity.
Substitute value:
0.8
𝑂𝑑𝑑𝑠 =
1−0.8
0.8
𝑂𝑑𝑑𝑠 = 0.2
𝑂𝑑𝑑𝑠 = 4
So,
Log-Odds (Logit)
Formula:
𝑝
𝐿𝑜𝑔 − 𝑂𝑑𝑑𝑠 = 𝑙𝑛
1−𝑝
Substitute value:
𝑙𝑛 ( 4)
✅ Final Answer
• Odds = 4
• Log-Odds ≈ 1.386
Steps
• Fit the Model
Build regression models using different variables or features.
• Evaluate Goodness of Fit
Use measures like R² (coefficient of determination) to check how well the model explains the
variation in data.
• Perform Cross-Validation
Use techniques like k-fold cross validation to test model performance on unseen data.
According to the module slides, metrics such as R², RSS, AIC, and cross-validation are used to
compare regression models and choose the best one.
SAQ
What is multicollinearity in multiple linear regression?
Multicollinearity occurs when two or more independent variables in a multiple linear regression
model are highly correlated with each other.
Explanation
• In multiple linear regression, several independent variables are used to predict a dependent
variable.
• When two or more predictors are strongly correlated, it becomes difficult to determine the
individual effect of each variable on the dependent variable.
• Multicollinearity increases the variance of regression coefficients, making the model unstable.
• Multicollinearity is commonly detected using Variance Inflation Factor (VIF). A large VIF value
indicates strong multicollinearity.
Example
If X₁ = house size and X₂ = number of rooms, these variables may be highly correlated, causing
multicollinearity.
Detection
• Using Variance Inflation Factor (VIF).
Explanation
• In linear regression, the goal is to find a line that best represents the relationship between
independent variable 𝑥x and dependent variable 𝑦y.
• The least squares method minimizes the sum of squared errors (SSE) between actual values and
predicted values.
• Squaring the errors ensures that positive and negative errors do not cancel each other.
• The method determines the optimal values of regression coefficients (intercept 𝛽 0β0 and slope
𝛽 1β1).
• This technique helps produce the best regression line for prediction and analysis.
Formula
𝑦 = 𝛽0 + 𝛽1 𝑥
Where
𝛽 0 = intercept
𝛽 1= slope of regression line
Error Minimization
2
𝑆𝑆𝐸 = ∑(𝑦 𝑖 −)
Homoscedasticity Heteroscedasticity
· Variance of error terms remains · Variance of error terms changes or is
constant across all values of the unequal across values of the
independent variable. independent variable.
· Residuals are evenly distributed · Residuals show an uneven or funnel-
around the regression line. shaped pattern.
· It satisfies one of the assumptions of · It violates the assumption of linear
linear regression. regression.
· Leads to reliable and efficient · Can produce biased or inefficient
regression estimates. estimates.
· Indicates potential problems in the
· Indicates a good regression model fit.
regression model.
Explanation
• Odds measure the likelihood of an event occurring compared to it not occurring.
• Log-odds (also called the logit function) is the logarithm of the odds and is used in logistic
regression to model the relationship between variables.
• Logistic regression transforms the linear equation into probability using the sigmoid function.
Formula
Odds
𝑝
𝑂𝑑𝑑𝑠 =
1−𝑝
Log-Odds (Logit)
𝑝
𝐿𝑜𝑔 − 𝑂𝑑𝑑𝑠 = 𝑙𝑛
1−𝑝
Example
If probability 𝑝 = 0.8
Odds = 0.8/0.2 = 4
Log-odds = 𝑙𝑛 ( 4) ≈ 1.386
Update Formula
𝜕𝐽(𝜃)
𝜃 = 𝜃−𝛼
𝜕𝜃
Where:
· 𝜃= model parameter
· 𝛼= learning rate
· 𝐽(𝜃) = cost function
Linear regression is used for regression problems, while logistic regression is used for classification
problems.
LAQ
Illustrate Model Assessment and Comparison in Linear
Regression
1. Introduction
Model assessment in linear regression is used to evaluate how well a regression model fits the data
and predicts outcomes. Multiple models may be compared to select the best performing model.
𝑆𝑆𝐸
𝑅 2 = 1−
𝑆𝑆𝑇
Where
SSE = Sum of Squared Errors
SST = Total Sum of Squares
3. Residual Analysis
Residuals are the difference between observed and predicted values.
^
𝑅𝑒𝑠𝑖𝑑𝑢𝑎𝑙 = 𝑦 𝑖 −𝑦 𝑖
· model errors
· heteroscedasticity
· non-linearity
𝐴𝐼𝐶 = 𝑛 𝑙𝑛 ( ) + 2𝑘
Where
n = number of observations
k = number of parameters
Lower AIC value indicates a better model.
5. Cross-Validation
Cross-validation evaluates the model using different subsets of data.
7. Conclusion
Model assessment helps:
3. Evaluation Metrics
1.️ Accuracy
Accuracy measures the overall correctness of the model.
Formula:
2.️ Precision
Precision measures how many predicted positives are actually positive.
4.️ F1 Score
F1 score balances precision and recall.
4. Example
Suppose a model predicts disease detection.
5. Conclusion
Confusion matrix and its metrics help:
2. Confusion Matrix
A confusion matrix compares actual and predicted values of the model.
3. Accuracy
Accuracy measures the overall correctness of the model.
4. Precision
Precision measures how many predicted positives are actually correct.
The Area Under the Curve (AUC) measures the model's ability to distinguish between classes.
7. Conclusion
Evaluation metrics help determine whether a logistic regression model is accurate, reliable, and
suitable for prediction tasks.
𝑦 = 𝛽0 + 𝛽1 𝑥
Where:
3. Calculate intercept (𝛽 0)
ˉ ˉ
𝛽 0 = 𝑦𝛽 1 𝑥
𝑦 = 𝛽0 + 𝛽1 𝑥
4. Example
Suppose we have points:
x y
1 3
2 4
3 8
4 9
The estimated regression line becomes:
𝑦 = 0.5 + 2.2𝑥
This line can be used to predict future values of 𝑦 for any value of 𝑥.
5. Graph Representation
The regression line is drawn through the data points in a scatter plot and represents the best linear
relationship between variables.
Where
· 𝑦 𝑖= actual value
^
· 𝑦 𝑖 = predicted value
· 𝑛 = number of observations
Equation
𝑝
𝐿𝑜𝑠𝑠 = 𝑆𝑆𝐸 + 𝜆 ∣ 𝛽𝑖 ∣
𝑖=1
Where
Characteristics
• Can reduce some coefficients exactly to zero
• Performs automatic feature selection
• Helps reduce model complexity
Equation
𝑝
6. Conclusion
Regularization techniques such as L1 and L2 help prevent overfitting and improve model
performance by controlling the complexity of machine learning models.
Module 2
BAQ
Define Conditional Probability
Definition
Conditional probability is the probability of an event occurring given that another event has already
occurred.
Formula
𝑃(𝐴 ∩ 𝐵)
𝑃(𝐴 ∣ 𝐵) =
𝑃(𝐵)
Where
· 𝑃(𝐴 ∣ 𝐵)= probability of event A given B
· 𝑃(𝐴 ∩ 𝐵)= probability that both A and B occur
· 𝑃(𝐵) = probability of event B
Example
If event A = drawing a heart card and B = drawing a red card, then conditional probability measures
the probability of drawing a heart given that the card is red.
Define Bayes’ Theorem
Definition
Bayes’ Theorem is a fundamental rule in probability theory that describes how to update the
probability of an event based on new evidence.
Formula
𝑃(𝐵 ∣ 𝐴) ⋅ 𝑃(𝐴)
𝑃(𝐴 ∣ 𝐵) =
𝑃(𝐵)
Where
· 𝑃(𝐴 ∣ 𝐵) → Posterior probability (probability of A given B)
· 𝑃(𝐵 ∣ 𝐴)→ Likelihood (probability of B given A)
· 𝑃(𝐴)P(A) → Prior probability (initial probability of A)
· 𝑃(𝐵)P(B) → Evidence or marginal probability
Use
Bayes’ theorem is widely used in machine learning, statistics, and decision making to update
predictions when new data is available.
Key Points
• It assumes that all features are independent of each other given the class label.
• The class with the highest posterior probability is chosen as the predicted class.
• It is widely used for text classification, spam detection, and sentiment analysis.
• Since Naïve Bayes multiplies probabilities, a zero probability can make the entire posterior
probability zero.
• Laplace smoothing solves this by adding a small constant (usually 1) to each frequency count.
• This ensures that no probability becomes zero and the model can make better predictions.
Formula
𝐶𝑜𝑢𝑛𝑡(𝑥 𝑖 ) + 1
𝑃(𝑥 𝑖 ∣ 𝐶) =
𝑇𝑜𝑡𝑎𝑙 𝑖𝑛𝑠𝑡𝑎𝑛𝑐𝑒𝑠 + 𝑘
Where
· 𝑥 𝑖 = feature value
· 𝐶 = class
· 𝑘 = number of possible feature values
This technique makes the Naïve Bayes model more robust when dealing with small datasets or
unseen data.
Key Assumptions
• Feature Independence
Each feature contributes independently to the prediction of the class.
• Distribution of Features
Continuous features are usually assumed to follow a normal (Gaussian) distribution.
• No Missing Data
The model assumes that the dataset does not contain missing values.
These assumptions simplify probability calculations and allow Naïve Bayes to work efficiently even
with high-dimensional data
SAQ
Describe Bayes’ Theorem with formula and meaning of each term
Definition
Bayes’ Theorem is a probability rule used to update the probability of an event based on new
evidence.
Formula
𝑃(𝐵 ∣ 𝐴) ⋅ 𝑃(𝐴)
𝑃(𝐴 ∣ 𝐵) =
𝑃(𝐵)
• P(B|A) – Likelihood
The probability of observing event B when event A is true.
Formula
𝑃(𝐵 ∣ 𝐴) ⋅ 𝑃(𝐴)
𝑃(𝐴 ∣ 𝐵) =
𝑃(𝐵)
Meaning of Each Term
• P(A|B) – Posterior Probability
The probability of event A occurring after observing event B.
• P(B|A) – Likelihood
The probability of observing event B when event A is true.
Features
• Probabilistic Classifier
It calculates the probability of each class and predicts the class with the highest posterior
probability.
• Simple to Implement
The algorithm is easy to understand and implement compared to many complex machine learning
models.
Describe the Assumptions of Naïve Bayes Classifier
Definition
The Naïve Bayes classifier assumes that all features are independent of each other given the class
label.
Assumptions
• Feature Independence
Each feature contributes independently to the prediction of the class label.
• No Missing Values
The dataset should ideally not contain missing values.
These assumptions simplify probability calculations and allow Naïve Bayes to perform efficiently
even with high-dimensional datasets.
Explanation
• The classifier calculates the posterior probability of each class given the feature values.
• It assumes that all features are independent of each other given the class label.
• For categorical data, probabilities are calculated using frequency counts of feature values within
each class.
Where
Example
Suppose we classify a fruit using features:
LAQ
What are Steps in Building a Naïve Bayes Classifier?
1. Introduction
Naïve Bayes is a probabilistic classification algorithm based on Bayes’ theorem.
It predicts the class label of a data point by calculating probabilities of different classes based on
input features.
Example:
9
𝑃(𝑆𝑝𝑎𝑚) =
14
Step 4: Calculate Likelihood Probabilities
Determine the probability of each feature given the class.
𝑃(𝑥 𝑖 ∣ 𝐶)
Example:
Probability that the word “free” appears in spam emails.
𝑃(𝑋 ∣ 𝐶) ⋅ 𝑃(𝐶)
𝑃(𝐶 ∣ 𝑋) =
𝑃(𝑋)
3. Applications
Naïve Bayes is widely used in:
Where
3. Naïve Assumption
Naïve Bayes assumes that all features are independent given the class label.
4. Working Steps
𝑃(𝑥 𝑖 ∣ 𝐶)
This is computed using frequency counts for categorical variables.
5. Example
Dataset:
Naïve Bayes calculates probabilities for Apple and Orange, then predicts the class with higher
probability.
6. Applications
· Spam email filtering
· Text classification
· Sentiment analysis
· Medical diagnosis
Where
3. Prior Probability
Definition
Prior probability is the probability of an event before observing new data or evidence.
Formula
𝑃(𝐴)
Example
Suppose in a population 1% of people have a disease.
𝑃(𝐷𝑖𝑠𝑒𝑎𝑠𝑒) = 0.01
4. Posterior Probability
Definition
Posterior probability is the updated probability of an event after considering new evidence.
Formula
𝑃(𝐴 ∣ 𝐵)
Example
If a person tests positive for the disease, Bayes’ theorem is used to calculate the updated
probability that the person actually has the disease.
6. Applications
Prior and posterior probabilities are widely used in:
Example:
Predicting disease probability based on age or blood pressure.
Example:
Spam detection using word frequency in emails.
• Sentiment analysis
• Document classification
• Medical diagnosis
6. Conclusion
Naïve Bayes classifier is a simple, fast, and efficient machine learning algorithm widely used for
classification tasks, especially with large text datasets.
Module 3
BAQ
What is hyperplane in SVM?
Definition
A hyperplane in Support Vector Machine (SVM) is a decision boundary that separates data points
of different classes in the feature space.
Key Points
• It divides the dataset into two classes such as +1 and −1.
• SVM chooses the hyperplane that maximizes the margin between the two classes.
Equation of Hyperplane
𝑤𝑇 𝑥 + 𝑏 = 0
Where
· 𝑤 = weight vector
· 𝑥 = feature vector
· 𝑏 = bias term
The hyperplane separates data points into different classes based on the sign of the equation.
Key Points
• Slack variables are used in soft margin SVM.
• They allow some data points to lie inside the margin or be misclassified.
• The value of slack variable indicates how much a data point violates the margin constraint.
Interpretation
· 𝜉 𝑖 = 0 → correctly classified and outside margin
· 0 < 𝜉 𝑖 ≤ 1→ inside margin but correctly classified
· 𝜉 𝑖 > 1→ misclassified point
Key Points
• SVM tries to maximize the margin between two classes.
• The nearest data points that define the margin are called support vectors.
Margin Formula
2
𝑀𝑎𝑟𝑔𝑖𝑛 =
∣∣ 𝑤 ∣∣
Where
· 𝑤w = weight vector
Key Points
• Kernel functions compute the similarity between data points without explicitly transforming them
into higher dimensions.
𝐾(𝑥,𝑧) = 𝑥 ⋅ 𝑧
• Polynomial Kernel
𝐾(𝑥,𝑧) = (𝑥 ⋅ 𝑧 + 𝑐) 𝑑
• Sigmoid Kernel
These kernels allow SVM to model complex decision boundaries in machine learning problems.
SAQ
Differentiate Hard Margin SVM and Soft Margin SVM.
Short Conclusion
Hard margin works only for clean datasets, while soft margin is more practical for real-world noisy
data.
Explanation
• In many real-world problems, data cannot be separated using a straight line or plane.
• The kernel trick maps the data into a higher-dimensional feature space where a linear hyperplane
can separate the classes.
• Instead of explicitly transforming the data, a kernel function computes the dot product in the
higher-dimensional space directly.
• This reduces computational complexity and allows SVM to handle complex nonlinear patterns.
Kernel Function
A kernel function calculates similarity between two data points:
Where
𝐾(𝑥,𝑧) = 𝑥 ⋅ 𝑧
• Polynomial Kernel
𝐾(𝑥,𝑧) = (𝑥 ⋅ 𝑧 + 𝑐) 𝑑
Conclusion
The kernel trick enables SVM to solve complex nonlinear classification problems efficiently without
explicitly computing higher-dimensional transformations.
Conclusion
Linear SVM is efficient for simple separable datasets, whereas non-linear SVM uses kernel
functions to classify complex data patterns
Applications
• Text Classification
Used in spam detection and sentiment analysis where SVM classifies text documents based on
features like word frequency.
• Image Recognition
Used in object detection and face recognition by analyzing pixel features.
• Bioinformatics
Applied in gene classification and protein structure prediction using high-dimensional biological
data.
• Medical Diagnosis
Helps detect diseases such as cancer by analyzing medical images and patient data.
• Anomaly Detection
One-class SVM can detect unusual patterns in cybersecurity and manufacturing systems.
Conclusion
SVM is widely used in real-world applications because it performs well with high-dimensional data
and complex classification problems.
𝑦 𝑖 (𝑤 ⋅ 𝑥 𝑖 + 𝑏) ≥ 1
Where
· 𝑤= weight vector
· 𝑥 𝑖 = feature vector
· 𝑏 = bias term
· 𝑦 𝑖 = class label (+1 or −1)
The goal is to minimize the weight vector magnitude, which maximizes the margin.
· 𝜉 𝑖 = slack variables
· 𝐶 = regularization parameter controlling penalty for errors
Conclusion
The SVM objective function ensures that the classifier finds the widest possible margin while
allowing minimal classification errors.
LAQ
Explain Support Vector Machine (SVM) with diagram.
1. Introduction
Support Vector Machine (SVM) is a supervised machine learning algorithm used for classification,
regression, and anomaly detection.
The main idea of SVM is to find an optimal hyperplane that separates two classes with the
maximum margin.
2. Basic Concept
SVM separates data points into two classes:
Hyperplane equation:
𝑤𝑇 𝑥 + 𝑏 = 0
Where
· 𝑤 = weight vector
· 𝑥 = feature vector
· 𝑏 = bias term
1. Hyperplane
A decision boundary that separates different classes in feature space.
Example:
· In 2D → line
· In 3D → plane
· In higher dimensions → hyperplane.
2. Support Vectors
Support vectors are data points closest to the hyperplane.
They determine the position of the hyperplane and define the margin.
3. Margin
Margin is the distance between the hyperplane and the nearest data points (support vectors).
Margin formula:
2
𝑀𝑎𝑟𝑔𝑖𝑛 =
∣∣ 𝑤 ∣∣
4. Types of SVM
Linear SVM
Used when data is linearly separable.
Non-linear SVM
Used when data is not linearly separable, using kernel functions.
5. Kernel Trick
When data cannot be separated by a straight line, SVM uses kernel functions to transform data into
a higher-dimensional space.
Common kernels:
· Linear kernel
· Polynomial kernel
· RBF kernel
· Sigmoid kernel
6. Applications of SVM
· Text classification
· Image recognition
· Medical diagnosis
· Fraud detection
· Bioinformatics
7. Conclusion
SVM is a powerful machine learning algorithm that maximizes the margin between classes and
provides good generalization performance, especially for high-dimensional datasets.
The kernel function maps data into a higher-dimensional feature space, allowing SVM to find a
linear decision boundary for nonlinear data.
Where
1. Linear Kernel
Formula:
𝐾(𝑥,𝑧) = 𝑥 ⋅ 𝑧
2. Polynomial Kernel
Formula:
𝐾(𝑥,𝑧) = (𝑥 ⋅ 𝑧 + 𝑐) 𝑑
Where
· 𝑑 = degree of polynomial
· 𝑐 = constant
• Captures feature interactions.
• Used for image processing and pattern recognition.
Where
· 𝛾 = kernel parameter
4. Sigmoid Kernel
Formula:
5. Conclusion
Kernel functions enable SVM to classify complex datasets by transforming them into higher-
dimensional spaces, making SVM a powerful tool for nonlinear machine learning problems.
Depending on the nature of the data, SVM can be implemented using Hard Margin or Soft Margin
approaches.
Definition
Hard Margin SVM is used when the dataset is perfectly linearly separable, meaning there are no
misclassified data points.
Objective Function
1
𝑚𝑖𝑛 ∣∣ 𝑤 ∣ ∣ 2
2
Subject to:
𝑦 𝑖 (𝑤 ⋅ 𝑥 𝑖 + 𝑏) ≥ 1
Where
· 𝑤 = weight vector
· 𝑥 𝑖 = input vector
· 𝑏 = bias
· 𝑦 𝑖 = class label (+1 or −1)
Characteristics
• Assumes perfect separation of data
• No misclassification allowed
Definition
Soft Margin SVM is used when data is not perfectly separable. It allows some misclassification using
slack variables.
Objective Function
1
𝑚𝑖𝑛 ∣∣ 𝑤 ∣ ∣ 2 + 𝐶∑𝜉 𝑖
2
Subject to:
𝑦 𝑖 (𝑤 ⋅ 𝑥 𝑖 + 𝑏) ≥ 1−𝜉 𝑖
Where
· 𝜉 𝑖 = slack variable
· 𝐶 = regularization parameter controlling penalty for errors.
Characteristics
• Allows some classification errors
5. Conclusion
Hard margin SVM works well for clean datasets, while soft margin SVM is more suitable for real-
world noisy datasets where some classification errors are allowed.
Module No 4
BAQ
What is the purpose of using decision trees in machine learning?
Definition
A decision tree is a supervised machine learning model that represents decisions and outcomes in a
tree-like structure.
Example
For example, a decision tree can predict whether a person will buy a product based on age,
income, and spending habits.
Decision trees are widely used because they are easy to understand and visualize.
Conclusion
Decision trees are simple models, while Random Forest improves accuracy by combining multiple
decision trees using bagging.
Explanation
Nodes form the structure of the tree where each branch represents a decision rule and each leaf
gives the final outcome.
Example
A very deep decision tree may perfectly fit training data but perform poorly on new data.
Pruning cuts weak branches to make the tree more reliable.
SAQ
• The algorithm selects the best feature for splitting based on criteria such as Gini impurity,
entropy, or information gain.
• The dataset is divided into subsets according to the selected feature condition.
• The same process is repeated recursively for each subset until the data becomes pure or another
stopping condition is met.
Example
In a customer prediction problem, the first split might be Age, followed by Income, then Spending
behavior, creating a tree-like structure of decisions.
Conclusion
Both Gini impurity and entropy are measures used to select the best feature for splitting in
decision trees.
• A feature with higher information gain is preferred for splitting because it produces more
homogeneous subsets.
• It helps the decision tree select the most informative feature at each node.
Formula
𝑛 𝑐ℎ𝑖𝑙𝑑
𝐼𝐺 = 𝐻(𝑝𝑎𝑟𝑒𝑛𝑡)−∑ 𝐻(𝑐ℎ𝑖𝑙𝑑)
𝑛
Where
Example
If splitting a dataset using Age significantly reduces entropy compared to other features, then Age
will be selected as the best split.
Explanation
• Decision trees tend to keep splitting until the data becomes perfectly classified, which may
create very deep trees.
• Such trees capture noise and irregular patterns in the training data.
• As a result, the model performs very well on training data but poorly on unseen test data.
Prevention Methods
• Pruning the tree to remove unnecessary branches.
These methods help create simpler and more generalizable decision tree models.
Types of Pruning
2️. Post-Pruning
• The decision tree is first fully grown, then unnecessary branches are removed.
Conclusion
Pruning simplifies the decision tree and helps create a more accurate and generalizable model.
LAQ
Explain the Decision Tree model with diagram.
1. Introduction
A Decision Tree is a supervised machine learning algorithm used for classification and regression
problems.
It represents decisions and their possible outcomes in a tree-like structure, where nodes represent
feature tests and leaves represent predictions.
4️. Branches
Branches represent the outcomes of a decision rule.
Entropy
𝐸𝑛𝑡𝑟𝑜𝑝𝑦 = −∑𝑝 𝑖 𝑙𝑜𝑔 2 𝑝 𝑖
Information Gain
𝑛 𝑐ℎ𝑖𝑙𝑑
𝐼𝐺 = 𝐻(𝑝𝑎𝑟𝑒𝑛𝑡)−∑ 𝐻(𝑐ℎ𝑖𝑙𝑑)
𝑛
Gini Impurity
𝐺𝑖𝑛𝑖 = 1−∑𝑝2𝑖
These measures help determine the best feature to split the data.
5. Example Diagram
Example: Predict whether a person will buy a product.
Age
/ \
Young Old
/ \
Income Income
/ \ / \
Buy Not Buy Buy Not Buy
Each branch represents a decision rule, and the leaf nodes represent the final prediction.
7. Conclusion
Decision trees are powerful machine learning models that break down complex decisions into
simple hierarchical rules, making them easy to interpret and useful in many applications.
Explain Gini impurity, entropy and information gain used in decision trees.
Answer
1. Introduction
In decision trees, splitting criteria are used to determine the best feature for dividing the dataset
into subsets.
The most common measures used are Gini Impurity, Entropy, and Information Gain. These
measures help create pure and homogeneous nodes.
2. Gini Impurity
Definition
Gini impurity measures the probability of incorrectly classifying a randomly chosen element in a
dataset.
Formula
𝐺𝑖𝑛𝑖 = 1−∑𝑝2𝑖
Where
· 𝑝 𝑖 = probability of class 𝑖.
Explanation
• A Gini value of 0 indicates a pure node (all elements belong to one class).
3. Entropy
Definition
Entropy measures the amount of uncertainty or randomness in a dataset.
Formula
𝐸𝑛𝑡𝑟𝑜𝑝𝑦 = −∑𝑝 𝑖 𝑙𝑜𝑔 2 𝑝 𝑖
Where
· 𝑝 𝑖 = probability of class 𝑖.
Explanation
• Entropy = 0 means the node is pure.
4. Information Gain
Definition
Information Gain measures the reduction in entropy after splitting a dataset using a particular
feature.
Formula
𝑛 𝑐ℎ𝑖𝑙𝑑
𝐼𝐺 = 𝐻(𝑝𝑎𝑟𝑒𝑛𝑡)−∑ 𝐻(𝑐ℎ𝑖𝑙𝑑)
𝑛
Where
Explanation
• A feature with higher information gain is chosen for splitting.
5. Example
Suppose a dataset contains two classes: Yes and No.
If splitting by Age reduces entropy significantly compared to other features, then Age will be
selected as the best split.
6. Conclusion
Gini impurity, entropy, and information gain are essential metrics that help decision tree algorithms
select the best feature for splitting and build efficient predictive models.
It uses techniques such as bagging (bootstrap sampling) and feature randomness to create a
collection of diverse decision trees.
· Fraud detection
· Medical diagnosis
· Recommendation systems
· Financial risk analysis
6. Conclusion
Random Forest improves the performance of decision trees by combining multiple trees to produce
more accurate and stable predictions.
Module 5
BAQ
Define clustering in machine learning.
Clustering is an unsupervised machine learning technique that groups similar data points into
clusters such that objects within the same cluster are more similar to each other than to those in
other clusters.
Clustering Classification
It is an unsupervised learning technique. It is a supervised learning technique.
Works with unlabeled data. Works with labeled training data.
Groups data points based on similarity or
Assigns data to predefined classes.
distance.
Used for discovering hidden patterns in data. Used for predicting labels for new data.
Example: K-means, DBSCAN, Hierarchical Example: Decision Tree, SVM, Neural
clustering. Networks.
Conclusion
Clustering discovers unknown groups in data, while classification predicts known categories using
labeled datasets.
Key Points
• Each cluster is represented by a centroid (mean of points).
• It groups similar data points so that points in the same cluster are close to each other.
Example
K-means is widely used for customer segmentation, image compression, and pattern recognition.
Key Points
• It forms clusters where points are densely packed together.
• Unlike K-means, DBSCAN does not require specifying the number of clusters in advance.
Parameters
• ε (epsilon) → neighborhood radius
SAQ
4️. Iteration
Repeat the assignment and update steps until centroids stop changing significantly or the
algorithm converges.
Objective Function
K-Means aims to minimize the Within-Cluster Sum of Squares (WCSS).
𝑘
𝑊𝐶𝑆𝑆 = ∑ ∣ 𝑥 𝑖 −𝜇 𝑗 ∣ ∣ 2
𝑗=1 𝑥𝑖∈𝐶𝑗
Where
· 𝑥 𝑖 = data point
· 𝜇 𝑗 = centroid of cluster 𝐶 𝑗
Applications
• Customer segmentation
• Image compression
• Pattern recognition
• Anomaly detection
Conclusion
Different clustering methods are used depending on the dataset structure, noise level, and cluster
shape.
• The process continues until each data point becomes its own cluster.
Dendrogram
Hierarchical clustering results are often represented using a dendrogram, which is a tree diagram
showing how clusters merge or split at different distances.
Applications
• Document clustering
• Biological taxonomy
• Image segmentation
• Gene analysis
Key Concepts
• Core Point
A point that has at least MinPts neighbors within radius ε (epsilon).
• Border Point
A point that lies within ε of a core point but does not have enough neighbors to be a core point.
• Noise Point
A point that is not reachable from any core point and considered an outlier.
Parameters
• ε (epsilon) → radius of neighborhood
Advantages
• Detects clusters of arbitrary shapes
Explanation
For each data point 𝑖i:
• 𝑎(𝑖) → average distance between point 𝑖i and all other points in the same cluster.
• 𝑏(𝑖) → average distance between point 𝑖i and points in the nearest neighboring cluster.
Formula
𝑏(𝑖)−𝑎(𝑖)
𝑠(𝑖) =
𝑚𝑎𝑥 ( 𝑎(𝑖),𝑏(𝑖))
Where
Use
• Evaluates quality of clustering
• Helps determine the optimal number of clusters (K) in algorithms like K-Means.
LAQ
Answer
1. Introduction
K-Means clustering is an unsupervised machine learning algorithm used to partition a dataset into K
clusters based on similarity.
2. Objective Function
K-Means aims to minimize the total squared distance between data points and their cluster
centroids.
𝑘
𝑊𝐶𝑆𝑆 = ∑ ∣ 𝑥 𝑖 −𝜇 𝑗 ∣ ∣ 2
𝑗=1 𝑥𝑖∈𝐶𝑗
Where
· 𝑥 𝑖 = data point
· 𝜇 𝑗 = centroid of cluster 𝐶 𝑗
· 𝑘 = number of clusters.
Step 4: Repeat
Repeat the assignment and update steps until cluster assignments stop changing or convergence is
reached.
4. Example
Dataset (1D points):
1, 2, 3, 9, 10
Let 𝐾 = 2
Iteration 1
Initial centroids: 2 and 9
Cluster assignments:
Cluster 1 → 1, 2, 3
Cluster 2 → 9, 10
New centroids:
Iteration 2
Assignments remain the same → algorithm converges.
Final clusters:
Cluster 1 → {1, 2, 3}
Cluster 2 → {9, 10}
5. Advantages of K-Means
• Simple and easy to implement
• Works efficiently on large datasets
• Computationally fast.
6. Disadvantages
• Requires specifying number of clusters (K) beforehand
7. Applications
• Customer segmentation
• Image compression
• Pattern recognition
• Recommendation systems.
Explain DBSCAN clustering algorithm with concepts (core, border, noise points).
1. Introduction
DBSCAN (Density-Based Spatial Clustering of Applications with Noise) is an unsupervised clustering
algorithm that groups data points based on density of points in a region.
It identifies clusters as dense regions separated by sparse regions, and points in sparse regions are
treated as noise or outliers.
2. Key Parameters
1️. ε (Epsilon)
Defines the radius of the neighborhood around a point.
2️. MinPts
Minimum number of points required inside the ε-radius to form a dense region.
3. Important Concepts
Core Point
A data point that has at least MinPts points within its ε-neighborhood.
Border Point
A point that lies within ε distance of a core point but does not have enough neighbors to be a core
point itself.
Noise Point
A point that does not belong to any cluster and lies in a low-density region.
5. Advantages
• Can detect clusters of arbitrary shapes
6. Disadvantages
• Sensitive to parameter selection (ε and MinPts)
7. Applications
• Geospatial data analysis
• Anomaly detection
• Image segmentation
1. Introduction
Hierarchical clustering is a clustering method that builds a hierarchy (tree-like structure) of
clusters, showing relationships between data points at different levels.
Unlike K-means, hierarchical clustering does not require specifying the number of clusters in
advance.
• The process continues until each point forms its own cluster.
3. Dendrogram
A dendrogram is a tree diagram used to visualize the hierarchy of clusters.
Characteristics:
5. Advantages
• No need to specify number of clusters beforehand
6. Disadvantages
• Computationally expensive for large datasets
7. Applications
• Biological taxonomy
• Document clustering
• Image segmentation
Module 6
BAQ
Define dimensionality reduction.
Dimensionality reduction is the process of reducing the number of features in a dataset while
preserving as much important information as possible, transforming high-dimensional data into a
lower-dimensional representation.
• The distance between data points becomes almost similar, making similarity-based algorithms
ineffective.
• Many machine learning algorithms require exponentially more data to perform well.
Example
Algorithms such as k-NN, clustering, and SVM perform poorly when the number of features is
extremely high.
Conclusion
Feature selection chooses important existing variables, while feature extraction creates new
variables representing the original data in a lower-dimensional space.
Key Points
• Principal components are linear combinations of the original features.
• PC1 (first principal component) captures the maximum variance in the data.
• PC2 captures the next highest variance and is perpendicular (orthogonal) to PC1.
• PCA helps reduce dimensionality while preserving the most important information.
Examples:
· Correlation coefficient
· Chi-square test
· Mutual information
Examples:
· Forward selection
· Backward elimination
· Recursive Feature Elimination (RFE)
Examples:
· Lasso regression
· Decision trees
· Random forest feature importance.
Conclusion
Feature selection reduces model complexity, training time, and overfitting, while improving
interpretability.
Mathematical Representation
𝐴𝑣 = 𝜆𝑣
Where:
· A → square matrix
· v → eigenvector
· λ (lambda) → eigenvalue
This equation means when matrix A multiplies vector v, the result is the same vector scaled by λ.
Key Points
• Eigenvectors represent important directions in the data.
• Eigenvalues and eigenvectors are widely used in Principal Component Analysis (PCA) for
dimensionality reduction.
Example Concept
When a matrix transformation acts on most vectors, their direction changes, but eigenvectors only
change in magnitude (stretch or shrink) without changing direction
Covariance Formula
1 ˉ ˉ
𝑠 𝑥𝑦 = ∑(𝑥 𝑖 −𝑥(𝑦 𝑖 −𝑦)
𝑛−1
Where:
· 𝑥 𝑖 ,𝑦 𝑖 = data values
ˉ ˉ
· 𝑥𝑦 = mean of variables
· 𝑛 = number of observations.
X Y
X Var(X) Cov(X,Y)
Y Cov(Y,X) Var(Y)
Key points:
Importance
• Helps understand relationships between variables.
Steps of PCA
1. Standardize the data so that each feature has mean 0 and standard deviation 1.
2. Compute the covariance matrix to measure relationships between features.
3. Calculate eigenvalues and eigenvectors of the covariance matrix.
4. Select top k eigenvectors corresponding to largest eigenvalues.
5. Project the data onto these principal components to obtain reduced dimensional data.
Advantages
• Reduces number of features
Explanation
• The scree plot displays principal components on the X-axis and eigenvalues (variance explained)
on the Y-axis.
Elbow Rule
• The point where the curve starts to flatten sharply is called the elbow point.
• Components before the elbow are retained because they capture most of the important variance.
• Components after the elbow are usually discarded since they represent less useful information or
noise.
Importance
• Helps determine the number of components to keep in PCA.
LAQ
Explain Principal Component Analysis (PCA) with steps.
1. Introduction
Principal Component Analysis (PCA) is a linear dimensionality reduction technique used to
transform a dataset with many correlated variables into a smaller set of uncorrelated variables
called principal components, while preserving maximum variance in the data.
The goal of PCA is to reduce dimensionality while retaining the most important information.
2. Concept of PCA
• PCA creates new axes called principal components.
• They are orthogonal (perpendicular) to each other, meaning they are uncorrelated.
• The first component captures maximum variance, followed by the second component, and so on.
3. Steps of PCA
Where
· 𝜇 𝑗= mean of feature
· 𝜎 𝑗= standard deviation.
Step 2: Compute Covariance Matrix
The covariance matrix measures the relationship between features.
𝐴𝑣 = 𝜆𝑣
Where
· 𝑣= eigenvector
· 𝜆 = eigenvalue.
4. Advantages of PCA
• Reduces number of features
5. Applications
• Image compression
• Face recognition
• Data visualization
The curse of dimensionality is a phenomenon that occurs when the number of features
(dimensions) in a dataset becomes very large. As the dimensionality increases, the data becomes
sparse and machine learning algorithms struggle to learn meaningful patterns.
Example:
To maintain the same data density:
· 1D → about 10 points
· 2D → about 100 points
· 3D → about 1000 points
· 10D → about 10¹⁰ points (very large).
4. Overfitting
Models may learn noise instead of real patterns, resulting in poor performance on new data.
These algorithms rely on distance calculations which become unreliable in high dimensions.
5. Solution
The main solution is Dimensionality Reduction techniques, such as:
These techniques reduce the number of features while retaining important information.
6. Conclusion
The curse of dimensionality is a major challenge in machine learning that affects model
performance, computation, and interpretability. Dimensionality reduction methods help overcome
this problem by simplifying high-dimensional data.
Examples:
· Chi-square test
· Correlation coefficient
· Mutual information
· ANOVA test
Advantages:
· Fast
· Scalable to large datasets.
Disadvantage:
Examples:
· Forward selection
· Backward elimination
· Recursive Feature Elimination (RFE)
Advantages:
Disadvantages:
· Computationally expensive.
Examples:
· Lasso Regression
· Decision Trees
· Random Forest feature importance.
Advantages:
· Efficient
· Combines benefits of filter and wrapper methods.
4. Conclusion
Feature selection improves machine learning performance by removing irrelevant features and
keeping only the most informative variables.
Mathematically:
𝑋 = 𝑈𝛴𝑉 𝑇
Where:
U Matrix
Represents the row space (samples).
Σ Matrix
Contains singular values, which represent the importance of each component.
Vᵀ Matrix
Represents the feature space directions.
• We keep only the largest singular values and discard smaller ones.
• This removes noise and redundant information while preserving important structure.
4. Applications
• Image compression
• Recommender systems
• Natural language processing
• Latent semantic analysis.
5. Conclusion
SVD is a powerful technique for reducing dimensionality, extracting important patterns, and
improving computational efficiency in machine learning.