ML module 2
ML module 2
Linear Regression Models: Least squares, single & multiple variables, Bayesian linear
regression, gradient descent, Linear Classification Models: Discriminant function –
Perceptron algorithm, Probabilistic discriminative model - Logistic regression, Probabilistic
generative model – Naive Bayes, Maximum margin classifier – Support vector machine,
Decision Tree
Introduction:
Supervised learning: classification is seen as supervised learning from examples.
● Supervision: The data (observations, measurements, etc.) are labeled with pre- defined classes. It is like
that a “teacher” gives the classes (supervision).
● Test data are classified into these classes too.
Unsupervised learning (clustering)
● Class labels of the data are unknown
● Given a set of data, the task is to establish the existence of classes or clusters in the data
1. Identifies a linear trend: It assumes a straight-line relationship between variables, plotting them on a
graph (scatter plot).
2. Finds the best-fit line: It calculates the line that minimizes the squared differences (residuals) between
the predicted values and the actual data points.
3. Uses an equation: The line is defined by an equation.
Where X (or xi) are the inputs, Y (or y) is the prediction, a (or β1) is the slope, b (or β0) is the y intercept
Key components
Dependent Variable (Y): The outcome you want to predict (e.g., house price).
● Independent Variable(s) (X/xᵢ): The feature(s) used for prediction (e.g., square footage, number of
rooms).
● Slope (a or β1): How much Y changes for a one-unit change in X.
● Y- intercept (b or β0): Value of Y when x = 0
● Error (ε ): The difference between the predicted and actual values.
Types
● Simple Linear Regression: One independent variable predicting the dependent variable (e.g., height to
predict weight).
● Multiple Linear Regression: Multiple independent variables predicting the dependent variable (e.g.,
age, height, diet to predict weight).
Important assumptions
Least Squares
The least squares method is a form of mathematical regression analysis used to determine the line of best
fit for a set of data, providing a visual demonstration of the relationship between the data points. Each
point of data represents the relationship between a known independent variable and an unknown
dependent variable. This method of regression analysis begins with a set of data points to be plotted on
an x-axis and y-axis graph. An analyst using the least squares method will generate a line of best fit that
explains the potential relationship between independent and dependent variables.
The regression line under the Least Squares method is calculated using the following
formula – y = a + bx
Where,
y = dependent variable
x = independent variable
a = y-intercept
b = slope of the line
If the data shows a leaner relationship between two variables, the line that best fits this linear
relationship is known as a least-squares regression line, which minimizes the vertical distance from the
data points to the regression line. The term “least squares” is used because it is the smallest sum of
squares of errors, which is also called the "variance."
In regression analysis, dependent variables are illustrated on the vertical y-axis, while independent
variables are illustrated on the horizontal x-axis. These designations will form the equation for the line
of best fit, which is determined from the least squares method.
In contrast to a linear problem, a non-linear least-squares problem has no closed solution and is generally
solved by iteration.
The line of best fit is a straight line drawn through a scatter of data points that best represents the
relationship between them. Let us consider the following graph wherein a set of data is plotted along the
x and y-axis. These data points are represented using the blue dots. Three lines are drawn through these
points – a green, a red, and a blue line. The green line passes through a single point, and the red line
passes through three data points. In the above graph, the blue line represents the line of best fit as it lies
closest to all the values and the distance between the points outside the line to the line is minimal (i.e.,
the distance between the residuals to the line of best fit – also referred to as the sums of squares of
residuals). In the other two lines, the orange and the green, the distance between the residuals to the lines
is greater as compared to the blue line.
However, the blue line passes through four data points, and the distance between the residual points to the
blue line is minimal as compared to the other two lines.
Multiple regression:
Multiple regression is a statistical technique used to analyze the relationship between one dependent variable
and two or more independent variables. Its main objective is to predict the value of the dependent variable
Multiple Regression Equation: The linear regression equation is given by ( y = bx + a ), where y is the
dependent variable, x is the independent variable, b is the coefficient, and a is the intercept. In multiple
regression, there are several independent variables, so the equation becomes ( y = b 1x1 + b2x2 +…….. + bnxn
+ a). Here, y is the dependent variable, x₁, x₂, …, xₙ are the independent variables, and b₁, b₂, …, bₙ are their
corresponding coefficients representing their contribution to y. The intercept a represents the value of y
when all independent variables are zero. This equation allows prediction of the dependent variable using
multiple independent variables.
Example: A researcher studies the decline in students’ performance during online lectures using multiple
regression. The dependent variable is performance, and the independent variables include factors such as
lack of attention, internet addiction, and technology support. The regression equation is y=b1(attention)
+b2(internet addiction) +b3(technology support) +⋯ +bn x n + a, where each coefficient represents the
influence of each factor on performance.
● Multiple regression helps analyze several predictor variables at the same time.
● It improves reliability by using more than one independent variable.
● It reduces dependence on a single variable.
● It helps study more complex and meaningful hypotheses.
Bayesian linear regression is a method in which the model parameters are treated as probability distributions
rather than fixed values. The dependent variable is expressed as a weighted sum of independent variables,
and the output is assumed to follow a normal (Gaussian) distribution. This method uses prior distribution and
In Bayesian linear regression, the posterior distribution is calculated using Bayes’ theorem:
Here, the posterior is the updated probability of the model parameters after observing data. The prior is the
initial belief about the parameters before seeing the data. The likelihood represents the probability of
observing the data given the parameters. The normalization term ensures the total probability equals one.
This is based on Bayes’ theorem:
In Bayesian regression, we start with prior estimates of parameters and update them as more data becomes
available. As the number of data points increases, the posterior estimates become more accurate and
approach the values obtained using Ordinary Least Squares (OLS).
where w represents the weights and x represents the input variables. In Bayesian regression, the output y is
assumed to follow a Gaussian (normal) distribution:
This means the output is probabilistic rather than a single fixed value. Bayesian Ridge Regression also
assumes a prior distribution for weights:
● When new sales data becomes available, the prior is updated to improve future predictions.
● It helps make better forecasts by combining prior knowledge and new data.
● It also helps prevent overfitting by regularizing the model when many variables are present, such as
season, holidays, and promotions.
Advantages of Bayesian Regression
● It works well even when the dataset is small.
● n_iter: Number of iterations used to train the model. The default value is 100.
● tol: Tolerance value used to check convergence of the model. The default value is 1x10-3.
● alpha_2: Inverse scale parameter for alpha. The default value is 1x10-6.
● lambda_1: Shape parameter of the Gamma distribution for lambda. The default value is 1x10-6
● lambda_2: Inverse scale parameter for lambda. The default value is 1x10-6.
These parameters help control the learning and regularization of the Bayesian Ridge Regression model.
Gradient Descent:
Gradient Descent is an optimization algorithm used to minimize the cost function. It works by repeatedly
adjusting the model parameters such as weights and biases. The adjustments are made in the direction that
reduces the error the most. It gradually reduces the difference between predicted and actual values. This
process continues until the model reaches the optimal parameter values.
Gradient Descent can be understood using the example of walking down a hill to reach the lowest point.
Initially, you start at the top of the hill, which is similar to starting with random parameter values. Then, you
check the slope to find the steepest downward direction, which represents calculating the gradient. Next, you
take a step in that direction, which means updating the model parameters. This process is repeated until you
reach the lowest point, where the error is minimum. Thus, gradient descent helps find the minimum value of
the loss function.
Learning Rate
Learning rate is a hyperparameter that controls the size of steps taken during gradient descent. It determines
how fast or slow the model learns.
● If the learning rate is too large, the model may overshoot the minimum and fail to converge, causing
oscillations or instability.
● Choosing the correct learning rate helps the model converge faster and improves training efficiency.
● Weight Regularization: Helps keep weights in a proper range and improves learning.
● Gradient Clipping: Limits gradient values to prevent very large updates.
● Batch Normalization: Normalizes inputs to improve stability and reduce gradient problems.
Where:
Purpose:
This function measures how wrong the prediction is.
Step 3: Find Gradient with Respect to Weight w
We differentiate the loss function.
1. Predict output
2. Calculate error
3. Calculate gradients
4. Update w and b
Until loss becomes very small.
Step-by-Step Algorithm
Algorithm
Advantages:
Disadvantages:
When to use:
Algorithms
Advantages:
Disadvantages:
When to use:
● Faster convergence.
● Reduces oscillations.
Disadvantages:
When to use:
Advantages:
● No need to manually tune learning rate.
● Good for sparse data.
Batch Gradient Entire dataset Stable but slow High (entire Computationally Stable convergence,
Descent dataset) expensive global view of data
Stochastic Gradient One example Fast but noisy Low (one Less efficient Faster convergence,
Descent per iteration example) good for online learning
Mini-Batch Gradient Mini-batch of Faster and Medium (mini- Efficient, Balance of speed and
Descent data smoother batch) parallelizable stability
Momentum-Based Entire dataset Faster and Medium (like Efficient with Accelerated
Gradient Descent or mini-batch smoother Mini-Batch) momentum convergence, smooth
updates
Data Processing Uses the whole training dataset to Uses a single training sample to
compute the gradient. compute the gradient.
Convergence Speed Slower, takes longer to converge. Faster, converges quicker due to
frequent updates.
Convergence Accuracy More accurate, gives precise Less accurate due to noisy
gradient estimates. gradient estimates.
Optimization of Non- Can get stuck in local minima. Can escape local minima and
Convex Functions find the global minimum.
Suitability for Large Not ideal for very large datasets due Can handle large datasets
Datasets to slow computation. effectively.
Nature Deterministic: Same result for the Stochastic: Results can vary with
same initial conditions. different initial conditions.
Overfitting Can overfit if the model is too Can reduce overfitting due to
complex. more frequent updates.
Escape Local Minima Cannot escape shallow local minima. Can escape shallow local minima
more easily.
Computational Cost High due to processing the entire Low due to processing one
dataset at once. sample at a time.
Linear classification models are supervised machine learning algorithms used to classify data into different
categories. They separate classes using a straight decision boundary such as a line, plane, or hyperplane
based on weighted input features. Common examples include Logistic Regression, Linear Support Vector
Machine (SVM), and Perceptron. These models are simple, fast to train, efficient, and easy to interpret.
Discriminant Functions
A discriminant is a function which takes the input vector X and assigns it to one of the classes Ck. When the
decision surfaces are hyperplanes, we call them as linear discriminants.
Two Classes:
The simplest representation of linear discriminant function is
The input vector will be assigned to the class C1 if y(X)≥0 and C2 otherwise. The decision boundary will
be defined by the relation y(X)=0. Let XA, XB are where W is called the weight vector and W0 is bias. The
negative of the bias is called threshold the two points lying on the decision surface, then y(XA) =
y(XB)=0 and hence
WT(XA−XB) = 0. This means that the weight vector W is orthogonal to every vector in the decision surface,
i.e. W determines the direction of the decision surface. Let X be a point on the decision surface which is
closest to the origin. Thie means that this point can be represented as X=αW as the perpendicular weight
vector W will be the direction in which we will have the smallest vector passing through origin and the
hyperplace. As X lies on the hyperplace, we have y(X)=WTX+W0=0, i.e. WTX+W0=αWTW+W0=0 and
−w0 −w0
hence α=−W0/||W||2. The distance of the point X from the origin is ||X||=||αW||= ||W||=
¿∨W ∨¿ 2 ¿∨W ∨¿ 2
−w0
. Hence, the normal distance of the hyperplane from the origin is given by . This means that
¿∨W ∨¿ 2
the bias parameter W0 decides the location of the decision surface.
Another thing to note is that the value of y(X) gives the signed measure of the perpendicular distance r of
point X from the decision surface. Let X⊥ be the orthogonal projection of X on the decision surface, then
~
We can combine the bias into weight vector with the new weight vector represented as W = (W0, W) with
~
the updated input vector as X =(1,X) and the updated equation
Multiple Classes
A K-class discriminant (K>2) can be built by combining multiple two-class discriminant
functions. However, there are some limitations to it. Consider a one-versus-the-
Fig: Attempting to construct a k class discriminant from a set of 2 class discriminants leads to ambiguous
regions, shown in green. On the left is an example involving the use of 2 discriminants designed to
distinguish points in class Ck. On the right is an example involving three discriminant functions each of
which is used to separate a pair of classes Ck and Cj
Another approach is to use K(K−1)/2 discriminant functions, one for each class pair of
classes. This is called as one-versus-one classifier. Each point then can be classified according to the
majority vote amongst the discriminant functions. The right-hand side image in the above figure shows this
approach. The green region has one vote for each of the classes C1, C2 and C3 and hence being ambiguous.
These ambiguous classification regions can be avoided by using a single K-class discriminant comprising
of K linear functions of the form
The class assignment will be done on the basis of: assign a point X to class Ck if yk (X) > yj(X) for all j ≠
k. The decision boundary between class Ck and Cj is given by yk(X)=yj(X) and corresponds
to a (D−1)-dimensional hyperplane defined by
The decision boundary is same as the one for a two-class case. The decision region of such a discriminant
function is always singly connected and convex. For two points XA, XB which lie in the decision region Rk,
any point X which lies on the line connecting XA, XB can be expressed in the form
Perceptron
The Perceptron was introduced by Frank Rosenblatt in 1957. It is based on the MCP neuron model. The
Perceptron is a supervised learning algorithm used for binary classification. It learns by processing one
training sample at a time and updates its weights accordingly.
1. Input Layer: The input layer consists of one or more input neurons, which receive input signals from
the external world or from other layers of the neural network.
2. Weights: Each input neuron is associated with a weight, which represents the strength of the
connection between the input neuron and the output neuron.
3. Bias: A bias term is added to the input layer to provide the perceptron with additional flexibility in
modeling complex patterns in the input data.
4. Activation Function: The activation function determines the out put of the perceptron based on the
weighted sum of the inputs and the bias term. Common activation functions used in perceptrons include the
step function, sigmoid function, and ReLU function.
5. Output: The output of the perceptron is a single binary value, either 0 or 1, which indicates the class
or category to which the input data belongs.
6. Training Algorithm: The perceptron is typically trained using a supervised learning algorithm such as
the perceptron learning algorithm or backpropagation. During training, the weights and biases of the
● Initially, weights are multiplied with input features, and then the decision is made whether the neuron is
fired or not.
● The activation function applies a step rule to check whether the function is more significant than zero.
● The linear decision boundary is drawn, enabling the distinction between the two linearly separable classes
+1 and -1.
● If the added sum of all input values is more than the threshold value, it must have an output signal;
otherwise, no output will be shown.
A Perceptron accepts inputs, moderates them with certain weight values, then applies the transformation
function to output the final result. The image below shows a Perceptron with a Boolean output.
The activation function applies a step rule (convert the numerical output into +1 or -1) to check if
the output of the weighting function is greater than zero or not.
For example:
If ∑ wixi > 0 🡺 then final output “o” = 1 (issue bank loan)
Else, final output “o” = -1 (deny bank loan)
Step function gets triggered above a certain value of the neuron output; else it outputs zero. Sign Function
outputs +1 or -1 depending on whether neuron output is greater than zero or not. Sigmoid is the S-curve and
outputs a value between 0 and 1.
For example:
If ∑ wixi > 0 🡺 then final output “o” = 1 (issue bank loan)
Else, final output “o” = -1 (deny bank loan)
Step function gets triggered above a certain value of the neuron output; else it outputs zero. Sign Function
outputs +1 or -1 depending on whether neuron output is greater than zero or not. Sigmoid is the S-curve and
outputs a value between 0 and 1.
Output of Perceptron
Perceptron with a Boolean output:
Output: o(x1……………..xn)
w0 🡺 bias or threshold
If ∑w.x > 0, output is +1, else -1. The neuron gets triggered only when weighted input
reaches a certain threshold value.
n output of +1 specifies that the neuron is triggered. An output of -1 specifies that the neuron did not get
triggered.
“sgn” stands for sign function with output +1 or -1.
Error in Perceptron
In the Perceptron Learning Rule, the predicted output is compared with the known output. If it does not
match, the error is propagated backward to allow weight adjustment to happen.
A decision function φ(z) of Perceptron is defined to take a linear combination of x and w vectors.
Bias Unit
For simplicity, the threshold θ can be brought to the left and represented as w0x0, where w0= -θ and x0= 1.
Output:
The figure shows how the decision function squashes wTx to either +1 or -1 and how it can be used to
discriminate between two linearly separable classes.
A Single Layer Perceptron is the simplest type of neural network with one layer of neurons connected to inputs. It works
by calculating a weighted sum of inputs and applying an activation function to produce the output.
● Training: Adjust weights using the Perceptron Learning Rule based on errors.
Probabilistic Models:
1. Generative Models
Generative models learn the joint probability of input and output variables. They can generate new data
similar to the training data. These models are used in applications such as image generation, speech
synthesis, language translation, and text generation.
2. Discriminative Models
Discriminative models learn the probability of the output given the input. They focus on finding a decision
boundary to separate different classes. These models are used for accurate classification tasks such as image
recognition, speech recognition, and sentiment analysis.
3. Graphical Models
Graphical models use graphs to represent relationships between variables. They show how variables depend
on each other. These models are used in image recognition, natural language processing, and causal analysis.
Logistic regression
Logistic regression is a statistical analysis method to predict a binary outcome, such as yes or no, based
on prior observations of a data set.
A logistic regression model predicts a dependent data variable by analyzing the relationship between one
or more existing independent variables. For example, a logistic regression could be used to predict
whether a political candidate will win or lose an election or whether a high school student will be
admitted or not to a particular college. These binary outcomes allow straightforward decisions between
two alternatives.
A logistic regression model can take into consideration multiple input criteria. In the case of college
acceptance, the logistic function could consider factors such as the student's grade point average, SAT
score and number of extracurricular activities. Based on historical data about earlier outcomes involving
the same input criteria, it then scores new cases on their probability of falling into one of two outcome
categories.
Logistic Regression:
Logistic regression is classified into three types based on the type of output variable:
This type is used when the dependent variable has only two possible categories, such as Yes/No, Pass/Fail,
or 0/1. It is the most commonly used type and is applied in binary classification problems.
This type is used when the dependent variable has three or more categories without any specific order. For
example, classifying animals as cat, dog, or sheep. It extends binary logistic regression to handle multiple
classes.
This type is used when the dependent variable has three or more categories with a natural order, such as low,
medium, and high. It considers the order of categories while making predictions.
● Independent observations: Each data point should be independent. There should be no relationship or
dependence between samples.
● Binary dependent variable: The output variable should have only two categories, such as 0/1 or
Yes/No. For more than two categories, Softmax is used.
● Linearity with log odds: There should be a linear relationship between input variables and the log odds
of the output. This means the input variables affect the prediction in a linear way.
● No outliers: The dataset should not contain extreme outliers. Outliers can affect the accuracy of the
model.
● Large sample size: Logistic regression works better with a large amount of data. A large sample size
gives more reliable results.
1. The sigmoid function is an important part of logistic regression. It converts the model output into a
probability value between 0 and 1.
2. It takes any real number as input and maps it to a value between 0 and 1. It forms an S-shaped curve
called the sigmoid curve or logistic curve.
3. In logistic regression, a threshold value, usually 0.5, is used to classify the input. If the sigmoid output is
greater than or equal to 0.5, the input is classified as Class 1. If the output is less than 0.5, the input is
classified as Class 0.
4. This function helps convert continuous values into class labels for classification.
● If the sigmoid output is same or above the threshold, the input is classified as Class 1.
● If it is below the threshold, the input is classified as Class 0.
This approach helps to transform continuous input values into meaningful class predictions.
How does Logistic Regression work?
Logistic regression model transforms the linear regression function continuous value output into categorical
value output using a sigmoid function which maps any real-valued set of independent variables input into a
value between 0 and 1. This function is known as the logistic function.
Suppose we have input features represented as a matrix:
Here xi is the ith observation of X, wi=[w1,w2,w3,⋯,wm] is the weights or Coefficient and b is the bias term
also known as intercept. Simply this can be represented as the dot product of weight and bias.
At this stage, z is a continuous value from the linear regression. Logistic regression then applies the sigmoid
function to z to convert it into a probability between 0 and 1 which can be used to predict the class.
Now we use the sigmoid function where the input will be z and we find the probability between 0 and 1. i.e.
predicted y.
Taking the natural logarithm of the odds gives the log-odds or logit:
Here K represents the number of elements in the vector z and i,j iterates over all the elements in the vector.
Then the probability for class c will be:
3. Recall (Sensitivity or True Positive Rate): Recall measures the proportion of correctly predicted
positive instances among all actual positive instances.
[Link] Under the Receiver Operating Characteristic Curve (AUC-ROC): The ROC curve plots the true
positive rate against the false positive rate at various thresholds. AUC-ROC measures the area under this
curve which provides an aggregate measure of a model's performance across different classification
thresholds.
6. Area Under the Precision-Recall Curve (AUC-PR): Similar to AUC-ROC, AUC-PR measures the area
under the precision-recall curve helps in providing a summary of a model's performance across different
precision-recall trade-offs.
Fitting
● Original data has two classes: green circles (y = 1) and red squares (y = 2).
● Estimate probability distribution along the first dimension i.e P(x1∣y=1),P(x1∣y=2)P(x1∣y=1),P(x1
∣y=2)
● Estimate probability distribution along the second dimension i.e P(x2∣y=1),P(x2∣y=2)P(x2∣y=1),P(x2
∣y=2)
● Combine both dimensions using conditional independence i.e P(x∣y)=∏αP(xα∣y)P(x∣y)=∏αP(xα
∣y)
Key Features of Naive Bayes Classifiers
The main idea behind the Naive Bayes classifier is to use Bayes' Theorem to classify data based on the
probabilities of different classes given the features of the data. It is used mostly in high-dimensional text
classification
● The Naive Bayes Classifier is a simple probabilistic classifier and it has very few number of
parameters which are used to build the ML models that can predict at a faster speed than other classification
algorithms.
● It is a probabilistic classifier because it assumes that one feature in the model is independent of
existence of another feature. In other words, each feature contributes to the predictions with no relation
between each other.
● Naive Bayes Algorithm is used in spam filtration, Sentimental analysis, classifying articles and many
more.
Why it is Called Naive Bayes?
It is named as "Naive" because it assumes the presence of one feature does not affect other features. The
"Bayes" part of the name refers to its basis in Bayes’ Theorem.
Consider a fictional dataset that describes the weather conditions for playing a game of golf. Given the
weather conditions, each tuple classifies the conditions as fit(“Yes”) or unfit(“No”) for playing golf. Here is
a tabular representation of our dataset.
The dataset is divided into two parts i.e feature matrix and the response vector.
● Feature matrix contains all the vectors(rows) of dataset in which each vector consists of the value
of dependent features. In above dataset, features are ‘Outlook’, ‘Temperature’, ‘Humidity’ and ‘Windy’.
● Response vector contains the value of class variable (prediction or output) for each row of feature
matrix. In above dataset, the class variable name is ‘Play golf’.
Assumption of Naive Bayes
The fundamental Naive Bayes assumption is that each feature makes an:
● Feature independence: This means that when we are trying to classify something, we assume that
each feature (or piece of information) in the data does not affect any other feature.
● Continuous features are normally distributed: If a feature is continuous, then it is assumed to be
normally distributed within each class.
● Discrete features have multinomial distributions: If a feature is discrete, then it is assumed to have
a multinomial distribution within each class.
● Features are equally important: All features are assumed to contribute equally to the prediction of
the class label.
● No missing data: The data should not contain any missing values.
Introduction to Bayes' Theorem
Bayes’ Theorem provides a principled way to reverse conditional probabilities. It is defined as:
P(y∣X)=P(X∣y)⋅P(y)P(X)P(y∣X)=P(X)P(X∣y)⋅P(y)
Where:
1. Terminology
Consider a classification problem (like predicting if someone plays golf based on weather). Then:
The "naive" in Naive Bayes comes from the assumption that all features are independent given the class.
That is:
P(x1,x2,...,xn∣y)=P(x1∣y)⋅P(x2∣y)⋯P(xn∣y)P(x1,x2,...,xn∣y)=P(x1∣y)⋅P(x2∣y)⋯P(xn∣y)
Thus, Bayes' theorem becomes:
P(y∣x1,...,xn)=P(y)⋅∏i=1nP(xi∣y)P(X)P(y∣x1,...,xn)=P(X)P(y)⋅∏i=1nP(xi∣y)
Since the denominator is constant for a given input, we can write:
P(y∣x1,...,xn)∝P(y)⋅∏i=1nP(xi∣y)P(y∣x1,...,xn)∝P(y)⋅∏i=1nP(xi∣y)
We compute the posterior for each class yy and choose the class with the highest probability:
y^=argmaxyP(y)⋅∏i=1nP(xi∣y)y^=argmaxyP(y)⋅∏i=1nP(xi∣y)
This becomes our Naive Bayes classifier.
Let’s take a dataset used for predicting if golf is played based on:
Class Probabilities:
From dataset of 14 rows:
● P(Yes)=914P(Yes)=149
● P(No)=514P(No)=145
Conditional Probabilities (Tables 1–4):
7. Normalize Probabilities
To compare:
P(Yes | today)=0.021160.02116+0.0068≈0.756P(Yes | today)=0.02116+0.00680.021
16≈0.756
8. Final Prediction
Since:
P(Yes | today)>P(No | today)P(Yes | today)>P(No | today)
The model predicts: Yes (Play Golf)
In Gaussian Naive Bayes, continuous values associated with each feature are assumed to be distributed
according to a Gaussian distribution. A Gaussian distribution is also called Normal distribution When
plotted, it gives a bell shaped curve which is symmetric about the mean of the feature values as shown
below:
Multinomial Naive Bayes is used when features represent the frequency of terms (such as word counts) in a
document. It is commonly applied in text classification, where term frequencies are important.
Bernoulli Naive Bayes deals with binary features, where each feature indicates whether a word appears or
not in a document. It is suited for scenarios where the presence or absence of terms is more relevant than
their frequency. Both models are widely used in document classification tasks
Advantages
● Easy to implement and computationally efficient.
● Effective in cases with a large number of features.
Principle:
The decision tree algorithm is based on a greedy approach that builds the tree step by step. It constructs the
tree in a top-down recursive divide-and-conquer manner. Initially, all the training samples are placed at the
root node. The samples are then split into smaller groups based on selected attributes, which are chosen
using measures such as information gain. The process stops when all samples belong to the same class, no
attributes remain for further splitting, or no samples are left, and the final node is assigned a class label using
majority voting if needed.
values
Expressiveness
Decision trees can express any function of the input attributes. E.g., for Boolean functions, truth table
● Trivially, there is a consistent decision tree for any training set with one path to leaf for each example
● a training set,
● a test set.
● In such cases, the values that give the best accuracy on the validation set are used as the final parameter
values.
● Classification measures
● In text mining, we may only be interested in the documents of a particular topic, which are only a small
● In classification involving skewed or highly imbalanced data, e.g., network intrusion and
● Precision and recall measures Used in information retrieval and text classification.
An Example
● recall r = 1%
● because we only classified one positive example correctly and no negative examples wrongly.
Note: precision and recall only measure classification on the positive class.
Support vector machines (SVM)
Support Vector Machine or SVM is one of the most popular Supervised Learning algorithms,
which is used for Classification as well as Regression problems. However, primarily, it is
used for Classification problems in Machine Learning.
The goal of the SVM algorithm is to create the best line or decision boundary that can
SVM chooses the extreme points/vectors that help in creating the hyperplane. These extreme
cases are called as support vectors, and hence algorithm is termed as Support Vector
Machine. Consider the below diagram in which there are two different categories that are
classified using a decision boundary or hyperplane:
Example: SVM can be understood with the example that we have used in the KNN classifier.
Suppose we see a strange cat that also has some features of dogs, so if we want a model that
can accurately identify whether it is a cat or dog, so such a model can be created by using the
SVM algorithm. We will first train our model with lots of images of cats and dogs so that it
can learn about different features of cats and dogs, and then we test it with this strange
creature. So as support vector creates a decision boundary between these two data (cat and
dog) and choose extreme cases (support vectors), it will see the extreme case of cat and dog.
On the basis of the support vectors, it will classify it as a cat. Consider the below diagram:
SVM algorithm can be used for Face detection, image classification, text categorization, etc.
Linear SVM: Linear SVM is used for linearly separable data, which means if a dataset can
be classified into two classes by using a single straight line, then such data is termed as
linearly separable data, and classifier is used called as Linear SVM classifier.
Non-linear SVM: Non-Linear SVM is used for non-linearly separated data, which means if a
dataset cannot be classified by using a straight line, then such data is termed as non-linear
data and classifier used is called as Non-linear SVM classifier.
Hyperplane and Support Vectors in the SVM algorithm:
Hyperplane: There can be multiple lines/decision boundaries to segregate the classes in n-
dimensional space, but we need to find out the best decision boundary that helps to classify
the data points. This best boundary is known as the hyperplane of SVM.
The dimensions of the hyperplane depend on the features present in the dataset, which means
if there are 2 features (as shown in image), then hyperplane will be a straight line. And if
there are 3 features, then hyperplane will be a 2-dimension plane. We always create a
hyperplane that has a maximum margin, which means the maximum distance between the
data points.
Support Vectors:
The data points or vectors that are the closest to the hyperplane and which affect the position
of the hyperplane are termed as Support Vector. Since these vectors support the hyperplane,
hence called a Support vector.
How does SVM works?
Linear SVM:
The working of the SVM algorithm can be understood by using an example. Suppose we have a dataset
that has two tags (green and blue), and the dataset has two features x1 and x2. We want a classifier that can
classify the pair (x1, x2) of coordinates in either green or blue. Consider the below image:
Hence, the SVM algorithm helps to find the best line or decision boundary; this best boundary
or region is calledas a hyperplane. SVM algorithm finds the closest point of the lines from
both the classes. These points are calledsupport vectors. The distance between the vectors and
the hyperplane is called as margin. And the goal of SVM is to maximize this margin. The
hyperplane with maximum margin is called the optimal hyperplane.
So to separate these data points, we need to add one more dimension. For linear data, we have
used two dimensions x and y, so for non-linear data, we will add a third dimension z. It can be
calculated as:
z=x2 +y2
By adding the third dimension, the sample space will become as below image:
Since we are in 3-d Space, hence it is looking like a plane parallel to the x-axis. If we convert it
in 2d space withz=1, then it will become as:
now, SVM will divide the datasets into classes in the following way. Consider the below image:
Since we are in 3-d Space, hence it is looking like a plane parallel to the x-axis. If weconvert it
in 2d space with z=1, then it will become as:
● Face detection – SVMs classify parts of the image as a face and non-face and create a
square boundary around the face.
● Text and hypertext categorization – SVMs allow Text and hypertext categorization for
both inductive and transductive models. They use training data to classify documents into
different categories. It categorizes on the basis of the score generated and then compares
with the threshold value.
● Classification of images – Use of SVMs provides better search accuracy for image
classification. It provides better accuracy in comparison to the traditional query- based
searching techniques.
● Bioinformatics – It includes protein classification and cancer classification. We use SVM
for identifying the classification of genes, patients on the basis of genes and other
biological problems.
● Protein fold and remote homology detection – Apply SVM algorithms for protein remote
homology detection.
● Handwriting recognition – We use SVMs to recognize handwritten characters used widely.
● Generalized predictive control (GPC) – Use SVM based GPC to control chaotic dynamics
with useful parameters.
Top of Form
Bottom of Form