ML Note
ML Note
Write about
some applications of machine learning.
Ans: Machine from Learning is the field of study that enables a system
experience without being explicitly programmed.
a. Problems for which existing solutions require a lot of hand-tuning or
long lists of rules: a Machine Learning algorithm can often simplify
code and perform better.
b. Complex problems for which there is no good solution at all using a
traditional approach: the best Machine Learning techniques can find a
solution.
Fluctuating environments: a Machine Learning system can adapt to new data.
• Getting insights about complex problems and large amounts of
data
Applications of Machine Learning
1. Spam Detection – Identifying spam emails
2. Recommendation Systems – Netflix, YouTube, Amazon
3. Image & Face Recognition – Security systems
4. Speech Recognition – Google Assistant, Siri
5. Medical Diagnosis – Disease prediction
6. Fraud Detection – Banking and credit card systems
7. Autonomous Vehicles – Self-driving cars
Wrapper Method
Definition:
The wrapper method is a feature selection technique that selects features by
training and evaluating a machine learning model on different subsets of
features and choosing the subset that gives the best performance.
Embedded Method
Definition:
The embedded method is a feature selection approach where feature selection
is performed during the model training process, and the model itself decides
which features are important.
Entropy Formula
Entropy=− p log 2 p−q log 2 q
Information Gain
Information Gain =1−Entropy
Detecting Outliers
Box plot
Histogram
Scatter plot
Handling Outliers
Drop outlier records: Remove abnormal data points
Cap outlier data: Limit extreme values to a threshold
Assign a new value: Replace with mean or predicted value
Transformation: Apply functions (log, sqrt) to reduce impact
Missing Values
Missing values occur when some attribute values are not recorded.
Reasons:
Data not collected
Attribute not applicable
Handling Missing Values
Remove data records
Estimate values (mean/median/mode/prediction)
Ignore during analysis
Replace with probable values
1️⃣ Noise
Noise refers to unwanted modification or disturbance in the original data values.
2️⃣ Outliers
Outliers are data objects whose values are significantly different from most other data
objects in a dataset.
3️⃣ Missing Values
Missing values occur when some attribute values are not recorded.
4️⃣ Duplicate or Redundant Data
Duplicate data refers to repeated records in a dataset.
How to Handle Outliers
Outliers can be handled using several techniques, depending on the nature of the data and the
analysis requirements.
1. Drop the outlier records:
If outliers occur due to data entry or measurement errors, removing those records helps
prevent them from skewing or biasing the analysis results.
2. Cap the outlier values:
In cases where extreme values behave similarly to normal values, outliers can be capped
at a certain threshold to reduce their influence on the analysis.
3. Assign a new value (Imputation):
When outliers are caused by incorrect data, they can be replaced with estimated values
such as the mean, median, or values predicted using regression techniques.
4. Apply data transformation:
Transforming the data using techniques like scaling or logarithmic transformation can
reduce the impact of outliers without removing data.
Answers how many, how much, or how often Answers why, how, or what
Examples: distance, height, weight, time, cost, Examples: gender, nationality, marital status, color,
number of visitors education level
Has a finite or countably infinite number of Can take any real value within a given range
values
Values are distinct and separate Values are continuous without gaps
Binary Classification
Definition:
Binary classification is a type of classification where each instance is
assigned to one of two possible classes.
Multiclass Classification
Definition:
Multiclass classification is a type of classification where each instance is
assigned to one of three or more classes.
Multi-Label Classification
Definition:
Multi-label classification is a type of classification where multiple class
labels can be assigned to a single instance at the same time.
Regression
Definition:
Regression is a supervised learning technique in which the output (target)
variable is a continuous numerical value, such as price, weight, or score.
Linear Regression
Definition:
Linear regression is a regression technique that models the relationship
between input variables and a continuous output using a linear (straight-
line) equation.
Polynomial Regression
Definition:
Polynomial regression is a regression technique that models the relationship
between variables using a polynomial equation to handle non-linear data.
Supervised Learning
Definition:
Supervised learning is a machine learning approach in which the model is
trained using labeled data, meaning each input has a corresponding output.
Unsupervised Learning
Definition:
Unsupervised learning is a machine learning approach in which the model is
trained using unlabeled data and discovers patterns or structures on its own.
Clustering
Definition:
Clustering is an unsupervised learning technique that groups data objects
such that objects within the same cluster are similar and objects in
different clusters are dissimilar.
4. Density-Based Clusters
In density-based clustering,
a cluster is a dense region of data points separated by low-density regions.
👉 Features:
Limitations
Computationally expensive
Sensitive to noise and outliers (especially single linkage)
Some methods may break large clusters (complete linkage)
(a) What is Zero frequency problem in Naïve Bayes Classifier? How to handle
with Zero frequency problem? Explain with an example. 2+3
Where:
Count = frequency of the feature
Total = total number of features in that class
V = number of possible feature values
This ensures that no probability becomes zero.
Example
Suppose we classify emails as Spam or Not Spam.
Training data:
Email Word = "Offer"
Type
Spam 0 times
Without smoothing:
P(Offer ∣Spam)=0
So, the Spam class will always get probability zero if the word “Offer” appears.
With Laplace smoothing:
0+1
P(Offer ∣Spam )=
Total+V
The class label of a new data point in kNN is decided using the following
methods:
Majority Voting:
The new data point is assigned the class that appears most
frequently among its k nearest neighbors.
Distance-weighted Voting:
The votes of neighbors are weighted based on their distance.
Closer neighbors have more influence using weight:
1
w= 2 where d is the distance.
d
So, nearer points contribute more to the final decision.
c) Write the working principle of the support vector machine (SVM)
algorithm. How kernel function related to support vector machine?
(c) Why does Support Vector Machine (SVM) select the hyperplane for which
the margin is maximum? What are the kernel tricks in SVM?
c) How does Support Vector Machines (SVMs) work? What are the kernel
tricks in SVM?
(b) How does Support Vector Machines (SVMs) work? How to identify the
right hyper-plane in SVM?
Cross-validation techniques are used to evaluate the performance of a model on unseen data
and to reduce overfitting by ensuring better generalization.
✅ 1. Holdout Method: The holdout method is a model validation technique in which the dataset
is divided into two disjoint sets: a training set and a test set. The model is trained on the training
set and evaluated on the test set.
✅ 2. Random Subsampling Method: Random subsampling is an extension of the holdout
method where the dataset is randomly split into training and test sets multiple times. The model
is trained and tested in each iteration, and the final performance is obtained by averaging the
results over all iterations.
✅ 3. k-Fold Cross Validation: In k-fold cross validation, the dataset is divided into k equal-sized
subsets (folds). The model is trained k times, each time using k−1 folds as the training set and the
remaining one fold as the test set. The final performance is the average of the k evaluation
results.
✅ 4. Leave-One-Out Cross Validation (LOOCV): Leave-One-Out Cross Validation is a special
case of k-fold cross validation where k is equal to the number of data samples. In each iteration,
one sample is used as the test set and the remaining samples are used for training. The final result
is obtained by averaging all iterations.
Cross-validation techniques are used to evaluate the performance of a model on unseen data
and to reduce overfitting by ensuring better generalization.
Q.6 (a) What is regression analysis? Why do you need to use regression analysis?
Regression Analysis is a supervised learning technique used to predict a continuous (real-valued)
output by modeling the relationship between a dependent (target) variable and one or more
independent (predictor) variables.
Regression analysis is used for the following purposes:
1. Prediction:
It is used to predict future or unknown values, such as predicting house prices or student
marks.
2. Understanding Relationships:
It helps to understand how one variable affects another variable.
3. Trend Analysis:
It is used to analyze trends and patterns in data over time.
4. Decision Making:
It supports decision-making in fields like business, engineering, and science.
5. Modeling Data:
It is used to create mathematical models of real-world situations.
6. 🔹 Case 1: Noise (small disturbance)
7. Now data becomes:
70, 72, 68, 71, 69, 73, 71.5
8. 👉 That extra 71.5 is just a small variation
✔ It is close to others
✔ It doesn’t break the pattern
9. ➡️This is Noise
10.
(b) What is meant by regression line? How do you find a best-fit regression line?
(b) Regression Line
A regression line is a straight line that represents the relationship between an independent
variable (x) and a dependent variable (y). It is used to predict the value of the dependent
variable based on the independent variable. The equation of a regression line is:
y=mx+c where m is the slope and c is the intercept.
Best-Fit Regression Line
The best-fit regression line is the line that best represents the data points by minimizing the
error between the actual values and predicted values.
How to find the best-fit regression line
1. Use Least Squares Method:
The best-fit line is found by minimizing the sum of squared errors between actual and
predicted values.
2. Calculate slope (m):
n ∑ xy−(∑ x)(∑ y)
m=
n∑ x 2−¿¿
3. Calculate intercept (c):
∑ y−m∑ x
c=
n
4. Form the equation:
Substitute m and c into y=mx+c .
(b) What is meant by regression line? How do you find a best-fit regression line?
(b) Simple Linear Regression
Definition (1 mark):
Simple linear regression is a statistical method used to model the relationship between one
independent variable (x) and one dependent variable (y) using a straight line.
Clustering
Types of Clusters
1. Well-Separated Clusters:
A cluster where all points are closer to each other than to any point outside the
cluster.
2. Center-Based (Partitioned) Clusters:
A cluster where each point is closer to its cluster center (centroid/medoid) than to other
cluster centers.
3. Contiguous (Connectivity-Based) Clusters:
A cluster where points are connected through nearest neighbors (each point is close to
at least one other point in the cluster).
4. Density-Based Clusters:
A cluster is a dense region of points separated by low-density areas; useful for
irregular shapes and handling noise/outliers.
(b) How to update the proximity matrix after merging two closest clusters?
When two clusters are merged, the proximity matrix is updated as follows:
1. Remove the rows and columns of the two merged clusters.
2. Add a new row and column for the new merged cluster.
3. Compute distances between the new cluster and all other clusters using a linkage
method:
o Single Link: minimum distance
o Complete Link: maximum distance
o Average Link: average distance
4. Keep diagonal values as 0.
Ensemble learning is a method where multiple models are combined instead of using just one.
Even if individual models are weak, combining their results gives more accurate and reliable
predictions.
Simple Ensemble Techniques
Ensemble techniques combine multiple models to improve prediction accuracy. The common
simple ensemble methods are:
1. Max Voting
Max voting is mainly used for classification problems.
In this method, multiple models make predictions for the same data.
Each model’s prediction is treated as a vote.
The final prediction is the one that gets the majority vote (mode).
Example:
If 5 models predict ratings: 4, 5, 4, 4, 5 →
The majority prediction is 4, so final output = 4.
2. Averaging
Averaging is used for both regression and classification.
Multiple models make predictions.
The final prediction is the average of all outputs.
Formula:
Final Output = (Sum of all predictions) / (Number of models)
Example:
Predictions: 5, 4, 5, 4, 4
Average = (5 + 4 + 5 + 4 + 4) / 5 = 4.4
3. Weighted Averaging
Weighted averaging is an improved version of averaging.
Each model is assigned a weight based on its importance or performance.
Predictions are multiplied by their weights.
Final output is the weighted sum.
Formula:
Final Output = Σ (Prediction × Weight)
Example:
(5×0.23) + (4×0.23) + (5×0.18) + (4×0.18) + (4×0.18) = 4.41
2. Boosting
Boosting is a sequential technique where each model tries to correct the errors of the previous
model.
Steps:
1. Initially, a base (weak) learner is trained by assigning equal weight to all observations.
2. After training, if there are prediction errors, the misclassified observations are given
higher weight (more importance).
3. A new base learner is trained focusing more on these difficult observations.
4. Steps 2 and 3 are repeated until the model achieves good accuracy or a maximum number
of iterations is reached.
5. Finally, all weak learners are combined to form a strong learner that provides more
accurate predictions.
Key Idea: Focus more on difficult (misclassified) data points.
Example: AdaBoost
Initially, all data points have equal weight.
First model (B1) misclassifies some points.
These misclassified points are given higher weight.
Second model (B2) focuses more on these errors but may misclassify others.
Third model (B3) again adjusts weights and improves accuracy.
Finally, all models (B1, B2, B3) are combined to create a strong model (B4).
3. Stacking
Stacking is an ensemble technique where predictions of multiple models are used to train a new
model.
Multiple base models are trained on the dataset.
Each model makes predictions.
These predictions are used as input features for another model called the meta-model.
The meta-model makes the final prediction.
Key Idea: Learn how to best combine different models.
Advanced Boosting Methods
1. What is GBM?
Gradient Boosting Machine (GBM) is an ensemble learning method where models are built
sequentially, and each new model tries to correct the errors of the previous one using gradient
descent.
2. What is XGBoost?
XGBoost (Extreme Gradient Boosting) is an improved version of GBM. It provides high
performance, regularization, and parallel processing, making it faster and more accurate
3. What is LightGBM?
LightGBM is a boosting algorithm developed by Microsoft. It uses histogram-based learning and
leaf-wise tree growth, making it very fast and memory efficient, especially for large datasets.
4. Advantages of XGBoost and LightGBM
XGBoost:
High accuracy
Handles missing values
Reduces overfitting using regularization
LightGBM:
Faster training speed
Low memory usage
Efficient for large datasets
5. Building Classifiers
GBM, XGBoost, and LightGBM are used to build classification models by:
1. Training the model on data
2. Making predictions
3. Evaluating performance
7. LightGBM vs XGBoost
LightGBM → Faster and better for large datasets
XGBoost → More accurate and better control over overfitting
What is CatBoost?
CatBoost (Categorical Boosting) is a gradient boosting algorithm developed by Yandex. It is specially
designed to handle categorical data efficiently.
Features:
Automatically handles categorical features
Uses ordered boosting to reduce overfitting
Provides high accuracy
Holdout Method
Split data into Training set and Test set
Use k% for training, (100−k)% for testing
Train model on training data, evaluate on test data
Limitations of Holdout
Less data for training
Result depends on how data is split
Single split → may give misleading accuracy
Random Subsampling
Repeat holdout multiple times (k iterations)
Randomly select test set each time
Average accuracy:
k
∑ ac c i
ac c ¿= i=1
k
Some data may not be used
Number of iterations not fixed
Cross Validation (k-fold)
Split data into k folds
For each fold:
o Use 1 fold as test
o Use remaining (k−1) folds as training
Train and evaluate k times
Final result = average of all scores
Variations
Repeated CV → run CV multiple times for better accuracy
Stratified CV → keeps class ratio same (important for imbalanced data)
LOOCV (Leave-One-Out)
Special case: k = N (dataset size)
Each test set has 1 sample
Uses maximum data for training
Very slow, but highly reliable
Generalization means a model’s ability to perform well on new, unseen data, not just the data it
was trained on.
Bias Error
Difference between actual and predicted values due to wrong assumptions
High Bias → Underfitting (model too simple, misses patterns)
Learns training data poorly
Examples:
High Bias → Linear Regression, Logistic Regression
Low Bias → Decision Trees, k-NN, SVM
Variance Error
Error due to sensitivity to small changes in training data
High Variance → Overfitting (model too complex, memorizes data)
Examples:
High Variance → Decision Trees, k-NN, SVM
Low Variance → Linear Regression, Logistic Regression
Bias–Variance Tradeoff
Goal: Low Bias + Low Variance
But reducing one often increases the other
Need a balance to minimize total error
The curse of dimensionality refers to the problem that arises when the number of features
(dimensions) increases in a dataset. As dimensionality increases, the data points become sparse
in the feature space
Adv. & Disadv. of Naïve Bayes Classifier
Advantage
Works surprisingly well
Simple
Handling missing value is easier
Robust to irrelevant attributes
Disadvantage
Can’t handle dependent variables
Suffers from “Zero Frequency” problem
Adv. & Disadv. of SVM
Advantage
SVM offers very high accuracy compared to other classifiers such as logistic
regression, decision trees, and Naïve Bayes.
SVM works well with a clear margin of separation and with high dimensional
space.
It uses less memory because it uses a subset of training points in the decision
phase.
Disadvantage
Required training time is higher for large datasets.
It works poorly with overlapping classes, e.g. when the data set has more noise
It is sensitive to the type of kernel used
Advantages of Random Forests
Random forests is considered as a highly accurate and robust method because of the
number of decision trees participating in
the process.
It likely does not suffer from the overfitting problem because it creates multiple trees
on random subsets, takes the average or most votes of the predictions of the trees, which
cancel out the biases. The randomness and voting or averaging mechanisms in random
forests elegantly solve the overfitting problem.
It can handle missing data.
It can be used in both classification and regression problems.
Disadvantages of Random Forests
Random forests is slow because it builds multiple decision trees and makes the final
prediction by combining the predictions of each individual tree.
The model is difficult to interpret compared to a decision tree, where you can easily
make a decision by following the path in the tree
x=(x 1 , x 2 , ... , x n )
👉 Final output:
o j=ϕ ( ∑ x i wij +θ j )
Multi-Layer Form
x l+1=ϕ (W l xl +θ l)
👉 Where:
W l = weight matrix
x l= input of layer
θl = bias
ϕ = activation function