Module 3
Module 3
• K-NN
• Logistic Regression
• Perceptrons
• Single layer & Multi-layer – Support
• Vector Machines
– Linear & Non-linear
• Error Bounds Fine tuning of algorithms for robotic
environment.
What isOverview
Session KNN?
Initialise the value of k i.e how many nearest neighbour data points should
consider?
To predict the class label for new observation, iterate through each training data.
1. Calculate the distance between the Query Instance and all the training samples
by using a defined distance measure equation such as Euclidean distance,
Manhattan distance, or Minkowski distance.
2. Sort the calculated distance in ascending order.
3. Get the top k rows from the sorted list of distance.
4. Return the most frequent class/ Majority class of these rows as known predicted
class
Procedure
Session Overview
• How to choose K?
How to Overview
Session Choose “k”?
170 Orange
As per our logic, take k= 3 (rounding off to nearest odd)
175 Orange
Answer is Apple
162 ?
Other Distance
Session Metrics
Overview
Logistic Overview
Session Regression
• Name is somewhat misleading. Really a technique for classification,
not regression.
– “Regression” comes from fact that we fit a
linear model to the feature space.
Dependent Variable(y):
The response categorical variable holding
values like 0 or 1, yes or no etc. (Binary)
Independent Variable(x):
The predictor variable used to predict the
response variable.
Logistic Overview
Session Regression
Odds and
Session Log-Odds
Overview
Admission CGPA
0 4.2
0 5.1
0 5.5
1 8.2
1 9.0
1 9.1
Estimated
Session Regression Equation
Overview
AnotherOverview
Session Example
Example:
Consider the following training examples:
Marks scored: X = [81 42 61 59 78 49]
Grade (Pass/Fail): Y = [Pass Fail Pass Fail Pass Fail]
Assume we want to model the probability of Y of the form
which is parameterized by (β0, β1).
i) Which of the following parameters would you use to model p(x).
(a) (-119, 2) (b) (-120, 2) (c) (-121, 2)
(ii) With the chosen parameters, what should be the minimum mark to ensure
the student gets a ‘Pass’ grade with 95% probability?
ExampleOverview
Session (1-feature X)
Sample Calculation
for p(x) for
ExampleOverview
Session
ExampleOverview
Session
ExampleOverview
Session
ii) With the chosen parameters, what should be the minimum mark to ensure
the student gets a ‘Pass’ grade with 95% probability?
Substituting p(x) = 0.95, 0 = -120 and 1 = 2, we will get
Hours of Pass(1)/Fail
AnotherOverview
Session Example Study (0)
29 0
Question: No. of hrs 32, pass class? Consider threshold 0.5 15 0
What if sample βi Values are not given? 33 1
• β0and β1 (coefficients) values are not given 38 1
39 1
• To find the coefficients, lets find the probability
• Low x → 15 to 29 – Class 0
• High x→ 33 to 39 → Class 1
• Rule of thumb estimate for coefficient is considering difference in 2 points
• Rough rule of thumb estimate for 1 feature
• Here x1➔ avg(high x values), x2 → avg (low x values)
• x1→avg(15,29), x2→avg(33,38,39), x1= 22, x2 = 36.67
• Y is 1 for x1 and 0 for x2 that is p1 =0, p2 = 1
• Instead of 1 and 0, we consider p1 = 0.01 and p2 = 0.99 respectively (since
they are probabilities and applying log is tricky)
• β1 = (ln(0.99/1-0.99))-(ln(0.01)/(1-0.01)) / (36.67-22)
=(4.595)–(-4.595) /14.67
= 9.190/14.67 ~ 0.625
…Continued…
Session Overview
Now computing β0
• β0 = (ln (p1/1-p1) – (β1 * x1)
= -4.595 -0.625* 22
= -4.595 – 13.75
=-18.345
• Z for x= 32,
-18.345+(0.625*32) = 1.655
• P = 1/ (1 +e-(1.655)) = 0.84
Class(y)
1
15 -8.22 0.00027 0
0.8
29 0.03 0.507 1
32 1.655 0.84 1 0.6
38 5.905 0.9973 1
0.2
39 6.53 0.9985 1
0
0 5 10 15 20 25 30 35 40 45
Hours of study
Performance
Session Evaluation
Overview
• Assume for the given problem out of 150 samples the classifier predicted “Yes” 100
times and “No” 50 times.
Performance
Session Evaluation – Confusion Matrix
Overview
• It explains how many of the actual negative cases we were able to predict correctly
with our model.
• It answers the question “How well a model correctly identifies negative cases?”
Performance
Session Evaluation -- True Positive Rate/ Sensitivity/ Recall
Overview
• It explains how many of the actual positive cases we were able to predict correctly
with our model.
=95%
Performance
Session Evaluation -- Precision
Overview
• The Area Under the Curve (AUC) is the measure of the ability of a classifier to
distinguish between classes and is used as a summary of the ROC curve.
• The higher the AUC, the better the performance of the model at distinguishing
between the positive and negative classes.
• When AUC = 1, then the classifier is able to perfectly distinguish between all
the Positive and the Negative class points correctly.
• If, however, the AUC had been 0, then the classifier would be predicting all
Negatives as Positives, and all Positives as Negatives.
Performance
Session Evaluation -- AUC-ROC Curve
Overview
• When 0.5<AUC<1, there is a high chance that
the classifier will be able to distinguish the
positive class values from the negative class
values.
Excellent →
Classifier Good
Classifier
Poor Classifier
Random Classifier →
Perceptron
What are
Session Perceptrons?
Overview
• A perceptron is the simplest form of an artificial neural network and one of the earliest
machine learning algorithms.
How areOverview
Session Perceptron part of Machine Learning?
• Perceptron are learning systems because:
• They learn from data
• They adjust parameters (weights & bias)
• They improve performance iteratively
• They generalize to unseen data
• Supervised learning model, Discriminative classifier, Parametric
learner
• Algorithmic model that learns a decision boundary from data.
What isOverview
Session a decision boundary?
Characteristics
Session Overviewof Single Layer Perceptron
0 0 0 1 Misclassification
0 1 1 1 Correct
1 0 1 1 Correct
1 1 1 1 Correct
Types
Session of Mis
Overview Classification
Actual Predicted Type
It controls how much the weights change during each training step.
For a perceptron:
Input (z):
Updated
S x₁ x₂ t z = w₁x₁ + w₂x₂ + b y t−y Remarks
(w₁, w₂, b)
If t≠y the sample(S) is misclassified. Here all samples are classified correctly
Updated
S x₁ x₂ t z = w₁x₁ + w₂x₂ + b y t−y Remarks
(w₁, w₂, b)
No Misclassifications – So Converged
XOR - Not linearly separable
• A single straight line cannot separate XOR outputs.
• Therefore:
• Single-Layer Perceptron (SLP) fails
• Multi-Layer Perceptron (MLP) works
• XOR proved that hidden layers are necessary, which led to modern neural networks.
To solve XOR, we need:
• At least one hidden layer
• Non-linear activation (ReLU, sigmoid, tanh)
• This creates a non-linear decision boundary.
Simple Example (Image Recognition)
• You give the algorithm examples of what you want the network to do and
it changes the network’s weights so that, when training is finished, it will
give you the required output for a particular input
• Back Propagation networks are ideal for simple Pattern Recognition and
Mapping Tasks
63
How Back Propagation Woks?
64
How Back Propagation Works?
65
How Back Propagation Works?
66
MLP– Back Propagation Algorithm – 6 Step Cycle
Step 1: Initialize weights (wi), biases (bi) (if any) and learning rate Ƞ
Example: w1 : 0.5, w2 : 0.4 , b=0, x=1, y=1
Step 2: Forward Pass: First apply the inputs to the network and work out the output -
remember this initial output could be anything, as the initial weights were random
numbers.
• Loss will give measure of “how wrong we are” but not “how much the
output neuron is responsible for the error” this is quantified in step 4
• We want “How much the loss will change for change in weight?
(derivative of L with respect to w)”
68
MLP– Back Propagation Algorithm – 6 Step Cycle
• STEP 4: Compute Output Layer Gradient (Output Delta)
• Loss depends on weight through multiple steps
70
MLP– Back Propagation Algorithm
71
Back Propagation Algorithm – Example
w1 H1 w5
w2
Output
w3 Layer
H2
w4 w6
72
Back Propagation Algorithm – Example
73
Back Propagation Algorithm – Example
L = ½ (1-0.69)2 = 0.048
74
Back Propagation Algorithm – Example
H1: H2:
𝛔’(Z1) = 0.68 * (1-0.68) = 0.218 𝛔’(Z2) = (0.664)*(1-0.664) = 0.223
75
Back Propagation Algorithm – Example
77
Train Network to recognize A, B, C, D
78
When to Stop Training?
• Ideally, stop it once the network can recognize all the letters successfully. But in Practice, let the error fall to a
lower value first
79
Four Fundamental Equations for Backpropagation
• In slide 9, equations given are for sigmoid function. Here they are generic, applicable to any activation
function
• First component shows how fast the cost is changing and the second component shows how fast the
activation function is changing
• It can be rewritten as, , where the first component is a gradient descent matrix and
second is the activation function change
3. An equation for the rate of change of the cost with respect to any bias in the network:
4. An equation for the rate of change of the cost with respect to any weight in the network
80
Use of Validation Sets
81
Problems with Back Propagation
82
Stochastic Gradient Descent with BP
83
Vanishing Gradients, Exploding Gradients and Sigmoid Function
• Vanishing gradients are common when the Sigmoid or Tanh activation functions
are used in the hidden layer units
• When the inputs grow extremely small or extremely large, the sigmoid function
saturates at 0 and 1
• The derivatives are very near zero
• This function ranges/regions are called saturated regions
• As a result, if your input is located in one of the saturating regions, it has
essentially no gradient to propagate back through the network
• Exploding Gradient: Suppose that the initial weights supplied to the network
result in a high loss, then Gradients can collect during an update, resulting in
very big gradients. This will eventually result in huge modifications to network
weights, resulting in an unstable network. The parameters can occasionally
become so enormous that they overflow and produce NaN values
84
How to Know if Model is Suffering from Vanishing/ Exploding Gradient?
• Vanishing Gradient:
• The parameters of the higher layers vary dramatically, whereas the
parameters of the lower levels do not change significantly for
Vanishing (or not at all).
• During training, the model weights may become zero.
• The model learns slowly, and after a few cycles, the training may
become stagnant.
• Exploding Gradient:
• The model parameters are growing exponentially.
• During training, the model weights may become NaN.
• The model goes through an avalanche learning process
85
Tanh as Activation Function
• The Hyperbolic Tangent, also known as Tanh, is a similar shaped
nonlinear activation function that outputs value range from -1.0 and 1.0
86
Vanishing Gradient Problem
87
What is the solution to vanishing gradient?
• ReLu (Rectified Linear Unit)
• If the input value is positive, the ReLU function returns it; if it is
negative, it returns 0.
• The ReLU’s derivative is 1 for values larger than zero. This handles
vanishing gradient problem
88
What is the solution to vanishing gradient?
• ReLu (Rectified Linear Unit)
• If the input value is positive, the ReLU function returns it; if it is
negative, it returns 0.
• The ReLU’s derivative is 1 for values larger than zero. This handles
vanishing gradient problem
89
What is the solution to vanishing gradient?
• ReLu (Rectified Linear Unit)
• If the input value is positive, the ReLU function returns it; if it is
negative, it returns 0.
• The ReLU’s derivative is 1 for values larger than zero. This handles
vanishing gradient problem
90
Limitations of ReLU
1. Dying ReLU
• During training, some neurons effectively die, meaning they stop outputting anything other than 0
• In some cases, you may find that half of your network’s neurons are dead, especially if you used a
large learning rate
• A neuron dies when its weights get tweaked in such a way that the weighted sum of its inputs are
negative for all instances in the training set
• Solution:
• Variations of ReLU → Leaky ReLU, Parametric Leaky ReLU (PReLU), Exponential Linear Unit (ELU),
or Scaled Exponential Linear Unit (SELU)
91
Variations of ReLU
• ELU (exponential linear unit) : • Scaled ELU (SELU) → is a scaled variant of the ELU activation function.
If we build a neural network composed exclusively of a stack of dense layers, and
if all hidden layers use the SELU activation function, then the network will self-
normalize: the output of each layer will tend to preserve a mean of 0, and the
standard deviation of 1 during training, which solves the vanishing/exploding
gradients problem. 92
Improving the way the network learn
93
Slow Learning in the network
• Example : Consider the single neuron below (take the input 1 to the output 0 )
Initial Weight : 0.6; initial bias: 0.9; Initial Weight : 2.0; initial bias: 2.0;
Learning rate:0.15 Learning rate:0.15
94
Cross-Entropy Cost Function
• If we can replace the cost function with a different cost function, learning slowdown can be
addressed
• What cost function to replace with? → Cross Entropy Cost Function
• Cross entropy loss is a metric used to measure how well a classification model in machine
learning performs
• Cross entropy loss measures the difference between the discovered probability distribution
of a machine learning classification model and the predicted distribution
95
Support Vector Machines(SVM)
• SVM chooses the extreme points/vectors that help in creating the hyperplane.
• These extreme cases are called support vectors, and hence algorithm is termed as Support
Vector Machine.
• The main objective of the SVM algorithm is to find the optimal hyperplane in an N-
dimensional space that can separate the data points in different classes in the feature space.
96
Support Vector Machines(SVM)
• The hyperplane tries that the margin between the closest points of different classes should
be as maximum as possible.
• The dimensions of the hyperplane depend on the features present in the dataset.
97
Support Vector Machines(SVM)
• The hyperplane tries that the margin between the closest points of different classes should
be as maximum as possible.
• The dimensions of the hyperplane depend on the features present in the dataset.
98
Support Vector Machines(SVM)
99
Types of SVM
• 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.
100
Linearly Separable and Non- Linearly Separable Classes
101
Types of SVM
How to choose the best
The dataset has 2 features (x,y) to be
hyperplane?
classified as green and blue
102
How SVM chooses Hyper plane?
• Logic:
For points (𝑥𝑖,𝑦𝑖 ) with labels 𝑦i=±1:
1. The hyperplane :w x+b
T =0
2. All points must satisfy: yi(w x+b)>=1
T
(wTx+b)>=1 103
Linear SVM Example
Positive labelled Class
104
Linear SVM Example
105
Linear SVM Example
• This states that each support vector lies exactly on the SVM margin,
resulting in the expression
106
SVM support-vector condition
107
SVM support-vector condition
108
Augmented Weight Vector
Distance interpretation
109
Points to remember
1
w= 0
(x,y) =(1,0) then the hyperplane is vertical
0
w= 1
(x,y) =(0,1) then the hyperplane is horizontal
1
w= 1
(x,y) =(1,1) then the hyperplane is 45-degree line
110
Final Summary
111
Support Vectors & Hyperplane
112
How to use SVM Model to Classify Data?
Final classification
SVM rule:
f(x)>0 then positive class
f(x)<0 then negative class
Since: 1> 0
(3,2) belongs to the POSITIVE class
113
How to use SVM Model to Classify Data?
114
Non-Linear SVM
115
Projecting Data in higher dimension makes it Linearly Separable
116
Example 1
X Y
-2 +1(. )
-1 -1 (. )
1 -1 (. )
2 +1 ( )
117
Example 1
X Y φ(x) = x2
(New feature f(x) = x2-
space)
2.5 Step 1: Choose a polynomial kernel of degree 2 (Since
degree 1 is non-linear for the problem given)
-2 +1(. ) 4 1.5
f(x)=0.2(−1)K(−1,x)+0.2(−1)K(1,x)+0.12(1)K(2,x)+b
Use 3D Mapping
Where
Now data is in 3D
In 3D, SVM finds a plane:
w1x1+w2x2+w3z+b=0
That plane separates the classes
linearly.
121
Example 2:How Does this Become 2D Again?
The plane equation becomes
122
Example 2
123
Example 2 : Non-Linear SVM - using the new mapping function
Positive labelled Class
2 10 6 6
2 6 6 10
124
Example 2: Support vectors Identified
125
Example 2
126
Example 2
127
How to use SVM Model to Classify Data?
128
Another Example
129