Deep Learning Notes
Deep Learning Notes
Regulation: R23
Machine Learning: Basics and Under fitting, Hyper parameters and Validation Sets, Estimators, Bias and
Variance, Maximum Likelihood, Bayesian Statistics, Supervised and Unsupervised Learning, Stochastic
Gradient Descent, Challenges Motivating Deep Learning.
Deep Feed forward Networks: Learning XOR, Gradient-Based Learning, Hidden Units,
Architecture Design, Back-Propagation and other Differentiation Algorithms.
Regularization for Deep Learning: Parameter Norm Penalties, Norm Penalties as Constrained
Optimization, Regularization and Under-Constrained Problems, Dataset Augmentation, Noise
Robustness, Semi-Supervised Learning, Multi-Task Learning, Early Stopping, Parameter Tying
and Parameter Sharing, Sparse Representations, Bagging and Other Ensemble Methods, Dropout,
Adversarial Training, Tangent Distance, Tangent Prop and Manifold Tangent Classifier.
Optimization for Training Deep Models: Pure Optimization, Challenges in Neural Network
Algorithms.
UNIT-IV: CONVOLUTIONAL NETWORKS (9)
2. [Link]
3. [Link]
4. [Link]
COURSE OBJECTIVES
The main objective of the course is to develop a system to solve the real world
problems using Deep learning models.
Typically we give vectors lower case names written in bold typeface, such as x.
The elements of the vector are identified by writing its name in italic typeface, with a
subscript.
The first element of x is x1 , the second element is x2 and so on. We also need to say
what kind of numbers are stored in the vector.
If each element is in R, and the vector has n elements, then the vector lies in the set
formed by taking the Cartesian product of R n times, denoted as Rn. When we need to
explicitly identify the elements of a vector, we write them as a column enclosed in square
brackets:
• Sometimes we need to index a set of elements of a vector. In this case, we define a
set containing the indices and write the set as a subscript.
• For example, to access x1 , x3 and x6, we define the set S = {1, 3, 6} and write xS.
• We use the − sign to index the complement of a set.
• For example x−1 is the vector containing all elements of x except for x1 , and x−S is the
vector containing all of the elements of x except for x1, x3 and x6 .
MATRICES
A matrix is a 2-D array of numbers, so each element is identified by
o We usually give matrices upper-case variable names with bold typeface, such as
A.
o We usually identify the elements of a matrix using its name in italic but not bold
font, and the indices are listed with separating commas.
o For example, A1,1 is the upper left entry of A and A m,n is the bottom right entry.
TENSORS
Tensors: In some cases we will need an array with more than two axes.
However, it is also possible for the system of equations to have no solutions or infinitely
many solutions for some values of b.
If both x and y are solutions then z = αx + (1 − α)y is also a solution for any real α.
Ax = ∑ xiA:,i.
∑ civ (i)
The span of a set of vectors is the set of all points obtainable by linear combination of the
original vectors.
CONT.
One other norm that commonly arises in machine learning is the L∞ norm, also known as the max
norm.
This norm simplifies to the absolute value of the element with the largest magnitude in the vector,
||x||∞ = max |xi|.
In the context of deep learning, the most common way to do this is with the otherwise obscure
Frobenius norm ||A||F = √ ∑ Ai,j2, which is analogous to the L 2 norm of a vector.
A = AT
If the vectors are not only orthogonal but also have unit norm, we call them orthonormal.
An orthogonal matrix is a square matrix whose rows are mutually orthonormal and whose
columns are mutually orthonormal:
ATA = AAT = I
eigenvalues.
The scalar λ is known as the eigenvalue corresponding to this eigenvector. (One can
also find a left eigenvector such that vTA = λvT , but we are usually concerned with
right eigenvectors).
EXAMPLE : EIGEN DECOMPOSITION OF A 2×2 MATRIX
Problem
Find the eigenvalues and eigenvectors of
4 1
𝐴=
2 3
Step 1: Characteristic Equation
4−𝜆 1
= 4−𝜆 3−𝜆 −2
2 3−𝜆
= 𝜆2 − 7𝜆 + 10 = 0
Step 2: Eigenvalues
𝜆−5 𝜆−2 =0
𝜆1 = 5, 𝜆2 = 2
Step 3: Eigenvectors
For 𝜆 = 5
−1 1
𝐴 − 5𝐼 𝑥 = 0 ⇒
2 −2
1
𝑥=
1
For 𝜆 = 2
2 1
𝐴 − 2𝐼 𝑥 = 0 ⇒
2 1
1
𝑥=
−2
Final Eigen Decomposition
𝐴 = 𝑄Λ𝑄−1
1 1 5 0
𝑄= ,Λ =
1 −2 0 2
Apply Formula
1 −2 −1
𝑄 −1 =
−3 −1 1
CONT.
If v is an eigenvector of A, then so is any rescaled vector sv for s ∈ R, s ≠ 0.
Moreover, sv still has the same eigenvalue. For this reason, we usually only look for
unit eigenvectors.
We may concatenate all eigenvectors to form a matrix V with one eigenvector per
column:
vector λ = [λ1 , . . . , λn ]
A = V diag(λ)V −1
CONT.
We have seen that constructing matrices with specific eigenvalues and eigenvectors
allows us to stretch space in desired directions.
However, we often want to decompose matrices into their eigenvalues and eigenvectors.
Doing so can help us to analyze certain properties of the matrix, much as decomposing
an integer into its prime factors can help us understand the behavior of that integer.
Every real symmetric matrix can be decomposed into an expression using only real-
valued eigenvectors and eigenvalues:
A = Q Λ QT
where Q is an orthogonal matrix composed of eigenvectors of A, and Λ is a diagonal
matrix.
CONT.
The eigenvalue Λi,i is associated with the eigenvector in column i of Q, denoted as
Q:,i. Because Q is an orthogonal matrix, we can think of A as scaling space by λi in
direction v(i).
The eigen decomposition of a matrix tells us many useful facts about the matrix.
The matrix is singular if and only if any of the eigenvalues are zero.
The eigen decomposition of a real symmetric matrix can also be used to optimize
quadratic expressions of the form f (x) = x TAx subject to ||x||2 = 1. Whenever x is
equal to an eigenvector of A, f takes on the value of the corresponding eigenvalue.
The maximum value of f within the constraint region is the maximum eigenvalue and
its minimum value within the constraint region is the minimum eigenvalue.
SINGULAR VALUE DECOMPOSITION
we saw how to decompose a matrix into eigenvectors and eigenvalues.
The singular value decomposition (SVD) provides another way to factorize a matrix, into
singular vectors and singular values.
The SVD allows us to discover some of the same kind of information as the eigen
decomposition.
Every real matrix has a singular value decomposition, but the same is not true of the
eigenvalue decomposition.
For example, if a matrix is not square, the eigen decomposition is not defined, and we must
use a singular value decomposition instead.
EXAMPLE FOR SINGULAR
3 0
VALUE DECOMPOSITION
Find the SVD of 𝐴 =
0 4
step 1: Compute 𝐴𝑇 𝐴
3 0 3 0 9 0
𝐴𝑇 𝐴 = =
0 4 0 4 0 16
Step 2: Eigenvalues of 𝐴𝑇 𝐴
𝜆1 = 16, 𝜆2 = 9
Step 3: Singular Values
𝜎1 = 16 = 4, 𝜎2 = 9 = 3
Step 4: Right Singular Vectors (𝑉)
Eigenvectors of 𝐴𝑇 𝐴:
𝑉=𝐼
Step 5: Left Singular Vectors (𝑈)
𝑈 = 𝐴𝑉Σ−1 = 𝐼
Final SVD
1 0 4 0 1 0
𝐴 = 𝑈Σ𝑉 𝑇 =
0 1 0 3 0 1
Given Matrix
1 2
𝐴=
2 1
Step 1: Compute 𝐴𝑇 𝐴
5 4
𝐴𝑇 𝐴 =
4 5
Step 2: Eigenvalues & Singular Values
𝜆1 = 9, 𝜆2 = 1
𝜎1 = 3, 𝜎2 = 1
Step 3: Right Singular Vectors (𝑉)
Solve 𝐴𝑇 𝐴 − 9𝐼 𝑣 = 0:
1 1
⇒ 𝑣1 =
2 1
Solve 𝐴𝑇 𝐴 − 𝐼 𝑣 = 0:
11
⇒ 𝑣2 =
2 −1
1 1
2 2
𝑉=
1 1
−
2 2
Step 4: Left Singular Vectors (𝑈)
For 𝜎1 = 3
1 1 1
𝑢1 = 𝐴𝑣1 =
3 2 1
For 𝜎2 = 1
1 1
𝑢2 = 𝐴𝑣2 =
2 −1
1 1
2 2
𝑈=
1 1
−
2 2
Final SVD
𝐴 = 𝑈Σ𝑉 𝑇
CONT.
Recall that the eigen decomposition involves analyzing a matrix A to discover a matrix V
of eigenvectors and a vector of eigenvalues λ such that we can rewrite A as
A = V diag(λ)V −1 .
The singular value decomposition is similar, except this time we will write A as a product
of three matrices:
A = UDV T.
The elements along the diagonal of D are known as the singular values of the matrix A.
The non-zero singular values of A are the square roots of the eigenvalues of AT A.
Tr(A) = ∑ Ai,i.
Some operations that are difficult to specify without resorting to summation notation
can be specified using matrix products and the trace operator.
example, the trace operator provides an alternative way of writing the Frobenius
norm of a matrix: ||A||F = √Tr(AAT).
For example, the trace operator is invariant to the transpose operator: Tr(A) = Tr(AT).
This invariance to cyclic permutation holds even if the resulting product has a
different shape.
For example, for A ∈ Rm×n and B ∈ Rn×m, we have Tr(AB) = Tr(BA) even
though AB ∈ Rm×m and BA ∈ Rn×n .
THE DETERMINANT
The determinant of a square matrix, denoted det(A), is a function mapping matrices to real
scalars.
The determinant is equal to the product of all the eigenvalues of the matrix. The absolute
value of the determinant can be thought of as a measure of how much multiplication by the
matrix expands or contracts space.
If the determinant is 0, then space is contracted completely along at least one dimension,
causing it to lose all of its volume. If the determinant is 1, then the transformation is
volume-preserving.
PROBABILITY AND INFORMATION THEORY
1. The laws of probability tell us how AI systems should reason, so we design our algorithms
to compute or approximate various expressions derived using probability theory.
2. we can use probability and statistics to theoretically analyze the behavior of proposed AI
systems.
Why Probability?
CONT.
Many branches of computer science deal mostly with entities that are entirely
deterministic and certain. A programmer can usually safely assume that a CPU will
execute each machine instruction flawlessly.
It can be surprising that machine learning makes heavy use of probability theory.
This is because machine learning must always deal with uncertain quantities, and
sometimes may also need to deal with stochastic (non-deterministic) quantities.
For example, most interpretations of quantum mechanics describe the dynamics of subatomic
particles as being probabilistic. We can also create theoretical scenarios that we postulate to
have random dynamics, such as a hypothetical card game where we assume that the cards are
truly shuffled into a random order.
For example, in the Monty Hall problem, a game show contestant is asked to choose
between three doors and wins a prize held behind the chosen door. Two doors lead to a
goat while a third leads to a car. The outcome given the contestant’s choice is
deterministic, but from the contestant’s point of view, the outcome is uncertain.
3. Incomplete modeling. When we use a model that must discard some of the
information we have observed, the discarded information results in uncertainty in the
model’s predictions. For example, suppose we build a robot that can exactly observe the
location of every object around it.
CONT.
If the robot discretizes space when predicting the future location of these objects, then
the discretization makes the robot immediately become uncertain about the precise
position of objects: each object could be anywhere within the discrete cell that it was
observed to occupy.
RANDOM VARIABLES
A random variable is a variable that can take on different values randomly.
x1 and x2 are both possible values that the random variable x can take on.
For vector-valued variables, we would write the random variable as x and one of its values as x.
A random variable is just a description of the states that are possible; it must be coupled with a
probability distribution that specifies how likely each of these states are.
Random variables may be discrete or continuous. A discrete random variable is one that has a
finite or countably infinite number of states.
Note that these states are not necessarily the integers; they can also just be named states that are
not considered to have any numerical value.
A probability distribution over discrete variables may be described using a probability mass function (PMF).
We typically denote probability mass functions with a capital P.
Often we associate each random variable with a different probability mass function and the reader must infer
which probability mass function to use based on the identity of the random variable, rather than the name of the
function; P(x) is usually not the same as P(y).
To be a probability mass function on a random variable x, a function P must satisfy the following properties:
• ∀x ∈ x,0 ≤ P(x) ≤ 1. An impossible event has probability 0 and no state can be less probable than that. Likewise,
an event that is guaranteed to happen has probability 1, and no state can have a greater chance of occurring.
CONT.
• ∑ P(x) = 1. We refer to this property as being normalized. Without this property, we could
obtain probabilities greater than one by computing the probability of one of many events
occurring.
Example: consider a single discrete random variable x with k different states. We can place a
uniform distribution on x make each of its states equally likely by setting its probability mass
function to P(x = xi) = 1 /k for all i.
We can see that this fits the requirements for a probability mass function.
∑ P(x = xi) = ∑ 1/ k = k/ k = 1,
• ∫ p(x)dx = 1.
A probability density function p(x) does not give the probability of a specific state directly,
instead the probability of landing inside an infinitesimal region with volume δx is given by
p(x)δx.
MARGINAL PROBABILITY
we know the probability distribution over a set of variables and we want to know the
probability distribution over just a subset of them. The probability distribution over the
subset is known as the marginal probability distribution.
P(x, y).
We can find P(x) with the sum rule: ∀x ∈ x, P(x = x) = ∑ P(x = x, y = y).
For continuous variables, we need to use integration instead of summation: p(x) = ∫ p(x, y)dy.
CONT.
Conditional Probability
we are interested in the probability of some event, given that some
other event has happened. This is called a conditional probability.
We denote the conditional probability that y = y given x = x as P(y
= y | x = x). This conditional probability can be computed with the
formula
P(y = y | x = x) = P(y = y, x = x)/ P(x = x) .
The conditional probability is only defined when P(x = x) >0
THE CHAIN RULE OF CONDITIONAL PROBABILITIES
Any joint probability distribution over many random variables may be decomposed into
conditional distributions over only one variable:
∀x ∈ x, y ∈
Two random variables x and y are conditionally independent given a random variable z
if the conditional probability distribution over x and y factorizes in this way for every
value of z:
Ex∼p[f(x)] = ∫ p(x)f(x)dx.
Expectations are linear, for example, Ex[αf(x) + βg(x)] = αEx[f(x)] + βEx[g(x)], when α and
β are not dependent on x. The variance gives a measure of how much the values of a function
of a random variable x vary as we sample different values of x from its probability
distribution:
CONT.
when α and β are not dependent on x. The variance gives a measure of how
much the values of a function of a random variable x vary as we sample
different values of x from its probability distribution:
properties:
P(x = 1) = φ
P(x = 0) = 1 − φ
P(x = x) = φ x (1 − φ) (1−x)
Bernoulli Random Variable in ML
In ML, we often model a binary label as a Bernoulli random variable:
Y∈{0,1},Y∼Bernoulli(p)
Where:
Model
Presence/absence features
𝑝 𝑥 ∣ 𝑧 = ς𝑖 Bernoulli 𝑥𝑖 ∣ 𝑝𝑖
𝑃 𝑥𝑗 ∣ 𝑦 ∼ Bernoulli 𝑝𝑗𝑦
Applications:
Text classification (word present / not present)
Spam filtering
Bernoulli in Regularization & Dropout
Dropout
𝑑𝑖 ∼ Bernoulli 𝑝
𝑑𝑖 = 1 →neuron kept
𝑑𝑖 = 0 →neuron dropped
Bernoulli vs Gaussian in ML
Aspect Bernoulli Gaussian
Data type Binary Continuous
Output activation Sigmoid Linear
Loss Binary Cross-Entropy MSE
Use case Classification Regression
Real-World ML Examples
Ex[x] = φ
Multinoulli Distribution
The exponential distribution uses the indicator function 1x≥0 to assign probability zero to all
negative values of x.
A closely related probability distribution that allows us to place a sharp peak of probability
mass at an arbitrary point µ is the Laplace distribution
we can compute the desired quantity using Bayes’ rule: P(x | y) = P(x)P(y | x) P(y) .
Note that while P (y) appears in the formula, it is usually feasible to compute
[Link]
Expected Outcome
The lecture notes should:
“Data in the real world is high-dimensional, and linear algebra provides the
tools to understand and manipulate it.”
• In order to understand deep learning well, one must have a solid understanding of the
basic principles of machine learning.
• There are multiple ways to define machine learning. But the one which is perhaps
most relevant, concise and accepted universally is the one stated by Tom M. Mitchell,
Professor of Machine Learning Department, School of Computer Science, Carnegie
Mellon University. Tom M. Mitchell has defined machine learning as:
Definition
• A formal definition of the word “task,” the process of learning itself is not the
task. Learning is our means of attaining the ability to perform the task. For
example, if we want a robot to be able to walk, then walking is the task.
• Usually this performance measure P is specific to the task T being carried out by the
system.
• Most of the learning algorithms in this book can be understood as being allowed to
experience an entire dataset.
• Parameter and Model Selection : For many of the algorithms there are parameters that
have to be set manually, or that require experimentation to identify appropriate values.
• Training: Given the dataset, algorithm, and parameters, training should be simply the use
of computational resources in order to build a model of the data in order to predict the
outputs on new data.
Cont.
• Evaluation :Before a system can be deployed it needs to be tested and
evaluated for accuracy on data that it was not trained on.
• This can often include a comparison with human experts in the field, and the
selection of appropriate metrics for this comparison.
MODEL REPRESENTATION AND INTERPRETABILITY
• The input data is just a limited, specific view and the new, unknown data in the test
data set may be differing quite a bit from the training data.
• It means after providing training on the dataset, it can produce reliable and accurate output.
• Hence, the underfitting and overfitting are the two terms that need to be checked for the
performance of the model and whether the model is generalizing well or not.
Overfittin
g
• Overfitting occurs when our machine learning model tries to cover all the data
points or more than the required data points present in the given dataset.
• Because of this, the model starts caching noise and inaccurate values present in
the dataset, and all these factors reduce the efficiency and accuracy of the model.
• Cross-Validation
• Removing features
• Regularization
• Ensembling
Underfitting
• A typical case of underfitting may occur when trying to represent a non-linear data
with a linear model
• Underfitting results in both poor performance with training data as well as poor
generalization to test data.
• Underfitting can be avoided by
1. using more training data
2. reducing features by effective feature selection
Underfitting and Overfitting
of models
Cont.
• Overfitting refers to a situation where the model has been designed in such a way that it
emulates the training data too closely.
• any specific deviation in the training data, like noise or outliers, gets embedded in the model.
• It adversely impacts the performance of the model on the test data.
• The target function, in these cases, tries to make sure all training data points are correctly
partitioned by the decision boundary.
• This exact nature is not replicated in the unknown test data set.
• The target function results in wrong classification in the test data set.
What is Underfitting?
• When a model has not learned the patterns in the training data well and is unable to
generalize well on the new data, it is known as underfitting.
• An underfit model has poor performance on the training data and will result in unreliable
predictions.
• As the algorithm learns over time, the error for the model on the training data reduces, as
well as the error on the test dataset.
• If you train the model for too long, the model may learn the unnecessary details and the
noise in the training set and hence lead to overfitting.
• In order to achieve a good fit, you need to stop training at a point where the error starts to
increase.
Overfitting
• Overfitting can be avoided by
1. using re-sampling techniques like k-fold cross validation
2. hold back of a validation data set
3. remove the nodes which have little or no predictive power for the given machine
learning problem.
• Both underfitting and overfitting result in poor classification quality which is reflected
by low classification accuracy.
Estimat
ors
• An estimator is a function or algorithm that tries to estimate a target variable from
given input features.
• Point Estimation is the attempt to provide the single best prediction of some quantity
of interest.
• A single parameter
• A whole function
Point estimator
• A point estimator is just a formula or function that gives you a best guess
for an unknown value (parameter) based on data.
• 78+85+90+82+75
μ^= -------------------------- =82
• 5
• So, μ̂ = 82 is your point estimate of the true average score.
Example 2:
Out of the past 30 days, it rained on 12 days.
Point estimate of the probability of rain:
p^=12/30=0.4
• Bias is the error occurring between the model’s predicted value and the actual value.
• It is the measurement of the model that how well it fits the data.
• Low Bias: Low bias value means fewer assumptions are taken to build the
target function. In this case, the model will closely match the training
dataset.
• High Bias: High bias value means more assumptions are taken to build the
target function. In this case, the model will not match the training dataset
closely.
To Reduce High
Bias
• Use a more complex model
• adding more features to train the dataset will increase the complexity of the model.
• Likelihood vs Probability
• Probability: data is random, parameters fixed
• Likelihood: data is fixed, parameters vary
• 𝑝 𝑥 ∣ 𝜃 viewed as a function of 𝜃
• Why MLE is Central in ML
• MLE underlies:
• Linear regression
• Logistic regression
• Neural networks
• Naive Bayes
• ℒ 𝜃 = ς𝑛𝑖=1 𝑝 𝑥𝑖 ∣ 𝜃
• Advantages
• Limitations
• Handles uncertainty
Incorporates prior knowledge
Prevents overconfidence
Works well with small data
• Limitations
• Computational cost
Approximation errors
Difficult posterior design •Data is scarce
•Interpretability is needed
• When to Use Bayesian Methods •Decisions are high-risk
•Uncertainty matters
Bias – variance trade-off
• In supervised learning, the class value assigned by the learning model built based on
the training data may differ from the actual class value.
• This error in learning can be of two types – errors due to ‘bias’ and error due to
‘variance’.
Errors due to ‘Bias’:
• While making predictions, a difference occurs between prediction values made by
the model and actual values/expected values, and this difference is known as bias
errors or Errors due to bias.
Cont.
• Errors due to bias arise from simplifying assumptions made by the model to make the
target function less complex or easier to learn.
• It is due to underfitting of the model.
• Parametric models generally have high bias
• These algorithms have a poor performance on data sets which are complex in
nature
• Underfitting results in high bias.
Errors due to ‘Variance’
• variance tells that how much a random variable is different from its expected value.
• Ideally the difference in the data sets should not be significant and the model trained
using different training data sets should not be too different.
• in case of overfitting, since the model closely matches the training data, even a small
difference in training data gets magnified in the model.
• A high variance model leads to overfitting.
• It Increase model complexities.
Combinations of
Bias-Variance
Combinations of Bias-Variance
4. High-Bias, High-Variance: With high bias and high variance, predictions are inconsistent
and also inaccurate on average.
• If the model is very simple with fewer parameters, it may have low variance and
high bias.
• If the model has a large number of parameters, it will have high variance and
low bias.
• It is required to make a balance between bias and variance errors, and this balance
between the bias error and variance error is known as the Bias-Variance trade-
off.
TYPES OF MACHINE LEARNING
• Machine learning can be classified into three broad categories.
• f(X) = Y
• Where X1, X2,….,Xn are inputs and Y1,Y2….,Yn are target outputs
• In the optimal case, the function will correctly determine the class labels for
unseen instances.
• A wide range of supervised learning algorithms are available, each with its
strengths and weaknesses. There is no single learning algorithm that works best
data, which is the answer that the algorithm should produce, attached.
• This is usually written as a set of data (xi, ti), where the inputs are xi, the targets are ti, and
the i index suggests that we have lots of pieces of data, indexed by i running from 1 to
• If we had examples of every possible piece of input data, then we could put them together
into a big look-up table, and there would be no need for machine learning at all.
• The thing that makes machine learning better than that is generalization: the algorithm
should produce sensible outputs for inputs that weren’t encountered during learning.
Cont.
Given:
– a set of input features X 1, … , X 𝑛
– A target feature 𝑌
– a set of training examples where the values for the input features and the
target features are given for each example
– a new example, where only the values for the input features are given
Predict the values for the target features for the new example.
– classification when Y is discrete
– regression when Y is continuous
Cont.
Supervised
Learning
X y
Input1 Output1 New Input x
Input2 Output2
Input3 Output3 Learning
Algorithm
Model
Input-n Output-n Output y
Example
Consider the following data regarding patients entering a clinic. The
data consists of the gender and age of the patients and each patient is
labeled as “healthy” or “sick”.
Cont.
• Based on this data, when a new patient enters the clinic, how can one predict whether
he/she is healthy or sick?
Classification
• In Classification, a program learns from the given dataset or observations and then
classifies new observation into a number of classes or groups Such as, Yes or No, 0 or
1, Spam or Not Spam, cat or dog, etc. Classes can be called as targets/labels or
categories.
Cont.
• There are mainly four types of classification tasks that one may come across, these are:
• Binary Classification
• Multi-Class Classification
• Multi-Label Classification
• Imbalanced Classification
• Binary Classification- This type of classification involves separating the dataset into two categories. It means
that the output variable can only take two values.
• The task of labeling an e-mail as "spam" or "not spam." The input variable here will be the content of the e-mail
that we are trying to classify. The output variable is represented by 0 for "not spam" and 1 for "spam”.
• Multi-Class Classification- In multi-class classification, the output variable can have more than two possible
values.
59
Cont.
Cont.
• If the image is of a round object, it is put under one category, while if the image
is of a triangular object, it is put under another category.
• In which category the machine should put an image of unknown category, also
called a test data in machine learning parlance, depends on the information it
gets from the past data, which we have called as training data.
• The most common unsupervised learning method is cluster analysis, which is used for
exploratory data analysis to find hidden patterns or grouping in data.
• In unsupervised learning, the objective is to take a dataset as input and try to find natural
groupings or patterns within the data elements or records.
• Therefore, unsupervised learning is often termed as descriptive model and the process of
unsupervised learning is referred as pattern discovery or knowledge discovery.
• One critical application of unsupervised learning is customer segmentation.
Cont
.
• Reasons for unsupervised learning:
Unsupervised learning is helpful for finding useful insights from the data.
Unsupervised learning is much similar as a human learns to think by
their own experiences, which makes it closer to the real AI.
Unsupervised learning works on unlabeled and uncategorized data which
make unsupervised learning more important.
In real-world, we do not always have input data with the corresponding
output so to solve such cases, we need unsupervised learning.
Types of Unsupervised Learning Algorithm
Unsupervised
Learning
X Clusters
Input1
Input2
Input3 Learning
Algorithm
Input-n
Clustering
• Different measures of similarity can be applied for clustering. One of
the most commonly adopted similarity measure is distance.
• Two data items are considered as a part of the same cluster if the
distance between them is less.
• In the same way, if the distance between the data items is high, the
items do not generally belong to the same cluster. This is also known as
distance-based clustering.
Cont
.
cont.
Cont.
• Unsupervised Learning algorithms:
• K-means clustering
• Hierarchal clustering
• Anomaly detection
• Neural Networks
• Apriori algorithm
• Disadvantages
• The result of the unsupervised learning algorithm might be less accurate as input data is
not labeled, and algorithms do not know the exact output in advance.
Reinforcement learning
• This continues till the machine is able to complete execution of the whole
task.
State st St+1
Agent Environment
Reward rt rt+1
Reinforcement
Learning
Action at
State st St+1
RLearner Environment
Reward rt rt+1
values
upda
Stat
Q-
te
e,
Policy
Action at
stat
acti
on
Be
e
st
State st St+1
User Environment
Reward rt rt+1
Building a Machine Learning
Algorithm
• Most ML algorithms follow a simple recipe:
Dataset + Model + Cost Function + Optimization Procedure
• 𝐽 𝑤 = 𝔼𝑥∼𝑝 ∣∣ 𝑥 − 𝑟 𝑥 𝑤 ∣∣22
data
• Model constraints: ∣∣ 𝑤 ∣∣= 1, 𝑟 𝑥 = 𝑤 ⊤ 𝑥 𝑤
• A recurring problem in machine learning is that large training sets are necessary for good
generalization, but large training sets are also more computationally expensive.
• The cost function used by a machine learning algorithm often decomposes as a sum over
training examples of some per-example loss function.
• Idea of Stochastic Gradient Descent
• However, they have not succeeded in solving the central problems in AI, such
as recognizing speech or recognizing objects.
• The curse of dimensionality arises in many places in computer science, and especially so in
machine learning
Local Constancy and Smoothness
Regularization
• The most widely used of these implicit “priors” is the smoothness prior or local constancy prior.
• This prior states that the function we learn should not change very much within a small region.
• Many simpler algorithms rely exclusively on this prior to generalize well, and as a result they fail to
scale to the statistical challenges involved in solving Ailevel tasks.
• we explain why the smoothness prior alone is insufficient for these tasks.
• There are many different ways to implicitly or explicitly express a prior belief that the learned function
should be smooth or locally constant.
• All of these different methods are designed to encourage the learning process to learn a function f∗ that
satisfies the condition
• From any given point, the manifold locally appears to be a Euclidean space. In everyday life,
we experience the surface of the world as a 2-D plane, but it is in fact a spherical manifold in
3-D space.
• In the example of the world’s surface as a manifold, one can walk north, south, east, or west.
• Although there is a formal mathematical meaning to the term “manifold,” in machine
learning it tends to be used more loosely to designate a connected set of points that can be
approximated well by considering only a small number of degrees of freedom, or
dimensions, embedded in a higher-dimensional space.
• In the context of machine learning, we allow the dimensionality of the manifold to vary
from one point to another.
• For example, a figure eight is a manifold that has a single dimension in most places but two
dimensions at the intersection at the center.
DEEP FEED FORWARD NEURAL NTWORK
M E PALANIVEL
Professor
SITAMS
Introduction
• In the last chapter we saw that while linear models are easy to understand and they can only
identify straight lines, planes, or hyperplanes.
• This is not usually enough, because the majority of interesting problems are not linearly
separable.
• We have pretty much decided that the learning in the neural network happens in the weights.
So, to perform more computation it seems sensible to add more weights.
• There are two things that we can do: add some backwards connections, so that the output
neurons connect to the inputs again, or add more neurons.
• 1. Input layer
• 2. Hidden layer
• 3. Output layer
• The inputs to the model corresponds to the features measured to each training tuple.
• The input are feed simultaneously into the units making up the input layer.
• They are then weighted and fed simultaneously to a second layer of hidden neurons
known as hidden layer.
• The output of hidden layer units can be input to another hidden layer and so on.
• The number of hidden layers is arbitrary.
• The weighted outputs of the last hidden layer are input to units making up the output layer, which
emits the DFFNN MODEL prediction output.
• The number of hidden layers in the above model is L-1 and one output layer, therefore we call it as L
layered DFFNN Model.
• The input layer is not counted because it serves only to pass the input values to the next layer.
• The network is feed-forward in that none of the weights cycles back to an input unit or to an output
unit of a previous layer
• The training the DFFNN Model consists of two phases:
• 1. Forward phase
• 2. Backward phase
Forward Phase
where g is called the activation function example, logistic, tanh, linear, etc.
The activation at the output layer is given by
f (x ) = h L (x ) = O (aL (x ))
where O is the output activation function (for example, softmax, linear, etc.)
N
Data: { x i , y i }i = 1
Model:
ŷ i = f (x i ) = O (W 3 g(W 2 g(W 1 x + b1 ) + b2 ) + b3 )
Parameters:
13/
9 θ = W 1 , .., W L , b1 , b2 , ..., bL (L = 3)
Algorithm: Gradient Descent with Back-
propagation (we will see soon)
O b j e c t i ve / L o ss/ E r ro r function: Say,
1 ΣN Σk
min (ŷ i j −y i j ) 2
N
i=1 j=1
❖ Gradient descent is an optimization algorithm that is used to find the weights that
minimize the cost function.
❖ Minimizing the cost function means getting to the minimum point of the cost
function.
❖ So, gradient descent aims to find a weight corresponding to the cost function’s
minimum point.
Navigating towards minimum cost function depends on 2 things
Direction - Gradient Descent or Gradient Ascent
Direction is determined by calculating the Gradients.
Specifically, we aim to find the negative gradient.
This is because a negative gradient indicates a decreasing slope.
A decreasing slope means that moving downward will lead us to the minimum point.
Step Size – Learning Rate
Step Size is determined by Learning Rate.
The learning rate is a tuning parameter that determines the step size at each iteration of gradient
descent.
1t determines the speed at which we move down the slope.
❖ Let’s say you are playing a game where the players are at the top of a mountain, and they are
asked to reach the lowest point of the mountain. Additionally, they are blindfolded. So, what
approach do you think would make you reach the lake?
❖ The best way is to observe the ground and find where the land descends. From that position,
take a step in the descending direction and iterate this process until we reach the lowest point.
Using the initial weight and the gradient and learning rate, we can determine the subsequent
weights.
From the graph of the cost function, we can see that:
2. Then, we take a step down and obtain a new weight using the gradient and learning
rate. With the gradient, we can know which direction to navigate. We can know the
step size for navigating the cost function using the learning rate.
3. We are then able to obtain a new weight using the gradient descent formula.
4. We repeat this process until we reach the minimum point of the cost function.
5. Once we’ve reached the minimum point, we find the weights that correspond to the
minimum of the cost function.
• Algorithm: gradient descent()
t ← 0;
wt+ 1 ← wt −η∇wt ;
bt+ 1 ← bt −η∇bt ;
end
The DFFNN Model in Practice
• We apply these ideas to using the MLP to find solutions to four different types of
problem: regression, classification, time-series prediction, and data compression.
• For the MLP with one hidden layer there are (L + 1) X M + (M + 1)X N weights,
where L, M, N are the number of nodes in the input, hidden, and output layers,
respectively.
• The extra +1s come from the bias nodes, which also have adjustable weights.
• This is a potentially huge number of adjustable parameters that we need to set during
the training phase.
• the more training data there is, the better for learning, although the time that the
algorithm takes to learn increases.
• Number of Hidden Layers
• There are two other considerations, which is the choice of the number of hidden nodes, and the
number of hidden layers.
• We can use the back-propagation algorithm for a network with as many layers as we like, although it
gets progressively harder to keep track of which weights are being updated at any given time.
• The training of the MLP requires that the algorithm runs over the entire dataset many times, with the
weights changing as the network makes errors in each iteration.
• Setting some predefined number N of iterations, and running until that is reached runs the risk that
the network has overfitted by then, or not learnt sufficiently, and only stopping when some
predefined minimum error is reached might mean the algorithm never terminates, or that it overfits.
• Using both of these options together can help, as can terminating the learning once the error stops
decreasing.
• If we plot the sum-of-squares error during training, it typically reduces fairly quickly during the first
few training iterations, and then the reduction slows down as the learning algorithm performs small
changes to find the exact local minimum.
• We don’t want to stop training until the local minimum has been found, but, as we’ve just
discussed, keeping on training too long leads to overfitting of the network.
• This is where the validation set comes in useful. We train the network for some predetermined
amount of time, and then use the validation set to estimate how well the network is generalizing.
At some stage the error on the validation set will start increasing again, because the network has
stopped learning about the function that generated the data, and started to learn about the noise that is
in the data itself as shown in Figure .
At this stage we stop the training. This technique is called early stopping.
Back Propagation Algorithm
• Back Propagation algorithm is a learning or Training algorithm works on Deep
Feed Forward Neural Network model to solve Classification or Prediction
problems.
2. Training phase :
i) Forward phase :
For each training tuple or input vector X in D , propagate the inputs in the forward
Hidden layers : for each Hidden layer unit or node j , Compute the net input of neuron j
with respect to the previous layer
𝐼𝑗 = 𝑤𝑖𝑗 𝑂𝑖 + 𝜃𝑗
𝑖
• Output layer : For Output layer unit or node j , Compute the net input of
neuron j with respect to the previous layer
𝐼𝑗 = 𝑤𝑖𝑗 𝑂𝑖 + 𝜃𝑗
𝑖
• Compute the activation or output of each neuron j in the Output layer using the
sigmoid activation function
1
Oj = f (Ij) =
1 + 𝑒 −𝐼𝑗
• Backward Phase:
• Compute Error at each neuron j in the output layer
• We will take a set of samples generated by a simple mathematical function, and try to learn
the generating function (that describes how the data was made) so that we can find the values
of any inputs, not just the ones we have training data for.
• We can now train an MLP on the data. There is one input value, x and one output value t,
so the neural network will have one input and one output. Also, because we want the output
to be the value of the function, rather than 0 or 1, we will use linear neurons at the output.
We don’t know how many hidden neurons we will need yet, so we’ll have to experiment to
see what works.
• Before getting started, we need to normalise the data using the method and then separate the
data into training, testing, and validation sets.
Classification with the DFFNN Model
• Using the DFFNNM for classification problems is not radically different once the output
encoding has been worked out.
• The inputs are easy: they are just the values of the feature measurements (suitably
normalized). There are a couple of choices for the outputs. The first is to use a single linear
node for the output, y, and put some thresholds on the activation value of that node.
• However, this gets impractical as the number of classes gets large, and the boundaries are
artificial; what about an example that is very close to a boundary, say y = 0.5?
• We arbitrarily guess that it belongs to class C3, but the neural network doesn’t give us any
information about how close it was to the boundary in the output, so we don’t know that this
Cont.
• A more suitable output encoding is called 1-of-N encoding. A separate node is used to
represent each possible class, and the target vectors consist of zeros everywhere except for
in the one element that corresponds to the correct class, e.g., (0, 0, 0, 1, 0, 0) means that
the correct result is the 4th class out of 6. We are therefore using binary output values (we
want each output to be either 0 or 1).
• Once the network has been trained, performing the classification is easy:
• simply choose the element yk of the output vector that is the largest element of y (in
mathematical notation, pick the yk for which yk > yj j = k; means for all, so this
statement says pick the yk that is bigger than all other possible values yj).
• This generates an unambiguous decision, since it is very unlikely that two output neurons
will have identical largest output values.
• This is known as the hard-max activation function (since the neuron with the highest
activation is chosen to fire and the rest are ignored).
• An alternative is the soft-max function, which and which has the effect of scaling the output
of each neuron according to how large it is in comparison to the others, and making the total
output sum to 1.
• So if there is one clear winner, it will have a value near 1, while if there are several P values
that are close to each other, they will each have a value of about 1 , where p is the number of
output neurons that have similar values.
Case study
• A research team is developing a neural network model named LeafYield, designed to
predict the crop yield (in kg) from leaf-level features extracted via sensors and imaging.
Each sample contains 5 normalized numerical features: Leaf length, Leaf width, Color
intensity, Water content, Light absorption level. The Deep Feed forward Neural Network as
follows and the neurons in the hidden layer 1, Hidden layer 2 and output layer are having
sigmoid activation function
•
• Given the input vector x= [0.1,0.5,0.3,0.7,0.2]T and
W1 = 1 0101
0 1010
1 -1 0 1 1
01110
• Find the pre-activation vector for hidden layer 1, Apply sigmoid activation to the above
vector obtained find the output from the hidden layer1 , Find the pre-activation vector for
hidden layer 2, Apply sigmoid activation to the above vector obtained find the output from
the hidden layer 2 and Find the pre-activation vector for output layer , Apply sigmoid
activation to the above vector obtained find the output from the Output layer.
Case Studies
Case Study 1: Predicting Student Performance using Supervised Learning
Problem: A university wants to predict whether a student will pass or fail based on previous academic records.
Concepts Used: Supervised Learning, Bias and Variance, Hyperparameters, Validation Set
Explanation:
The university collects historical student data including: Attendance, Assignment scores ,Internal exam marks ,Study hours
A supervised learning model is trained using labeled data (Pass/Fail).
The dataset is divided into:
Training set – to train the model
Validation set – to tune hyperparameters
Test set – to evaluate performance
During training:
If the model is too simple → Underfitting
If the model memorizes training data → Overfitting
Hyperparameters such as learning rate and model complexity are adjusted using the validation set.
Outcome:
The system predicts students who may need academic support.
Case Study 2: Customer Segmentation using Unsupervised Learning
Problem: A retail company wants to group customers based on their buying behavior.
Concepts Used: Unsupervised Learning, Feature analysis, Data clustering
Explanation:
Customer data includes: Purchase frequency, Amount spent, Product categories
Since there are no predefined labels, the company uses unsupervised learning algorithms
such as clustering.
The algorithm automatically identifies groups like:
High-value customers
Occasional buyers
Budget shoppers
Outcome:
The company can design targeted marketing strategies.
Applications:
Marketing personalization
Customer analytics
E-commerce recommendations
• Case Study 3: Spam Email Detection using Bayesian Statistics
• Problem: Email providers must automatically identify spam emails.
• Concepts Used: Bayesian Statistics, Maximum Likelihood, Probability distributions
• Explanation:
Each word in an email is treated as a feature.
• The system calculates:
• Probability(Spam | Email Content)
• Using Bayes’ Rule, the classifier evaluates whether the email is spam or legitimate.
• Training involves estimating probabilities using Maximum Likelihood Estimation (MLE)
from historical email data.
• Outcome:
Emails are automatically filtered into Spam or Inbox.
• Applications:
• Gmail spam filtering
• Email security systems
Case Study 4: Product Recommendation using Stochastic Gradient Descent
Problem: An online shopping platform wants to recommend products to users.
Concepts Used: Stochastic Gradient Descent (SGD) , Gradient-based optimization,
Hyperparameter tuning
Explanation:
The system learns user preferences based on: Previous purchases , Product ratings , Browsing
history
A recommendation model is trained using SGD, which updates model parameters using small
batches of data.
Advantages:
Faster training
Efficient for large datasets
Hyperparameters like: Learning rate, Batch size are tuned using validation data.
Outcome:
Users receive personalized product suggestions.
Applications:
Amazon product recommendations
E-commerce personalization
• Case Study 5: Solving the XOR Problem using Deep Feedforward
Networks
• Problem: Early neural networks failed to learn the XOR logical function.
• Explanation:
The XOR function:
Input 1 Input 2 Output
0 0 0
0 1 1
1 0 1
1 1 0
• A single-layer perceptron cannot solve XOR because it is not linearly
separable.
• Outcome:
The neural network correctly models the XOR function.
• Importance:
This example demonstrated the need for multi-layer neural networks, which
led to modern deep learning.
Case Study 6: Handwritten Digit Recognition using Backpropagation
Problem: Banks need to automatically recognize handwritten digits on cheques.
Concepts Used: Deep feedforward networks , Backpropagation ,Gradient-based learning
Explanation: A neural network is trained on thousands of digit images.
Training process:
Input image passes through layers (forward propagation).
The model predicts the digit.
The error between predicted and actual value is computed.
Backpropagation calculates gradients.
Weights are updated using gradient descent.
Hidden units learn features like: Edges ,Curves, Digit shapes
Outcome:
The model accurately recognizes handwritten numbers.
Applications:
Bank cheque processing
Postal code recognition
Document digitization
Case Study 7: Image Recognition Challenges Motivating Deep Learning
Problem: Traditional machine learning struggled with complex tasks such as image
recognition.
Challenges: High-dimensional data, Feature engineering difficulty, Large datasets
Solution:
Deep learning models automatically learn hierarchical features.
Example:
In image recognition:
Layer 1 → detects edges
Layer 2 → detects shapes
Layer 3 → detects objects
This hierarchical learning makes deep learning effective for complex tasks.
Applications:
Self-driving cars
Medical image analysis
Face recognition
Questions
PART –A 2 Mark Questions
1. Define Machine Learning.
• Differentiate between Supervised Learning and Unsupervised Learning techniques and apply
appropriate algorithms to different types of datasets.
• Analyze and implement optimization techniques, particularly Stochastic Gradient Descent and
gradient-based learning, for training machine learning models.
• Design and understand the structure of Deep Feedforward Neural Networks, including hidden
units, architecture design, and learning nonlinear functions such as XOR.
• Apply Backpropagation and other differentiation algorithms to train neural networks and
improve model performance.
Standard Quote
• “Artificial intelligence is the new electricity transforming every industry.”
- Andrew Ng
• “Data is the new oil, but machine learning is the engine that makes it valuable.”
• “Every dataset tells a story, and machine learning helps us understand it.”
• - Ian Goodfellow