Introduction to Machine Learning Concepts
Introduction to Machine Learning Concepts
=======================
Machine Learning (ML) is an automated learning with little or no human intervention. It involves programming
computers so that they learn from the available inputs. The main purpose of machine learning is to explore
and construct algorithms that can learn from the previous data and make predictions on new input data.
The input data to a machine learning system can be numerical, textual, audio, visual, or multimedia. The
corresponding output data of the system can be a floating-point number, for instance, the velocity of a rocket,
an integer representing a category or a class, for example, a pigeon or a sunflower from image recognition.
Supervised learning
==================== is a type of machine learning where the model is trained using labeled data that
is, data that already has the correct output provided. The goal is to learn a function that maps inputs to
desired outputs. For example, if we want to predict house prices, we provide the algorithm with data about
houses (like size, location, number of rooms) along with their actual prices. The model then learns the
relationship between features and prices and can make predictions on new, unseen data.
There are two main types of supervised learning: Regression and Classification. Regression is used when
the output is a continuous value (e.g., predicting temperature or price), while Classification is used when the
output belongs to categories (e.g., spam or not-spam emails, positive or negative sentiment). Algorithms like
Logistic Regression, Neural Networks, Support Vector Machines (SVM), and Naive Bayes are commonly
Unsupervised learning
====================== is a machine learning approach where the model is trained on unlabeled data
meaning the data doesnt have predefined outputs or categories. The goal is to explore the structure of the
data, discover hidden patterns, group similar data points, or detect anomalies. Unlike supervised learning,
A common use of unsupervised learning is clustering, where the algorithm groups data based on similarities
like segmenting customers based on shopping behavior or identifying fraud by detecting unusual patterns.
Popular algorithms include K-Means clustering, Hierarchical clustering, and sometimes Random Forests (for
=========================
If some learning samples are labeled, but some other are not labeled, then it is semi-supervised learning. It
makes use of a large amount of unlabeled data for training and a small amount of labeled data for testing.
Semi-supervised learning is applied in cases where it is expensive to acquire a fully labeled dataset while
with an environment. Instead of being given correct input-output pairs (like in supervised learning), the agent
learns from feedback in the form of rewards or penalties based on the actions it takes.
The goal of the agent is to learn the best sequence of actions (called a policy) that maximizes the total reward
over time. It works on a trial-and-error basis if an action results in a good outcome, it's reinforced; if it leads
===================================
ML systems learn patterns from historical data and make predictions on unseen data.
Medical diagnosis
Fraud detection
Capable of analyzing massive datasets that are impossible for humans to process manually.
Example: Recommendation systems adapt based on user preferences (Netflix, YouTube, Amazon).
7. Scalability
Once trained, ML models can be scaled to handle large user bases without performance loss.
==================================
1. Data Dependency
Training complex models (e.g., deep neural networks) requires powerful hardware (GPUs/TPUs).
Difficult to understand how complex models (like deep learning) arrive at decisions.
Lack of transparency is a major issue in sensitive fields like healthcare and law.
4. Risk of Overfitting/Underfitting
5. Difficult to Generalize
A model trained on one dataset may not perform well on other or unseen datasets.
6. Complex Implementation
Data preprocessing
Feature selection
Algorithm tuning
Model evaluation
Data privacy issues may arise due to collection and storage of personal data.
ML systems can inherit bias from historical data (gender, race, etc.).
8. Time-Consuming Training
Model training (especially for deep learning) can take hours or days.
====XXXX====
=======================
When a model is trying to learn a target concept (like identifying whether an email is spam or not), it starts
with a hypothesis space In machine learning, a hypothesis is a function or rule that the learning algorithm
As the model sees labeled examples, it eliminates hypotheses that don't match the training data. The
==============================
The set of all possible rules or functions that your learning algorithm considers.
For example: All red fruits, All sweet fruits, All round fruits, etc.
==========================
G (General Boundary):
Contains the most general hypotheses that are still consistent with data.
S (Specific Boundary):
All hypotheses between the most general and most specific consistent ones form the Version Space.
====XXXX====
SOFTWARE USED IN ML
===================
[Link] Mahout
================
Definition:
Apache Mahout is an open-source machine learning library developed by the Apache Software Foundation.
It is designed to build scalable machine learning applications that run efficiently on large datasets.
Apache Mahout is known for its scalability, as it is designed to handle big data efficiently using distributed
computing frameworks like Apache Hadoop and Apache Spark. It is also highly extensible and customizable,
====XXXX====
========================
Definition:
In machine learning, a hypothesis is a function or rule that the learning algorithm uses to make predictions
Formally, a hypothesis is a possible explanation (or function) that maps inputs to outputs, aiming to
Let:
=====================================================
In machine learning, a hypothesis is a possible mapping function that defines how input data (X) is related to
output values (Y). It is the models assumption about the underlying relationship between inputs and outputs.
1. Hypothesis Space
The hypothesis space (H) is the set of all possible hypotheses that a learning algorithm can explore.
For example, in linear regression, the hypothesis space includes all linear functions of the form:
y=mx+c
y=mx+c
In more complex models like decision trees or neural networks, the hypothesis space includes tree structures
Each learning algorithm has a different hypothesis space, depending on how it represents and processes the
data.
2. Formulating a Hypothesis
A specific hypothesis (h) is selected from the hypothesis space based on the training data.
A decision tree formulates a hypothesis by dividing the input space into regions using conditions.
A neural network forms a hypothesis by adjusting weights and biases through multiple layers.
This hypothesis should predict outputs accurately for both training and unseen data.
The learning algorithm searches the hypothesis space to find the best hypothesis that minimizes prediction
error.
It uses techniques like gradient descent, entropy-based splitting, or backpropagation.
The objective is to find a hypothesis that not only fits the training data but also generalizes well to
new/unseen data.
================================================
1. Consistent Hypothesis
A hypothesis is called consistent if it correctly predicts the output for all training examples.
Example: If a hypothesis always predicts "yes" for all known fruits and never for non-fruits, it is consistent.
2. Inconsistent Hypothesis
In practice, many algorithms can tolerate some level of inconsistency to avoid overfitting.
3. General Hypothesis
4. Specific Hypothesis
A specific hypothesis is highly restrictive and applies to a narrow set of data.
Example: Only white cats with blue eyes are pets very specific.
5. Inductive Hypothesis
Used in supervised learning where the model learns patterns from labeled data.
====XXXX====
============================
Definition:
Multiple Hypothesis Testing refers to the process of simultaneously testing several statistical hypotheses. It is
commonly used in fields like machine learning, bioinformatics, and data analysis where large datasets lead to
multiple comparisons.
====XXXX====
PAC Learning (Probably Approximately Correct Learning) is a framework in machine learning introduced by
Leslie Valiant in 1984. It helps to understand whether a learning algorithm can perform well on unseen data
after being trained on a limited number of examples. In PAC learning, the goal is to find a hypothesis (or rule)
that is approximately correct (meaning it may have small errors) and probably correct (meaning it works well
with high confidence, like 95%). It tells us that if enough training data is given, the algorithm can learn a good
solution with high accuracy and low error. PAC learning helps to check if learning from examples is possible
and reliable in a practical way.
Sample Complexity in PAC Learning means how many training examples are needed to make sure the
learning algorithm gives good results. It tells us how much data we need so that the algorithm learns a rule
that works well on new, unseen data. The number of samples depends on how accurate and confident we
want the result to be. If we want very high accuracy or high confidence, we will need more samples.
Hyphothesis space
Generalization means how well a learning algorithm can make correct predictions on new, unseen data. In
PAC Learning, generalization tells us the chance that the learned hypothesis will have only a small error
when used on new data. It is very important in machine learning because a model is useful only if it works
well not just on training data, but also on real-world data. The PAC framework gives us confidence that if we
train the model properly with enough data, it will also perform well on future examples.
PAC Learning Theorem gives us a way to understand how many training examples are needed to learn well.
It says that if we want a learning algorithm to be accurate (small error, called ) and confident (high chance of
being right, called 1), then there is a minimum number of samples (m) needed for this to happen.
Where:
The VC Dimension tells us how flexible or powerful the model is. A more complex model (higher VC) will
need more samples to learn properly without overfitting.
In short, the PAC theorem helps us know how much data we need to train a model that will work accurately
====XXXX====
hypothesis set is. It tells us how well a model can fit different patterns in the data. This concept was
introduced by Vladimir Vapnik and Alexey Chervonenkis in the 1970s and is important in learning theory.
The VC dimension of a hypothesis set H is the maximum number of data points that it can shatter.
To "shatter" a set of points means the model can correctly classify the points in every possible way no
In simple words, if a model has a higher VC dimension, it means it can handle more complex data patterns.
But too high a VC dimension can also lead to overfitting, so we need to balance it properly.
Bounds of VC Dimension
The VC dimension provides both upper and lower bounds on the number of training examples required to
achieve a given level of accuracy. The upper bound on the number of training examples is logarithmic in the
====XXXX====
A hypothesis space is the set of all possible rules or models that a learning algorithm can choose from while
learning.
Example:
If your model has only 10 fixed rules to classify emails, the hypothesis space is finite.
It can represent more complex models, but learning and analysis are harder.
Example:
If you're trying to fit a line to data (like in linear regression), there are infinite possibilities for slope and
====XXXX====
UNIT-2
======
============================
Linear classification is a technique where we use a straight line (or plane) to separate data into different
classes.
It works best when the data from different categories can be separated by a straight line.
If your data is clean and classes are well-separated, linear models perform very well.
4. Easy to interpret
You can clearly understand the relationship between features and output.
If the data is not linearly separable (e.g., circular or XOR shaped), it performs poorly.
2. Sensitive to outliers
A few wrong or extreme data points can change the decision boundary.
3. Limited flexibility
It assumes that the relationship between features and output is linear which is not always true in real life.
In Real Life:
Spam detection: Classify emails as spam or not based on word count and other features.
================================================
Non-linear classification is used when the data cannot be separated by a straight line. Instead, it needs a
Its useful when classes overlap in such a way that a line just won't do the job.
Decision Trees
Neural Networks
Since real data is rarely perfectly linear, non-linear models are often better.
Flexible
Harder to interpret
Risk of Overfitting
============================= is a machine learning technique used to classify input data into more
than two categories. Unlike binary classification which deals with only two possible outputs (like yes or no),
multiclass classification involves multiple class labels, but the model still assigns only one label per input. The
main goal is to train the model in such a way that it can look at the features of new data and decide the most
This type of classification is used in many real-life applications. For example, in handwritten digit recognition,
the model predicts which number (0 to 9) is written in an image. In email filtering, emails may be sorted into
"spam", "important", or "other" folders. Other common applications include image recognition, speech
To perform multiclass classification, machine learning algorithms like Decision Trees, Random Forest,
Support Vector Machines (SVM), and Neural Networks are often used. The model is trained on labeled data,
and then it uses that learning to make predictions on new, unseen data. This helps machines understand and
Multi-label classification
============================ is a machine learning task where each input can be assigned more than
one label at the same time. This is different from multiclass classification, where each input gets only one
label from many possible classes. In multi-label classification, a single instance may belong to multiple
categories, which makes the task more complex and closer to real-world situations.
For example, a single news article might be related to "politics", "economy", and "education" at the same
time. Similarly, a photo on a social media platform can be tagged with "nature", "mountain", and "sunset" all
at once. In such cases, the model must predict a set of labels, not just one.
This method is used in many real-life applications like movie genre classification, music recommendation,
document tagging, and medical diagnosis, where a patient might have multiple symptoms or diseases.
Multi-label classification provides a better and more flexible way to handle data that doesnt fit neatly into just
one category.
What are Decision Trees? Full Explanation for Exams
====================================================
Definition:
A Decision Tree is a supervised machine learning algorithm used for both classification and regression tasks.
It models decisions in the form of a tree-like structure, where internal nodes represent conditions on attributes
(features), branches represent outcomes of these conditions, and leaf nodes represent the final class label or
decision.
====================================
The terminal nodes (leaves) are the final decisions or class labels.
=================================
Stop when:
Overfitting Trees may become too complex and fit noise in the data.
learning. It helps in building a decision tree by choosing the best feature to split the data at each step. The
main idea is to select the feature that gives the highest information gain, meaning it reduces the uncertainty
The algorithm works by checking all the features and selecting the one that best divides the data into smaller,
more similar groups. This process is done recursively, where the tree keeps growing until a stopping
condition is met such as when all data is perfectly classified, or a certain tree depth is reached.
ID3 uses the concept of entropy and information gain to determine the attribute that best separates the data.
Entropy measures the impurity or randomness in the dataset. The algorithm calculates the entropy of each
attribute and selects the one that results in the most significant information gain when used for splitting the
data.
2. Creating Tree Nodes:
The chosen attribute is used to split the dataset into subsets based on its distinct values. For each subset,
ID3 recursively finds the next best attribute to further partition the data, creating branches and new nodes
accordingly.
3. Stopping Criteria:
The recursion continues until one of the stopping criteria is met, such as when all instances in a branch
belong to the same class or when all attributes have been used for splitting.
ID3 can handle missing attribute values by employing various strategies like attribute mean/mode substitution
5. Tree Pruning:
Pruning is a technique to prevent overfitting. While not directly included in ID3, post-processing techniques or
=========================================
Definition:
CART is a type of decision tree algorithm used for both classification and regression problems.
It builds a binary tree by splitting the data at each node using the feature that gives the best separation based
on a criterion.
1. Tree Structure:
CART builds a tree-like structure consisting of nodes and branches. The nodes represent different decision
points, and the branches represent the possible outcomes of those decisions. The leaf nodes in the tree
2. Splitting Criteria:
CART uses a greedy approach to split the data at each node. It evaluates all possible splits and selects the
one that best reduces the impurity of the resulting subsets. For classification tasks, CART uses Gini impurity
as the splitting criterion. The lower the Gini impurity, the more pure the subset is. For regression tasks, CART
uses residual reduction as the splitting criterion. The lower the residual reduction, the better the fit of the
3. Pruning:
To prevent overfitting of the data, pruning is a technique used to remove the nodes that contribute little to the
model accuracy. Cost complexity pruning and information gain pruning are two popular pruning techniques.
Cost complexity pruning involves calculating the cost of each node and removing nodes that have a negative
cost. Information gain pruning involves calculating the information gain of each node and removing nodes
============================
Stop when:
Splitting Criteria:
=====================
For Classification:
For Regression:
Advantages of CART:
Disadvantages of CART:
Simple Definition:
Linear Regression is a technique used to find the relationship between two variables one is input
It tries to draw a straight line that best fits the data points and helps us predict future values.
1300240
1500320
1700330
1830295
1550256
2350409
1450319
Y=mX+c
Where:
Definition:
Simple Linear Regression is used when we have one input variable (X) and we want to predict one output
Formula:
Y=w0+w1X+
X = Input (feature)
Definition:
Multiple Linear Regression is used when we have two or more input variables (X1, X2, ...) and we want to
Formula:
Y=w0+w1X1+w2X2+...+wpXp+
Y = Output (target)
= Error term
Step-by-Step Working of Linear Regression:
=========================================
We assume that there is a linear relationship between the input (X) and the output (Y).
To know how good our prediction is, we compare it with the actual value.
The difference between the actual Y and predicted Y is called the error.
We use a cost function (also called loss function) to calculate the total error for all data points.
Now, the model tries to reduce this error by adjusting the values of
w0 and w1
In this method, the algorithm updates the weights step-by-step in the direction where the error becomes
Over time, the model finds the best values of w0 and w1 that give the lowest error.
==================================
In Simple Linear Regression, we predict the output using only one input variable.
But in Multiple Linear Regression, we use two or more input variables to predict the output.
====> NoteBook
============================
Logistic Regression is a classification algorithm used to predict the probability of a variable. It uses the
sigmoid function to map predictions between 0 and 1 and helps in binary and multi-class classification
problems.
Logistic regression is a machine learning algorithm used to predict a yes/no (binary) outcome, like whether a
Instead of predicting exact numbers, it predicts probabilities, and then classifies the result as 0 or 1 (No or
Yes).
===========================================
[Link] Relationship:
Logistic Regression assumes that there is a linear relationship between input features and the output.
Pass the linear output z into the sigmoid function to map the result between 0 and 1:
Y = 1 / (1 + e^(-z))
[Link] Probability:
[Link] Error:
Use a loss function (like binary cross-entropy) to measure the error between predicted and actual outputs.
[Link] Weights:
Adjust the weights using optimization techniques like gradient descent to minimize the error.
Repeat:
Steps 2 to 7 are repeated until the model performs well and predictions are accurate.
Advantages:
===========
Disadvantages:
===============================================
K-Nearest Neighbors (KNN) is a supervised learning algorithm used for classification and regression tasks. It
is one of the simplest and most intuitive machine learning algorithms. The main idea is to classify a new data
point based on the majority label of its K nearest neighbors in the feature space.
=========================
K represents the number of nearest neighbors that needs to be considered while making prediction.
To measure the similarity between target and training data points Euclidean distance is used. Distance is
The k data points with the smallest distances to the target point are nearest neighbors.
When you want to classify a data point into a category (like spam or not spam), the K-NN algorithm looks at
the K closest points in the dataset. These closest points are called neighbors. The algorithm then looks at
which category the neighbors belong to and picks the one that appears the most. This is called majority
voting.
In regression, the algorithm still looks for the K closest points. But instead of voting for a class in
classification, it takes the average of the values of those K neighbors. This average is the predicted value for
Advantages of KNN
Disadvantages of KNN
Slow for large datasets (as distance must be calculated for each point)
Fraud detection
What is a Perceptron?
========================
A Perceptron is a type of Artificial Neuron (like one cell of a human brain) used in binary classification tasks
It takes multiple input values, applies weights, adds a bias, and then passes the result through an activation
===================================
A Perceptron is a basic algorithm used for binary classification. It decides whether an input belongs to Class
ini
Copy
Edit
cpp
Copy
Edit
When the perceptron makes a wrong prediction, it adjusts weights and bias using the following rule:
ini
Copy
Edit
This helps the perceptron to learn from its mistakes and improve future predictions.
This process is repeated for many iterations (epochs) over the dataset until:
==================================================================================
=============================
UNIT-4
===========
Clustering (or Cluster Analysis) is a machine learning technique used to group unlabeled data into meaningful
clusters based on similarity. It is a way of organizing data points such that similar data points are placed in
the same group (cluster), while different or dissimilar data points are placed in separate groups.
==========================================
Partitioning clustering means dividing data into small groups, where each group has similar types of data
points.
Its called non-hierarchical because it doesnt follow a step-by-step tree structure it just directly splits the data
into groups.
Then the algorithm places centers (called centroids) and checks which data point is closest to which center.
Data points in the same group are similar
==============================================
Density-based clustering works by finding areas in the data where points are packed closely together (high
density).
It then joins these dense areas to form clusters, even if the clusters are in weird or random shapes.
Key Points:
It doesnt care about shape clusters can be round, long, or any random shape
The data is high-dimensional (many features), which makes it harder to measure density
========================================================
In this method, clustering is done by assuming that the data comes from a specific type of distribution usually
What is the probability that a data point belongs to a certain cluster (distribution)?
So, it creates models (like bell-shaped curves) for each cluster and assigns data points based on how likely
they fit into those curves.
Example:
A popular algorithm for this is Expectation-Maximization (EM) using Gaussian Mixture Models (GMM).
Then it calculates probabilities for each data point like this point has 80% chance of being in Cluster A, 20%
in Cluster B
==========================================
Hierarchical clustering is a method where you dont need to pre-define the number of clusters (unlike
K-Means).
What is a Dendrogram?
Later, you can cut the tree at any level to choose how many clusters you want.
================================================
What is AGNES?
It starts by treating each data point as its own cluster and then repeatedly merges the two closest clusters
until:
Start with individual points: Each data point is its own cluster. For example if you have 5 data points you start
Calculate distances between clusters: Calculate the distance between every pair of clusters. Initially since
each cluster has one point this is the distance between the two data points.
Merge the closest clusters: Identify the two clusters with the smallest distance and merge them into a single
cluster.
Update distance matrix: After merging you now have one less cluster. Recalculate the distances between the
Repeat steps 3 and 4: Keep merging the closest clusters and updating the distance matrix until you have only
Create a dendrogram: As the process continues you can visualize the merging of clusters using a tree-like
diagram called a dendrogram. It shows the hierarchy of how clusters are merged.
AGNES uses different ways to measure how "close" two clusters are:
Linkage TypeDescription
Average LinkageAverage distance between all pairs of points from two clusters
Ward's MethodMerges clusters that result in the least increase in total variance
What is a Dendrogram?
Example:
Start: Each point is its own cluster {A}, {B}, {C}, {D}
Merge the two closest Suppose A and B now clusters are: {AB}, {C}, {D}
Recalculate distances
Merge next closest suppose {C} and {D} now: {AB}, {CD}
==============================================
What is DIANA?
It is the opposite of AGNES while AGNES is bottom-up, DIANA is a top-down hierarchical clustering method.
Start with one big cluster containing all the data points.
Then, it splits the cluster by identifying the most dissimilar data point (the one thats farthest from others).
Now, other points are moved from the original cluster to the new cluster if they are more similar to the new
one.
OR
Simple Example:
Identify the point most different suppose it's E create new cluster {E}
Check which other points are closer to E maybe D now {D, E}, and {A, B, C}
======================================================
Introduction:
K-Modes Clustering is an unsupervised machine learning algorithm specially designed for clustering
categorical data.
It is an extension of the K-Means algorithm, which is typically used for numerical data.
While K-Means uses the mean to find cluster centers, K-Modes uses the mode (most frequent value)
Why K-Modes?
K-Means cant handle this kind of data because it relies on numerical distance calculations like Euclidean
distance.
Thats why we use K-Modes, which compares matching categories instead of using distance formulas.
Assign the point to the cluster with the lowest mismatch (highest similarity).
Update the clusters: Find the most common value (the mode) for each cluster and update the cluster centers
based on this.
Repeat the assignment and mode update steps until cluster assignments stop changing (convergence).
Advantages of K-Modes:
Disadvantages:
Requires you to predefine K (number of clusters)
May not work well with mixed data types (categorical + numerical)
====XXXX====
Kohonen Self-Organizing Map (SOM) is a type of neural network that learns using a technique called
competitive learning.
==============================
The neuron that is closest to the input (most similar) is declared the winner.
This winning neurons weights are updated so that it becomes even more like the input.
The SOM creates a map where similar inputs are mapped close together, forming a meaningful pattern.
This is called topological ordering similar data points get connected to nearby neurons on the map.
In a 1D SOM, the weights of the neurons are arranged in a proper increasing or decreasing order like: Wi <
A Self-Organizing Map (SOM) is usually shown as a 2D grid of neurons (also called processing elements).
Each neuron has its own weight vector, and the learning in SOM is based on adapting these weight vectors.
When an input is given, all neurons calculate their distance from the input (usually Euclidean distance).
Not only the winners weights, but also the neighboring neurons weights are updated.
At the beginning of training, the neighborhood is large, helping to create a rough organization of the map.
As training continues, the neighborhood gets smaller, which helps in fine-tuning the map.
This use of neighborhoods helps SOM to build a topologically ordered map, where similar inputs are placed
close together.
Because of this combination of competition + neighborhood updates, the learning process becomes
non-linear.
=====================================
Initialization:
Each neuron (node) in the map is assigned a random weight vector (same size as the input).
Input Presentation:
The Euclidean distance between the input vector and each nodes weight is calculated.
The node with the smallest distance is chosen as the BMU (Best Matching Unit).
Updating Weights:
The BMU and its neighboring nodes update their weights to become more like the input vector.
Shrinking Neighborhood:
Over time, the learning rate and neighborhood radius decrease, allowing fine-tuning of the map.
Repeat:
Steps 25 are repeated for all input vectors over many iterations (epochs).
Final Result:
The map organizes the input data such that similar inputs are grouped together and dissimilar ones are far
apart.
==========================
Unsupervised Learning:
No need for labeled data, works well with raw and unstructured data.
Preserves Topology:
Clustering Ability:
Groups similar data together automatically.
Noise Tolerance:
===================================
Needs careful tuning of learning rate, map size, and number of iterations.
Computation Time:
Works best with numerical data, not with text or categorical data unless preprocessed.
Final output depends on initial weights and may vary slightly with each run.
=========================================
Expectation-Maximization (EM) Algorithm Easy Notes
Definition: The EM algorithm is an iterative method used in unsupervised machine learning to estimate
unknown parameters in statistical models, especially when some data is missing or hidden.
Latent Variables:
These are hidden things in the data that we can't see directly. But they still affect what we observe. We try to
guess them.
Likelihood:
This means how likely it is that our current guess (parameters) explains the data we have. Higher is better.
Log-Likelihood:
This is just a math tricktaking the log of likelihood. It makes the calculations easier and helps us check how
This is a way to find the best guess for the model. We try to choose values that make the data most likely.
Posterior Probability:
This tells us the chance of something being true after weve looked at the data. It helps when we have missing
or uncertain info.
In this step, we guess the hidden parts (latent variables) using the data we have and the current guess of
parameters.
Now we update our guess (parameters) to better fit the data, based on what we figured out in the E-step.
Convergence:
This means the process is done. Our guesses are not changing much anymore, so we can stop.
1st Step: Initialization
First, we assume some initial values for the parameters (like mean, variance, or probability).
Example: If we are dividing people into 2 groups, we assume each groups average height/weight, etc.
In this step, we use the observed (known) data to guess the missing or hidden information.
Basically, we try to figure out which data point belongs to which group based on current parameter values.
Now, based on the guessed data from the E-step, we update the parameter values (like group averages,
probability, etc.).
This step improves the model by learning from the guessed full data.
In the final step, we check if the guessed values are becoming stable or not.
Initialization:
The algorithm starts with initial parameter values and assumes the observed data comes from a specific
model.
Calculate the posterior probability (responsibility) of each latent variable given the observed data.
Compute the log-likelihood of the observed data using the current parameter estimates.
This involves solving an optimization problem to find parameter values that improve the model fit.
Convergence:
If the changes in log-likelihood or parameters are below a set threshold, stop. If not, repeat the E-step and
============================================================
GMM is a probabilistic model that assumes the data is made up of a mixture of several Gaussian (normal)
distributions.
Think of it like this: if you have a group of people with different heights some short, some average, some tall
GMM assumes that each group of heights follows its own bell-shaped curve (Gaussian), and the full dataset
GMM is used when you want to find hidden groups or clusters in data especially when the data is unlabeled
The challenge is that the data is generated by multiple sources (or processes), and all data is mixed together.
But we dont know which data point came from which source so its hard to separate them just by looking.
IT USES EM-ALGORITHM.
===========================================
PCA is a dimensionality reduction technique used in machine learning. Its main job is to:
WORKING
=========
What is it?
We convert all the features (columns) so that they have a mean of 0 and a standard deviation of 1.
Why?
Because some features might have large values (like salary) and others small (like age), which can mislead
Example:
If one feature is height in cm (160, 170...) and another is weight in kg (60, 70...), height will dominate. So we
standardize.
What is it?
Why?
To find which features vary together and how strongly they are related.
Example:
They help us know which directions (or combinations of features) carry the most important information.
What is it?
Why?
Because they represent the most important patterns or directions in the data.
Goal:
Keep only the components that explain the most variance and drop the rest.
What is it?
We project (shift) the original data onto the new axes (principal components).
======================================
LLE is an unsupervised learning method used for dimensionality reduction, especially when the data lies on a
Goal: Convert high-dimensional data into a low-dimensional version (2D, 3D, etc.) without losing the local
For each data point, it finds the k-nearest neighbors (the closest points).
It is assumed that each point is formed as a linear mixture (combination) of its neighbors.
Step 2: Building the Weight Matrix (How much mixture?)
For each data point, it calculates how much each neighbor contributes to form that point.
The goal is to minimize reconstruction error i.e., the original point should be approximately rebuilt from its
neighbors.
can every point still be formed from its neighbors in the same way as in the original space?
How accurately can each data point be reconstructed from its neighbors in the new space?
This representation preserves the shape and relationships of the original data,
UNIT-3
=======
Ensemble Learning is a technique that combines multiple machine learning models to get better and more
You train multiple different models (like Decision Tree, SVM, KNN).
Then you train a final model (called a meta-model) that learns how to best combine the predictions of those
models.
It doesnt just average it learns how to weigh each models prediction smartly.
2. Blending
Then you just use a simple average or a basic model (like linear regression) to combine them.
Bagging is when:
You train the same model (like Decision Trees) on each subset.
Then you average their outputs (for regression) or vote (for classification).
Each new model focuses on the mistakes made by the previous one.
At the end, predictions are combined with weights (better models get more say).
====================================
Voting is an ensemble technique used mainly for classification problems. Instead of depending on a single
model, multiple models (also known as base learners or classifiers) are trained and their individual
predictions are combined to make a more accurate and robust final decision.
Purpose:
Even if individual models are weak, combining them smartly can lead to a stronger overall model.
The final output is the class which has the highest number of votes.
Example:
ModelPrediction
M1Cat
M2Dog
M3Cat
This method doesn't consider the confidence of models just their label.
All the probabilities are averaged, and the class with the highest average probability is selected.
Example:
ModelP(Cat)P(Dog)
M10.70.3
M20.60.4
M30.90.1
Average:
Soft voting is more powerful, because it takes model confidence into account.
3. Weighted Voting:
ModelPredictionWeight
M1Cat0.9
M2Dog0.6
M3Cat0.8
====================================
Input:
A training dataset:
Training Phase:
For i = 1 to k:
Collect predictions:
C_votes = {c1, c2, ..., ck}
C_final = argmax(count(ci))
=========================================
Random Forest is a machine learning algorithm used for both classification (like predicting a category) and
Its called Random Forest because it uses many decision trees, not just one. Each tree looks at a different
part of the data, and then they vote or average their results to give the final prediction.
===================================
From the main training dataset, pick K random samples (with replacement). This means some data points
Using the selected K data points, train a decision tree. This tree learns patterns only from this small subset.
Decide how many trees you want to build in total for example, N = 100 trees.
The prediction (class/label) which appears most frequently (majority vote) is the final prediction.
Example:
Lets say you have 3 trees that give the following predictions for a new email:
Tree 1 Spam
Tree 3 Spam
=============================
There are mainly four sectors where Random forest mostly used:
Banking: Banking sector mostly uses this algorithm for the identification of loan risk.
Medicine: With the help of this algorithm, disease trends and risks of the disease can be identified.
Land Use: We can identify the areas of similar land use by this algorithm.
Marketing: Marketing trends can be identified using this algorithm.
==========================
It enhances the accuracy of the model and prevents the overfitting issue.
=============================
Although random forest can be used for both classification and regression tasks, it is not more suitable for
Regression tasks.
=============================================
Boosting is a technique where multiple weak models (usually decision trees) are trained one after another,
and each new model tries to correct the mistakes of the previous ones.
A weak learner means a model that performs slightly better than random guessing.
Each new model focuses more on the data points that were wrongly predicted before.
In the end, we combine all models predictions to get the final result.
=================
Initially, a simple model (e.g., decision tree with limited depth) is trained on the data.
errors.
In the next iteration, more weight is given to the misclassified data points. This means the model will focus
A new model is trained with the updated weights. The goal is for the new model to perform better on the
misclassified points.
The final prediction is made by combining the predictions from all the individual models, often by assigning a
This process continues for several rounds or iterations, and the final output is a weighted sum of all the
individual predictions.
converting it into several binary classification problems. Each class is assigned a unique binary code (like
101, 010, etc.), and for every bit position in the code, a separate binary classifier is trained. When a new input
is given, all binary classifiers make predictions, forming a binary string. This predicted string is then compared
to the predefined codes of each class, and the closest match determines the final class prediction.
One-vs-All (OvA) is a strategy where one class is compared against all other classes. For example, if there
are 4 classes, 4 binary classifiers are created. Each classifier is trained to recognize one class as positive (1)
and the remaining as negative (-1). The code matrix created using this method has each column representing
one class. This approach is easy to implement and works well in many situations, but it might struggle when
One-vs-One (OvO), on the other hand, compares every possible pair of classes. So for n classes, it creates
n(n-1)/2 binary classifiers. Each classifier focuses on distinguishing between just two classes at a time. This
often results in higher accuracy but at the cost of increased computational effort. Similarly, ECOC can also
use dense or sparse codesdense codes involve more classifiers and offer better error correction, while
sparse codes use fewer classifiers and are computationally faster but may be slightly less robust in noisy
conditions.
Stacking
========
Stacking is one of the popular ensemble modeling techniques in machine learning. Various weak learners are
ensembled in a parallel manner in such a way that by combining them with Meta learners, we can predict
This ensemble technique works by applying input of combined multiple weak learners' predictions and Meta
In stacking, an algorithm takes the outputs of sub-models as input and attempts to learn how to best combine
Stacking is also known as a stacked generalization and is an extended form of the Model Averaging
Ensemble technique in which all sub-models equally participate as per their performance weights and build a
new model with better predictions. This new model is stacked up on top of the others; this is the reason why it
is named stacking.
1. Original Data
This is your regular dataset. You divide it using techniques like K-Fold cross-validation so that every model
Decision Tree
KNN
SVM
Each base model is trained on the training data and makes predictions. These are called Level-0 predictions.
3. Level-0 Predictions
These predictions become the new input for the next model the meta-model.
This model is trained on the predictions made by the base models. It learns:
It could be any model like Logistic Regression, Random Forest, or another powerful algorithm.
5. Final Prediction
Now, the meta-model takes the Level-0 predictions as input and gives the final result a better, more accurate
prediction.
====XXXX====
Bayes Theorem is a rule used to find the updated chance (probability) of an event when we get some new
information. In machine learning, Bayes' theorem is used to improve predictions by using new data. One
common use is in spam filters, where the system checks the words in an email and decides if it's spam or not.
It is also used in medical testing and many other areas where decisions are made using past data and new
evidence.
Bayesian learning starts with some assumptions or beliefs about the data before seeing any actual results.
This is helpful when we already have some past experience or expert knowledge.
As new data comes in, the algorithm updates its beliefs using Bayes Theorem.
Instead of giving a direct "yes or no" answer, Bayesian models give a probability score for example, theres a
70% chance this email is spam.
Unlike many ML models that need huge amounts of data, Bayesian methods can learn well even from a small
Because it provides confidence levels (probabilities), its easier to make smart decisions, especially in fields
Spam filters (email classification), medical diagnosis (disease prediction), speech recognition,
Here are the main challenges when we try to use it in real life:
Example:
How do you know the exact percentage of people who will actually open your email ad? Hard to say!
If your data is wrong, missing, or biased, the result from Bayes Theorem will also be wrong.
Example:
If a survey was only done in one city, it might not reflect the whole country.
For big problems with many variables, the formula becomes complicated and tough to calculate manually.
Example:
Spam filters use Bayes' theorem, but when there are thousands of words (features), the calculation is hard.
Even though Bayes' Theorem is logical, its sometimes hard to explain to people without a math or stats
background.
5. Changing Probabilities
In real-world situations, probabilities may change over time so your earlier "prior" might no longer be correct.
Example:
Weather predictions from last year won't work for this years sudden climate changes.
====XXXX====
Bayes Optimal Classifier (Easy Explanation):
The Bayes Optimal Classifier is the most accurate possible classifier that can be built using Bayes' Theorem.
It chooses the class label for a given input that has the highest probability, based on all possible hypotheses
Naive Bayes is a simple and fast machine learning algorithm. It is mostly used for classification problems.
Key Features:
Uses Probability:
It assumes that all features are independent. This means that each feature (like a word or value) works
It has less number of rules/parameters, so it trains fast and gives predictions quickly.
It is good for data with many features, like in text classification (thousands of words).
Real-life Uses:
Feature Independence:
Each feature is assumed to be independent of every other feature. This means that the presence or value of
one feature does not affect the presence or value of another feature.
If a feature is continuous (numerical), it is assumed to follow a normal (Gaussian) distribution within each
class.
If a feature is discrete (categorical), it is assumed to follow a multinomial distribution within each class.
All features are considered to be equally important in determining the class of the input data.
No Missing Data:
It is assumed that the dataset does not contain any missing values. Every feature should have a valid value.
The core idea behind Naive Bayes is to calculate the posterior probability of a class
X = (x1, x2, ..., xn) using Bayes Theorem. This is done by combining the prior probability of the class and the
Where:
P(C | X): Posterior probability of class C given the features X (what we want to calculate).
P(C): Prior probability of class C (how likely the class is before seeing any data).
P(X | C): Likelihood, the probability of observing the features X given class C.
P(X): Evidence, the total probability of the features (this acts as a normalizing constant).
Since Naive Bayes assumes feature independence, we can simplify the likelihood
P(X | C) as:
Class Prediction:
P(C | X) for each class C and choose the class with the highest probability:
====XXXX====
Bayesian Belief Network (BBN) is a model that helps us understand how different variables (things or events)
are related to each other using probabilities. It is useful for situations where there is uncertainty and we want
Graphical Representation:
BBNs use a graph to represent variables. In this graph, the variables are shown as circles (nodes), and the
relationships between them are shown as arrows (edges). The arrows represent how one variable might
influence another.
Conditional Probabilities:
Each variables probability (or likelihood of happening) depends on the variables that directly influence it. For
example, the probability of variable A happening could depend on variable B. This is shown as:
P(Variable | Parent), which means the probability of a variable happening given its parent variables.
Probabilistic Model:
BBNs use probability distributions to build a model. These models can be applied to make predictions about
unknown outcomes or detect unusual patterns (anomalies) based on the data and the relationships between
variables.
Applications:
BBNs are useful in areas like medical diagnosis, risk assessment, and decision-making, where uncertainty is
involved, and you need to calculate the probability of different events happening based on available data.
Lets consider a real-world scenario where we want to predict the likelihood of getting wet while walking
Step-by-Step Explanation:
We have two variables: "Rain" and "Umbrella". The outcome we are interested in is whether you will get wet
or not.
In the Bayesian Belief Network, each of these variables will be represented as nodes (circles).
The "Rain" variable influences the "Get Wet" variable, and the "Umbrella" variable also influences the "Get
lua
Copy
Edit
Graphical Representation:
sql
Copy
Edit
Rain Umbrella
| |
V V
"Rain" and "Umbrella" are parent nodes, and "Get Wet" is the child node. The arrows show how the two
Conditional Probabilities:
P(Get Wet | Rain, Umbrella): The probability of getting wet based on whether its raining and whether you
If its raining and you have an umbrella, the chance of getting wet is low (say 10%).
If its raining and you don't have an umbrella, the chance of getting wet is high (say 90%).
If its not raining, you wont get wet regardless of the umbrella.
Based on these conditional probabilities, we can calculate the probability of getting wet under different
conditions:
P(Get Wet | Rain = True, Umbrella = False) = 90% (high probability of getting wet if it's raining and no
umbrella).
P(Get Wet | Rain = False, Umbrella = False) = 0% (no chance of getting wet if it's not raining and no
umbrella).
Suppose you want to predict the chance of getting wet tomorrow. If you know the probability of rain tomorrow
and whether youll carry an umbrella, you can use the Bayesian Belief Network to calculate the exact
====XXXX====
Mining Frequent Patterns refers to the process of identifying patterns, associations, or correlations in large
datasets. These patterns are "frequent" because they appear frequently in the dataset, indicating that they
In data mining, frequent pattern mining is a technique used in discovering regularities in data and is widely
used in market basket analysis, web page analysis, and various other domains. Here's an easy explanation
Data Collection:
The first step is to collect the data. This could be transaction data in a retail store, web browsing data, or any
A frequent itemset is an itemset that appears in the data with a frequency that is above a certain threshold,
Example: In the above transactions, let's say we have a minimum support of 50%. This means any itemset
The most commonly used algorithm for frequent pattern mining is the Apriori Algorithm.
In each step, the algorithm prunes the candidate itemsets that do not meet the minimum support threshold.
{Eggs} appears in 1 transaction Support = 1/4 = 25% (Not frequent as it is below the minimum support of
50%)
We continue this process until we cannot find any more frequent itemsets.
Association Rules:
Once frequent itemsets are found, we can generate association rules. These are rules of the form:
{Bread} {Butter}, meaning if a customer buys bread, they are likely to buy butter as well.
Confidence: The probability that item B is bought when item A is bought. For example:
Confidence of {Bread} {Butter} = P(Butter | Bread) = 3/3 = 100% (if bread is bought, butter is always bought).
Lift: The ratio of observed support to expected support if A and B were independent. For example:
Lift = (How often A and B come together) (How often they would come together if there was no relation
between them)
====XXXX====