What is Ar ficial intelligence, Machine Learning, Deep Learning
Types of ML: Supervised, unsupervised, reinforcement learning
In supervised learning, the
algorithm is trained on a labeled
dataset, where each example in the
dataset is paired with the correct
output. The model uses this to learn
the rela onship between inputs and
outputs. It's like learning with a
teacher who provides the answers.
-
-
Predic ng house prices
based on features like size,
loca on, and age.
Handwri ng recogni on
where the system learns to
iden fy le ers and numbers
from labeled examples
Logis c Regression
Decision Trees
Random Forests
k-Nearest Neighbors (k-NN)
Neural Networks (Deep
Learning)
Unlike supervised learning,
unsupervised learning algorithms
work with unlabeled data. The
model tries to understand the
structure of the data without any
explicit feedback on what is right or
wrong. It's akin to self-learning
where the system tries to find
pa erns and rela onships on its
own.
- Clustering news ar cles into
different topics based on
content without pre-defined
categories.
- Anomaly detec on in
network traffic to iden fy
unusual pa erns indica ve
of security breaches.
- -Means Clustering
- Hierarchical Clustering
This approach involves learning to
make decisions through trial and
error. An agent makes decisions,
observes the outcomes (rewards or
penal es), and adjusts its ac ons
accordingly. It's similar to learning a
skill through prac ce and feedback.
-
-
A chess program that
improves by playing games
against itself and learning
from wins and losses.
Autonomous vehicles
learning to navigate roads
and traffic effec vely
through trial and error.
Commented [ADI1]: Examples
Commented [ADI2]: Classifiers for each learning method
History, Why now?
Advances in Technology: Significant advancements in hardware, such as GPUs (Graphics Processing Units) and TPUs
(Tensor Processing Units), have made it possible to train and run more complex AI models at a much faster pace.
This has enabled the development of more sophis cated AI applica ons.
Data Availability: The digital age has generated massive amounts of data, which is a crucial ingredient for training AI
models. The availability of large datasets has facilitated the training of machine learning algorithms, making AI
applica ons more powerful and accurate.
Algorithms and Models: The development of new machine learning algorithms and the refinement of exis ng ones,
such as deep learning techniques, have led to remarkable improvements in AI capabili es. Deep neural networks, in
par cular, have achieved remarkable success in various applica ons, from image recogni on to natural language
processing.
Industry Adop on: Many industries have recognized the poten al benefits of AI, such as increased efficiency, cost
reduc on, and improved decision-making. As a result, there has been a surge in AI adop on across sectors like
healthcare, finance, retail, manufacturing, and more.
Accessibility of Tools and Frameworks: Open-source AI frameworks and libraries, like TensorFlow and PyTorch, have
made it easier for developers and researchers to work with AI technologies. These tools have lowered the entry
barrier for AI development.
Investment and Research: Governments, corpora ons, and venture capitalists have been inves ng heavily in AI
research and development. This influx of resources has accelerated progress in AI and has led to innova ons in the
field.
Real-World Applica ons: AI is no longer just a theore cal concept; it is being applied to real-world problems with
tangible benefits. Examples include virtual assistants, autonomous vehicles, healthcare diagnos cs, fraud detec on,
and recommenda on systems.
ML Pipeline, Data processing, training, evalua on, deployment
This step involves
preparing the data for the
ML algorithm. It o en
includes cleaning
(removing irrelevant or
erroneous data),
normalizing (scaling
numerical data), encoding
(conver ng categorical
data into a machinereadable format), and
spli ng the dataset into
'Training' and 'Test'
datasets. The datasets
contain features
d
xi∈R and labels yi∈R,
where d is the
dimensionality of the
features, and n is the
number of samples.
This part of the pipeline
involves choosing the ML
algorithms that will learn
from the data. The
example lists common
algorithms like Logis c
Regression, Random
Forests, Gradient
Boos ng, and Neural
Networks. These
algorithms have different
strengths and are suitable
for different types of data
and problems.
This is the outcome of the
training process. The
algorithm uses the
training data to learn and
generate a model that can
make predic ons.
The test dataset is used to
evaluate the performance
of the model. This is an
unseen dataset for the
model, and its
performance on this
dataset provides an
es mate of how well the
model will perform on
real-world data.
A er the model has been
trained, it can produce
outputs when new data is
fed into it. These outputs
are the predic ons or
classifica ons made by the
model
This represents new data
that the model has never
seen before. It is used for
the final predic ons and
represents real-world
applica on. Finally, the
model is used to make
predic ons on the
unseen/new dataset. This
is where the model proves
its prac cal u lity.
Data, object / samples, a ribute / features, sepal, petal
o en used in classifica on tasks where the goal is to predict the species of an Iris flower based on the
measurements of its petals and sepals
1. Data Defini ons:
Data: Refers to a collec on of objects and their corresponding a ributes.
Data Object/Samples: These are individual items or instances in the dataset. Each object is an abstract or real
representa on of a concept, such as an Iris flower in this case.
Data A ribute/Features: These are the proper es or characteris cs of an object. In this context, they refer to the
measurements of the Iris flowers, such as sepal length and petal width.
2. Dataset Table:
The table contains rows (samples) and columns (features and a label).
Each row represents a sample, an Iris flower in this context.
Columns under "Features" represent the a ributes of each flower: Sepal Length, Sepal Width, Petal Length, and
Petal Width.
The final column, "Label", indicates the class of Iris flower, which can be one of three species: Iris-setosa, Irisversicolor, or Iris-virginica.
3. Features and Labels:
Features (highlighted in blue): These are the input variables of the dataset, which in this case are the dimensions of
the sepals and petals of Iris flowers. These measurements are used by machine learning models to learn pa erns.
Labels/Classes (highlighted in pink): This is the output variable, also known as the target or class. It is the species of
the Iris flower that the model will a empt to predict based on the features.
4. Samples and Dimensions:
n Samples: Indicates the number of individual data points in the dataset. In this example, there are 150 samples.
d Dimensions, Measurements: Represents the number of features or dimensions in the dataset. Here, there are 4
dimensions corresponding to the physical measurements of the flowers.
Data types, binary, symmetric, asymmetric, nominal, ordinal, con nuous, ra o, discrete, interval
Symmetric Binary:
- In symmetric binary encoding, both 0s and 1s are represented by two dis nct voltage levels, which are
typically symmetric around a reference point.
- This means that there are two equally spaced voltage levels: one for encoding 0 (low voltage) and one for
encoding 1 (high voltage).
- The advantage of symmetric binary is that it is rela vely simple to implement and is less suscep ble to
certain types of noise and interference.
- An example of symmetric binary encoding is Non-Return-to-Zero (NRZ) encoding.
Asymmetric Binary:
- In asymmetric binary encoding, 0s and 1s are represented by two different voltage levels, but these levels are
not necessarily symmetric around a reference point.
- This means that the voltage level represen ng 0 may be different from the voltage level represen ng 1.
- Asymmetric binary encoding can be used to improve the reliability of data transmission, as it can make it
easier to dis nguish between 0s and 1s, even in the presence of noise or interference.
- An example of asymmetric binary encoding is Bipolar Encoding, where 0 is represented by zero voltage, and
1 is represented by a posi ve or nega ve voltage level.
Data processing, missing values, ignoring tuples, manual values, a ribute mean, global constant, probable value
Ignoring Tuples: inten onally excluding or omi ng certain rows or observa ons (tuples) from your dataset during
the data processing or analysis phase
Global Constant: refers to a fixed value or parameter that remains the same throughout the en re analysis or
processing pipeline
Data standar sa on, z-normalisa on, original data, centered data, normalised data
The goal of Z-Normaliza on is to scale the features so that they have the proper es of a standard normal
distribu on with a mean of 0 and a standard devia on of 1.
Original Data
Centered Data
Normalised Data
This is the star ng dataset with
This step involves centering the data A er centering the data, the next
N samples, each with
around the mean, which is
step is to scale it by its standard
d dimensions. The data points are
calculated as:
devia on, which is calculated as:
sca ered with their own mean
(see first formula)
(see first formula)
(average) and spread (variance).
Each data point xi is then
Each centered data point is then
transformed by subtrac ng the
divided by the standard devia on σ
mean μ from it:
to normalize the data.This step
x=xi −μ
ensures that the standard devia on
of the dataset is 1
Purpose:
To align the center of the data (its
Purpose:
mean) to the origin (0) of the
To scale the variability of the data so
feature space.
that each feature contributes
Comparability: Algorithms that are
equally to the final model
sensi ve to the magnitude of the
Equal Variance: By scaling the
features (like K-Nearest Neighbors)
features to have unit variance, it
can be biased towards the features
prevents features with larger
with larger scales. Centering ensures variance from domina ng the
that each feature contributes
objec ve func on of the machine
equally to the distance calcula ons. learning model.
Op miza on Efficiency: For
Stability and Numerical Precision:
algorithms that use gradient
Algorithms can become numerically
descent (like neural networks),
unstable if the features have very
having features centered around
different scales. It helps to mi gate
zero can help in achieving faster
this risk.
convergence, as it ensures that the
Learning Rate Tuning: Having
gradient descent starts at the same features on the same scale allows
scale for all features.
for a single learning rate to be set
more easily.
Min Max Scaling
This is the dataset before any scaling
is applied. It contains
n samples each with d dimensions
or features
Each data point xi has the minimum
value of its feature xmin substracted
from it:
xi=xi−xmin
Purpose: This shi s the data so that
the minimum value of each feature
is aligned at 0
A er subtrac ng the minimum
value, each data point
x1 is divided by the range of its
feature (which is xmax - xmin)
Purpose:
This scales the data to fit within the
range of 0 to 1. A er applying
min/max normalisa on, the
minimum value of each feature will
be 0, and the maximum value will
be 1.
Reasons for Min-Max Scaling:
1. To put all features on the same scale: This is especially important for algorithms that use distance
calcula ons (like K-Nearest Neighbors) or gradient descent (like in neural networks), where features on larger
scales can dispropor onately influence the model.
2. To ensure consistency in parameter updates: When using op miza on algorithms, features with larger
ranges can cause larger changes in the parameter updates, which can make the learning process unstable or
inefficient.
3. To improve convergence: Algorithms converge faster when features are on a similar scale because the shape
of the op miza on problem becomes more "spherical", and gradient descent can take more straigh orward
paths to the minimum.
However, Min-Max Scaling can be sensi ve to outliers because the presence of a very large or small value as the min
or max can skew the scaling for all the other values. This is where other methods like Z-Normaliza on (or
standardiza on) can be preferable, especially if the data contains outliers
Visualisa on, histofram, distribu on, bin-size, bin-boundaries, outliers
Data sampling
Allows researchers to efficiently and effec vely gather data, reduce biases, make inferences about popula ons, and
address resource constraints while upholding ethical considera ons
Simple Random Sampling:
Is a method where each individual in the popula on has an equal chance of being selected for the sample. This is
typically achieved through random selec on techniques like drawing lots, using random number generators, or using
random sampling so ware.
Example: If you have a list of 1,000 students in a school, you can assign each student a number and then use a
random number generator to select, say, 100 students. This ensures that every student has an equal chance of being
included in the sample.
Systema c Random Sampling:
Involves selec ng every "kth" element from a list or popula on. The first element is randomly chosen, and then
every "kth" element a er that is included in the sample.
Example: If you have a list of 1,000 employees and you want to select a sample of 100, you could randomly select a
star ng point (e.g., employee #37) and then choose every 10th employee from there (i.e., employee #47, #57, #67,
and so on).
Stra fied Random Sampling:
Involves dividing the popula on into dis nct subgroups or strata based on certain characteris cs (e.g., age, gender,
loca on) and then randomly sampling from each stratum propor onally to its size or importance.
Example: If you are conduc ng a survey in a city and you want to ensure that your sample represents different age
groups, you might divide the popula on into strata (e.g., 18-24, 25-34, 35-44, and so on). Then, you randomly
sample from each stratum based on its propor on in the overall popula on.
Cluster Random Sampling:
Involves dividing the popula on into clusters (e.g., geographical regions, schools, households) and then randomly
selec ng some of these clusters. You then collect data from all individuals within the selected clusters.
Example: Suppose you want to study students' performance in a country. Instead of sampling individual students,
you might randomly select a few schools as clusters and then collect data from all students within those selected
schools.
ML Algorithm
Visualisa on of various machine learning algorithms applied to a two-dimensional dataset for both classifica on and
regression tasks.
There are different types of mapping func ons f(), which take inputs from a real-valued vector space Rd×R to real
numbers = R. Each func on f() has its own set of assump ons and parameters.
For classifica on tasks, the focus is on how the decision boundary between different classes is defined.
For regression tasks, the emphasis is on predic ng con nuous values.
Algorithm Visualiza ons:
Below the header, there are mul ple panels, each represen ng a different machine learning algorithm's approach to
classifica on or regression.
Row 1: Classifica on Tasks
The first row of panels shows how each algorithm creates a decision boundary for a classifica on problem, where
the goal is to separate two classes of points (likely represented by two different colors, such as blue and red).
Algorithms included:
1. Nearest Neighbors: This method uses proximity to classify points, with the decision boundary being defined by
the closeness to the nearest points of each class.
2. Linear SVM (Support Vector Machine): This method finds a linear boundary that maximizes the margin between
the two classes.
3. RBF SVM (Radial Basis Func on Support Vector Machine): A more complex SVM that uses a radial basis func on
to create a non-linear decision boundary.
4. Decision Tree: Uses a tree-like model of decisions and their possible consequences to classify data points.
5. Random Forest: An ensemble of decision trees to improve the classifica on accuracy.
6. Neural Net: A simplified representa on of a neural network, which uses layers of neurons to learn complex
decision boundaries.
Row 2 and Row 3: Regression Tasks
The second and third rows seem to illustrate regression tasks, where the goal is to predict a con nuous value rather
than a class. The panels might show how well each algorithm fits a curve to the data points.
Each algorithm panel appears to include a subset of data points used for training, the fi ed model or decision
boundary, and some performance metric (possibly accuracy for classifica on and error for regression).
K-NN nearest neighbor
Input: The input is described as a dataset D consis ng of pairs (xi, yi) where x1 is a feature vector in a d-dimensional
space Rd, and yi is the corresponding label or output in real numbers R. There is also a men on of a number k of
neighbors, which is a parameter of the k-NN algorithm.
Output: The output is the sample predic ons yi or each sample xi in the dataset D.
Classifica on: This is about predic ng the class of an unknown data point.
Regression: This refers to capturing the rela onships between input variables and the output.
Visual Representa on Sec on:
The diagram includes a ques on mark at the center, surrounded by a circle that encompasses several nearest points.
These points are of different colors, indica ng their class labels (e.g., pink for diabetes and blue for healthy).
The circle represents the boundary within which the k-nearest neighbors of the ques on-marked point are located.
In k-NN, the class of the unknown point is predicted based on the majority class of its nearest neighbors.
The mathema cal nota on at the bo om right corner of the diagram, reiterates the dataset's structure with feature
vectors and labels.
Overview Sec on:
It men ons that k-NN uses distance metrics to compute the distances among data samples.
The predic ons are based on a majority vo ng scheme among the k-nearest neighbors.
For classifica on tasks, the algorithm uses the dominant label (the most frequent label) within the k-neighborhood
to make a predic on.
For regression tasks, the algorithm uses the mean or median value within the k-neighborhood to make a predic on.
Diagram Sec on:
An unknown data point (marked with a ques on mark) is the query point for which the algorithm is supposed to
make a predic on.
Arrows (black lines) are drawn from the query point to its nearest neighbors, indica ng the process of finding the knearest neighbors. In this instance, it appears that six neighbors are healthy (blue) and five have diabetes (pink).
For classifica on, the majority vo ng would determine the class of the query point. Since there are more blue points
(6) than pink (5), the algorithm would classify the query point as "Healthy" under a simple majority vote.
The formula below the diagram, represents the dataset consis ng of feature vectors xi and labels yi.
Algorithm:
Input: A dataset D is given, consis ng of pairs (xi, yi)where xi is a feature vector in Rd and yi is the corresponding label
or output. There is also a specified number of neighbors k.
Output: The output is the sample predic ons yi.
Goal: The goal is to compute the set of nearest neighbors Sx to perform classifica on or regression tasks.
Steps for the k-NN Algorithm:
1. For every sample xi in the dataset D, compute and record the distance between the query sample X and every
sample xi: dist(xi X).
2. Sort the samples xi by their distances in ascending order.
3. Assign the top k-samples onto the set of nearest neighbors:Sx.
For Classifica on Tasks:
Return the dominant label/class, which is computed as Yi = arg max of the average label occurrence within the kneighbors, given by (formula), where l is a par cular label.
Classifica on Formula explained:
Regression Formula explained:
Hpyerparameters
k = 1:
This panel shows a situa on where the k-value is set to 1, meaning the algorithm only considers the closest neighbor
for making predic ons.
These are the consequences:
Overfi ng: The model is likely to fit the training data too closely, capturing noise as if it were a significant part of
the pa ern.
Sensi ve to noise: With only one nearest neighbor, the predic on is en rely dependent on the nearest data point,
which could be an outlier or have some noise.
Increasing k reduces noise sensi vity: By considering more neighbors, the model can average out the noise among
mul ple data points.
Ideal Se ng:
This panel suggests a balanced approach to choosing k. The circle encompasses a moderate number of neighbors.
The advice is to choose a k-value that is neither too large nor too small, balancing the trade-off between overfi ng
and underfi ng.
k → n:
Here, the k-value approaches the total number of data points n, meaning the model considers a very large
neighborhood.
These are the consequences:
Underfi ng: The model becomes too general, failing to capture the nuances in the data.
Decreasing k allows to capture finer details: By choosing a smaller k, the model can pay more a en on to the local
structure of the data, which can be important for making accurate predic ons.
The graph typically shows that a very small k-value leads to low accuracy due to overfi ng (high variance), and a
very large k-value also leads to low accuracy due to underfi ng (high bias). There is an op mal range of k-values
that provide the best accuracy, demonstra ng the trade-off and the need to tune k appropriately.
k-NN is a type of supervised learning algorithm that is used for classifica on and regression tasks. In supervised
learning, the algorithm is trained on a labeled dataset, which means each training example is paired with an output
label.
Classifica on: For classifica on, k-NN uses a majority vo ng system. When predic ng the class of a new sample, the
algorithm looks at the k closest labeled samples – the k-nearest neighbors – and assigns the new sample to the class
that has the majority among those neighbors.
Regression: For regression tasks, k-NN predicts the value for a new point based on the average of the values of its knearest neighbors. This means the output is computed as the mean (or some mes median) of the known values of
the nearest neighbors.
Selec on of the k-Value:
The choice of k (the number of nearest neighbors to consider) is cri cal in k-NN. A small value of k can make the
algorithm overly sensi ve to noise in the dataset, leading to overfi ng and erra c boundaries. Conversely, a larger k
provides smoothing that reduces the impact of noise but can lead to underfi ng, where the model is too simplis c
and fails to capture important nuances in the data.
Feature Normalisa on:
Feature normalisa on is the process of scaling input features so that they have a similar range. This is important in kNN because the algorithm uses distance calcula ons to determine the nearest neighbors. If one feature has a very
large range compared to others, it can dominate the distance calcula on, skewing the results. Normalizing features
to a similar range ensures that each feature contributes equally to the distance calcula ons.
Advantages:
The algorithm is straigh orward and intui ve, making it easy to understand and implement.
It doesn't make any strong assump ons about the form of the data, giving it flexibility to capture actual pa erns.
Disadvantages:
The algorithm can be computa onally intensive, par cularly as the size of the dataset grows, because it requires
calcula ng the distance from the query point to every other point in the dataset. High-dimensional datasets can
exacerbate this issue (a phenomenon o en referred to as the "curse of dimensionality"), as compu ng distances in
many-dimensional spaces can become less meaningful due to the way distances are distributed in high-dimensional
spaces.
Linear Regression
The goal of the process is described in two parts:
Data: It starts by sta ng that there is a dataset D comprising pairs of (xi, yi)where each xi is a feature vector in a highdimensional space Rd, and yi is the corresponding output value.
Func on: The aim is to find a func on fw() that maps the high-dimensional feature vectors xi to output values yi in
real numbers R, essen ally learning the rela onship between the independent variables xi and the dependent
variable yi.
Data (X):
This part shows a sca er plot within a cylindrical container, symbolizing the collected data points in the feature
space. Each point represents an observa on with its specific features and associated outcome.
Algorithm Sec on:
The middle part of the image represents the algorithm as a neural network structure, indica ng that a complex
model like a neural network is used to learn the mapping from features X to the target Y.
It suggests that the func on fw() is parametrized by weights, and it will output a predic on ŷ.
Predic on (ŷ) Sec on
It depicts a graph with a line of best fit through data points, indica ng the model's learned rela onship between the
features and the target variable.
This graph represents the outcome of the modeling process, where new data points can be input into the func on
fw(), and the output ŷ gives the predicted values.
In summary, the image outlines a typical machine learning workflow where a model is trained to understand the
underlying pa erns in a dataset. The model learns from the provided features to predict outcomes for new data.
The predic on graph suggests a linear regression model, although the algorithm representa on seems more
complex, implying the use of a more sophis cated model like a neural network. This might indicate that the model
can capture not only linear but poten ally nonlinear rela onships as well.
The dataset D consists of pairs (xi, yi)where xi is a feature vector and yi is the corresponding target value.
The goal is to find a linear func on fw() that models the rela onship between the feature vectors xi and the target
values yi. The subscript w indicates that the func on is parameterized by weights.
Linear Func on Equa on:
The linear func on fw(xi) is given by the equa on *formula* , where:
W0 is the bias term or intercept.
Wd are the weights or coefficients corresponding to each feature d in the feature vector xi.
Xi,d is the value of feature d for the i-th data point.
Expanded Equa on:
The equa on is also expanded to show the computa on for a feature vector with d features: w0+w1xi,1+w2xi,2+...+wd
xi,d
It's also expressed in vector nota on as w0+wT xi where w is the weight vector excluding the bias, and wT xi
represents the dot product between the weight vector and the feature vector.
Graphical Representa on
A graph is shown depic ng a line of best fit through a sca er plot of data points. This line represents the predic ons
of the linear regression model.
The func on f (x) = w0+w1xi,1+w2xi,2+...+wd is annotated on the graph, summarizing the linear rela onship that the
model has learned from the data.
In essence, this image summarizes how a linear regression model is formulated, parameterized, and used to predict
con nuous target values based on weighted combina ons of input features. It emphasizes the mathema cal
founda ons of the linear regression algorithm in machine learning.
Loss func on
The first graph shows a sca er plot with a linear line running through the data points. This line represents a simple
linear regression model trying to fit the data.
The second graph also shows a sca er plot with a regression line, but it includes ver cal lines from each data point
to the regression line, indica ng the residual errors for each point.
Linear Model Predic on:
The linear model's predic on ŷi is given by the linear equa on ŷi = w0+w1xi where:
ŷi is the predicted value.
w0 is the bias or intercept term.
w1 is the weight or coefficient associated with the feature xi
Residual Term:
The residual term ei is introduced, which measures the difference between the observed value yi and the predicted
value ŷi.
The residual error for each data point is calculated ei = yi - ŷi or ei = yi - w0+w1xi.
This error term is what the loss func on seeks to minimize. In most cases, the sum of the squared residuals (known
as the least squares method) is used as the loss func on to train the model.
Addi onal Annota ons:
The second graph might be annotated with the true unknown func on (the actual rela onship between x and y and
the es mated func on from the model.
There may also be a dis nc on made between the es mated values (predic ons from the model) and the observed
values (actual data points).
In summary, the image likely illustrates the process of linear regression model fi ng, highligh ng the role of the loss
func on in quan fying how well the model's predic ons match the observed data. By minimizing the loss func on
during training (usually through a process like gradient descent), the model's parameters w0 and w1 are adjusted to
find the best possible line that fits the given data.
Residual Error Calcula on:
The residual error ei for each data point in the dataset D is calculated. This error represents the difference between
the observed value yi and the predicted value ŷi from the linear regression model.
The predicted value ŷi is given by the linear model ŷi = w0 + wTxi, where w0 is the bias term and w is the vector of
weights associated with the features x1.
Least-Squared Error (LSE): This func on sums the squares of the residuals. It's the same as the Mean-Squared Error
(MSE) but without the division by the number of data points n.
Mean-Squared Error (MSE): This is the average of the squares of the residuals. It's a commonly used loss func on for
regression problems because it emphasizes larger errors due to the squaring opera on.
Mean-Absolute Error (MAE): This func on computes the average of the absolute values of the residuals. It's less
sensi ve to outliers than MSE because it doesn't square the error terms.
In these formulas, yi is the actual observed value, ŷi is the predicted value by the model, and n is the total number of
observa ons in the dataset.
Purpose of Loss Func ons:
These loss func ons are cri cal in the training phase of a regression model. The goal of training is to adjust the
model parameters w0 and W to minimize the selected loss func on. This process usually involves op miza on
techniques such as gradient descent.
In the context of machine learning and sta s cal modeling, minimizing these loss func ons helps to find the line (or
hyperplane in higher dimensions) of best fit that predicts the target variable as accurately as possible given the input
features.
Numerical solu on: gradient descent
Numerical Solu on: Gradient Descent Sec on
It explains that given the MSE loss defined over a dataset D, the model parameters are es mated using gradient
descent.
- The MSE loss func on is given by the formula:
(see formula)
Here, w0 is the bias term, and w is the weight vector for the features xi.
The factor 1/2n is o en included to simplify the deriva ve calcula on during op miza on.
Gradient Descent Algorithm:
The procedure starts with random ini al values for the model parameters w0, w1
The algorithm runs for a certain number of epochs (itera ons), indexed by k . During each epoch, the parameters are
updated to reduce the loss.
Graphical Representa ons:
One graph might illustrate the MSE loss func on surface, showing how gradient descent progresses towards the
minimum. Points on the curve indicate the value of the loss func on at different parameters during the itera ve
process.Another graph possibly shows a sca er plot of data points with the linear regression line being fi ed. The
line adjusts its slope and intercept with each itera on to minimize the MSE loss, ge ng closer to the best fit.
Purpose of the Image:
The purpose of this image is to demonstrate the applica on of gradient descent in minimizing the MSE loss func on
for a linear regression problem. It visually explains the concept of upda ng model parameters itera vely to decrease
the error between the predicted and actual values, which is central to the training of many machine learning
models.
For Bias Term
For Wheights
Gradient of the Loss Func on:
The image outlines the computa on of the gradient of the loss func on with respect to the model parameters. The
gradient, denoted as
is the vector of par al deriva ves of the loss func on with respect to each parameter. It
points in the direc on of the steepest increase of the loss func on.
Parameter Update Rule:
The parameter update rule is shown, which is used to itera vely adjust the parameters in the opposite direc on of
the gradient to minimize the loss func on.
Here, n represents the learning rate, a hyperparameter that determines the size of the steps taken towards the
minimum of the loss func on. The subscript k denotes the itera on or epoch number.
Visualiza on of Gradient Descent:
The diagram might include a visualiza on of the loss func on as a parabola in a two-dimensional space, where the xaxis represents the parameter space, and the y-axis represents the loss. The points on the parabola represent the
value of the loss func on for different parameter values.
- There may also be a depic on of a ball rolling down the curve, symbolizing the itera ve process of gradient descent
seeking the minimum loss.
Loss Func on Equa on:
The image emphasises that this is averaged over 2n data points to compute the gradient. This factor of 2 is typically
included to simplify the deriva ve calcula on but is not essen al to the op miza on process.
Overall Summary:
This image provides a visual and formulaic representa on of how gradient descent is used to find the op mal
parameters of a linear regression model by minimizing the MSE loss func on. The key takeaway is the itera ve
process of calcula ng gradients and upda ng parameters, which is central to the training of many machine learning
models.
Summary Linear Regression
Model Structure:
The independent features xi are elements of a feature space Rd , where d is the number of dimensions (features).
The dependent target variables yi are real numbers R.
The rela onship is modeled as a linear combina on of the input features.
Model Parameters:
The parameters of the linear regression model, represented by include weights corresponding to each feature and
a bias term (also known as the intercept).
The number of parameters is equal to the number of features plus one for the bias. If there are d features, then
there are d+1 parameters.
Loss Func on:
The loss func on Lw is used to measure the discrepancy between the predicted values ŷi from the model and the
actual observed values yi.
The Least Squared Error (LSE), which is the sum of the squared differences between the predicted and actual values,
is a common loss func on in linear regression.
This LSE is o en used to train the model by finding the set of parameters w that minimize this sum, which represents
the best fit line through the data points.
Training the Model:
The parameters of the model are typically es mated using op miza on algorithms like gradient descent. The
process involves:
Star ng with random ini al values for the parameters w0, w1…,wd.
Itera vely adjus ng the parameters to minimize the LSE by moving in the opposite direc on of the loss func on's
gradient with respect to the parameters.
In prac ce, the linear regression model is a founda onal tool for predic ve modeling and is widely used in both
sta s cs and machine learning for tasks such as trend es ma on, forecas ng, and finding rela onships between
variables.
Polynomial Regression
Model Structure Assump on:
Unlike simple linear regression, which assumes a straight-line rela onship between the features and target variable,
polynomial regression can model more complex, non-linear rela onships. It does this by raising input features to
various powers (squared, cubed, etc.) and possibly considering interac on terms between different features.
Goal:
The goal of polynomial regression is to es mate these non-linear rela onships. This is done by training a model fw(),
on the provided data samples, where w represents the coefficients (parameters) of the polynomial.
Data Samples:
The dataset D consists of pairs of input features xi and target values yi.
The features in the dataset may include numerical data such as Age and BMI, as well as categorical data such as
Gender, Smoker status, and Region. These would be encoded appropriately to fit into a regression model.
Polynomial Regression Curve:
The curve in the graph suggests the polynomial model is not simply a straight line, allowing it to be er fit the
nuances of the actual data.
This is par cularly useful when the rela onship between variables is not perfectly linear and may change direc on
(increase, then decrease, or vice versa) at different points in the feature space.
In summary, polynomial regression extends the linear model to accommodate non-linear rela onships by adding
polynomial terms, which can provide a be er fit for data with complex trends and pa erns. This can lead to more
accurate predic ons for certain types of datasets, especially those where the influence of predictors on the
response variable changes at different levels of the predictors.
Model Structure Assump on:
Polynomial regression assumes that the rela onship between the independent variable xi and the dependent
variable yi can be modeled with a polynomial func on. This allows for a non-linear rela onship between the
variables.
Polynomial Func on:
The model is expressed as fw(xi),, which is a polynomial func on of the input Xi.
Where w0 + x1+ w2x2…. are the model parameters to be learned, and M is the degree of the polynomial.
Polynomial Degree:
The degree M of the polynomial determines the model's complexity. Higher degrees allow the model to capture
more intricate rela onships within the data but also increase the risk of overfi ng.
Feature Transforma on:
Polynomial regression involves transforming the input x1 into a higher-dimensional space. This is done by crea ng
new features that are powers of the original feature: (see bo om formula) This transforma on allows the use of
linear regression techniques to fit a non-linear model by trea ng each power of xi as a separate feature.
Data Augmenta on:
The table in the image likely shows the original features alongside the transformed features up to the M-th power.
This augmented dataset is used to train the polynomial regression model.
Goal:
The ul mate goal is to es mate the coefficients w of the polynomial func on that best fits the data, typically by
minimizing a loss func on such as the Mean Squared Error (MSE) through an op miza on algorithm like gradient
descent.
Problem Formula on:
The ques on posed is about finding the best func on that es mates the rela onship between the output and
inputs, acknowledging that this rela onship might be non-linear.
The model's predic on ŷi is expressed as the dot product of a transformed input vector g(xi) and the weight vector
w. This transforma on allows the linear regression model to capture non-linear rela onships.
Residual Term:
Similar to linear regression, a residual term ei is used to measure the discrepancy between the observed value yi and
the predicted value ŷi.
- The residual is calculated as ei = yi – fw(g(xi)) which is equivalent to ei = yi – (g(xi)T * w), making it clear that the
predicted value comes from a transforma on of the input space.
True vs. Es mated Func on:
The es mated func on is the model's a empt to approximate the true unknown func on, which might be indicated
in the image with an equa on or descrip ve text (e.g., the true func on might be sinusoidal and the es mated
func on is a polynomial that approximates it).
Conclusion:
The picture likely summarizes that by using polynomial transforma ons of input features, linear regression models
can be extended to approximate complex, non-linear rela onships in a dataset. The process involves crea ng
polynomial features, es ma ng the model parameters that minimize the residuals, and evalua ng the model's fit
using the transformed feature space.
Supervised Learning: Classifica on
Goal of Supervised Learning:
The primary objec ve in a supervised learning classifica on task is to find a func on f() that maps high-dimensional
input data xi in Rd to predicted outputs ŷi which approximate the true labels yi as closely as possible.
Dataset:
A dataset D is composed of feature-label pairs xi, yi where xi are the features or independent variables, and yi are the
labels or dependent variables that the model aims to predict. The dataset is used to train the model.
In the context of classifica on, yi represents the class to which each data point belongs.
Predic on Func on/Algorithm:
The predic on func on, o en represented as a neural network in diagrams, is the algorithm that learns from the
input data how to make accurate predic ons.
The func on f(X, y) is trained to predict the output ŷi given a set of features X.
Types of Classifica on Problems:
Binary Classifica on:The problem where there are only two classes, o en denoted by {0, 1} or {-1, 1}. The goal is to
classify inputs into one of these two categories.
Mul -label Classifica on: A more complex classifica on where each input can be categorized into one or more
classes out of K total classes. The classes are typically represented by an integer range {1, …., K}.
Conclusion:
In summary, supervised learning classifica on involves training a model on labeled data to learn a mapping from
inputs to outputs. The model's performance is evaluated on how well it generalizes to unseen data, with the aim of
making accurate predic ons for the class labels of new inputs.
Intui on
Input and Output:
The input is a dataset D with pairs xi, yi where each xi is a feature vector from a high-dimensional space Rd, and each
yi is a binary class label.
The output is the predic on func on fw(), which maps the input feature space to the output label space.
Goal:
The goal of logis c regression is to es mate the parameters w0, w1, ..., wd of the model that maps the features xi to
the class labels yi.
Decision Boundary:
The decision boundary can be found by determining the parameters of a linear equa on that separates the classes.
The general equa on of a line (or hyperplane in higher dimensions) is given by (see formula)
The vector is orthogonal to the decision boundary, meaning it is perpendicular to the line that separates the classes.
The parameter w0 is the bias term, which represents an offset of the decision boundary. It shi s the line along the
orthogonal direc on given by w without changing its orienta on.
Conclusion
Logis c regression is par cularly useful for binary classifica on problems where the two classes can be separated by
a linear boundary. The learned model parameters define the orienta on and posi on of this decision boundary in
the feature space. The algorithm aims to find the parameter values that maximize the likelihood of the observed
data, which typically involves using op miza on techniques such as gradient descent.
Linear Classifier:
Logis c regression is a type of linear classifier, meaning it predicts the class label ŷi based on a linear combina on of
the input features.
The predicted label ŷi can take on values from a set like {-1, 1\}, represen ng the two possible classes.
Linear Classifica on Rule:
A linear classifica on rule is used to predict the class based on a calculated value Zi.
The value Zi is a linear combina on of the features xi weighted by the model's parameters w, plus the bias term w0.
Based on the sign of Zi, the class is predicted. If Zi is greater than or equal to zero, the predicted class ŷi is +1. If Zi is
less than zero, ŷi is -1.
Decision Boundary
The decision boundary is the set of points where the model's output Zi is exactly zero. Graphically, this is typically a
line (or hyperplane in higher dimensions) that divides the input feature space.
Data points falling on one side of this boundary are classified into one category, and those on the other side are
classified into the other category.
Intui on Behind Logis c Regression:
Although logis c regression is a linear model for binary classifica on, it uses a logis c func on to squeeze the
output of the linear equa on into a range between 0 and 1, which can be interpreted as the probability of a data
point belonging to a par cular class.
The linear combina on Zi is passed through a logis c func on (o en denoted as the sigmoid func on) to obtain this
probability.
In the context of logis c regression, the model learns the parameters w and w0 during training by maximizing the
likelihood of the observed data, which usually involves an op miza on algorithm such as gradient descent. The
logis c func on provides a smooth probabilis c transi on as input features move from one side of the decision
boundary to the other.
Hard vs. So Decision Classifiers
Binary Classifica on Problem:
The problem involves categorizing input features xi into one of two classes, which are typically represented as 0 or 1.
In the example provided, the two classes are "Cat" and "Dog."
Hard Decision Classifier:
This type of classifier makes a defini ve decision about which category an input belongs to. The output class label ŷi
is either 0 or 1, with no probability or uncertainty involved.
The decision rule for a hard classifier involves compu ng a linear combina on of the input features (weighted sum),
represented as (see formula) where w0 is the bias and wi are the weights corresponding to each feature.
If zi is greater than or equal to zero, the classifier predicts the class label ŷi as 1 (e.g., "Cat"). If z1 is less than zero, it
predicts the class label as 0 (e.g., "Dog").
So Decision Classifier:
A so decision classifier outputs a condi onal probability that indicates the likelihood of the input belonging to one
of the classes (in this case, class label 0, which might correspond to "Dog").
The probability is calculated using the logis c func on (also known as the sigmoid func on) which maps the linear
combina on z1 to a probability between 0 and 1.
The logis c func on creates an S-shaped curve, where inputs with a high nega ve linear combina on tend towards
a probability of 0, and those with a high posi ve linear combina on tend towards a probability of 1.
Conclusion:
In binary classifica on, hard decision classifiers give a definite classifica on without considering uncertainty, while
so decision classifiers provide the probability of belonging to a class, allowing for a measure of uncertainty or
confidence in the predic on. Logis c regression is an example of a so decision classifier that can provide nuanced
probabilis c outputs rather than just binary class predic ons.
Mul variate Logis c Regression: Used if mul ple Categories.
Mul variate Logis c Regression:
The logis c regression model is defined as (see formula) where ŷi is the predicted probability that yi equals one of
the classes, given the input features x1.
This probability is computed using the logis c func on (or sigmoid func on), denoted by σ, applied to a linear
combina on of the features The sigmoid func on transforms the linear combina on into a value between 0 and 1,
which can be interpreted as a probability.
Sigmoid Func on:
When applied to the linear combina on of features and weights, it provides the mechanism for the logis c
regression model to output probabili es.
Model Parameters and Data Samples:
The parameters w of the model, including w0 (the bias), are what the training process aims to learn.
The dataset includes various features (like radius, texture, perimeter, etc.), each of which contributes to the
predic on.
Conclusion:
Logis c regression is used when the outcome to be predicted is categorical, especially for binary classifica on tasks.
It is a probabilis c model that not only provides a classifica on but also gives the probability of the input belonging
to a par cular class, offering more informa on than just a simple classifica on.
Non-linear decision boundary
**Ques on:**
Yes, logis c regression can have a non-linear decision boundary when you incorporate polynomial terms or other
non-linear transforma ons of the features
Nature of Decision Boundary:
In logis c regression, a decision boundary is typically the result of a linear combina on of features. Here, x
represents the feature vector and w represents the weight vector.
Non-linear Decision Boundaries:
To achieve non-linearity, one can extend logis c regression using polynomial regression concepts. By adding
polynomial terms of features as new features, logis c regression can model more complex rela onships.
By including polynomial terms, such as w0, w1…, the logis c regression model can have a non-linear decision
boundary, allowing for more complex datasets where classes are not linearly separable.
Linear Boundary:
A tradi onal logis c regression model might have a decision boundary described by (see formula)
Example Model:
A specific example might include a weight vector with given values, and the resul ng logis c func on would
incorporate these weights along with the original and polynomial features to make predic ons.
Classifica on Rule:
The classifica on rule based on the logis c func on with polynomial features would classify data points into Class 1
or Class 0 depending on whether the value of the logis c func on is above or below a certain threshold, typically 0.5
for binary classifica on. For instance, using the sigmoid func on, a condi on like class 1 might define one class,
while class 0 defines the other.
Loss func on
Loss Func on in Logis c Regression:
The loss func on given is specifically designed for binary classifica on problems and is known as the binary crossentropy or log loss.
For a given dataset D where xi is a feature vector in Rd and yi is a binary class label (0 or 1), the loss func on for
logis c regression is defined.
This func on penalizes the model for incorrect predic ons; the first term deals with the true posi ves (when yi = 1)
and the second term deals with the true nega ves (when yi = 0).
Goal of Op miza on:
The goal is to find the values of the model parameters w0 (bias) and \( w = w1, …, wd (weights) that minimize the
loss func on. This is typically expressed as an op miza on problem.
Op mizing the Model Parameters:
A numerical solu on is proposed for op mizing the model parameters, typically involving an itera ve op miza on
algorithm like gradient descent.
- In gradient descent, the parameters are updated by moving in the opposite direc on of the gradient of the loss
func on, which points towards the steepest increase. By itera vely adjus ng the parameters in the direc on of the
steepest descent, the algorithm seeks to find the minimum value of the loss func on.
Logis c Regression Model:
Logis c regression aims to model the probability that a given input point x belongs to a par cular class (usually class
"1" in binary classifica on) using the logis c func on, which is an S-shaped curve also known as the sigmoid
func on.
The logis c func on σ(xTw) is defined as (see formula), where xTw is the dot product of the feature vector x and the
weight vector w. This dot product is a linear combina on of the input features weighted by the model's parameters.
Model Parameters:
The goal is to find the parameter vector w that best fits the training data. W0 is the bias term, and the rest are
weights corresponding to each feature.
Loss Func on for a Single Sample:
The loss func on, also known as the cost func on for logis c regression, is defined piecewise depending on the
actual class label yi of each training example xi.
If the actual class label yi is 1, the loss for a predic on fw(xi) is -log(fw(xi)). This part of the loss func on punishes the
model more as the predicted probability fw(xi) deviates from 1.
If the actual class label yi is 0, the loss is -log(1 - fw(xi)). This part of the loss func on punishes the model more as the
predicted probability fw(xi) deviates from 0.
Essen ally, the loss func on captures the penalty for the discrepancy between the predicted probabili es and the
actual labels. If the predic on is very confident and correct (i.e., predic ng a true class with high probability), the
loss is low (close to 0). If the predic on is very confident and incorrect, the loss approaches infinity, represen ng a
high cost for confident misclassifica ons.
Implica ons:
For yi = 1, if fw(xi) is close to 1, the loss is low. While if fw(xi) is close to 0 (a wrong predic on with high confidence),
the loss is very high (tending towards infinity).
- For yi = 0, if fw(xi) is close to 0, the loss is low, while if fw(xi) is close to 1 (again, a wrong predic on with high
confidence), the loss is very high.
Gradient descent
Cross-Entropy Loss Func on:
The cross-entropy loss, o en used for binary classifica on problems, is defined for logis c regression. For a dataset
D where x1 is a feature vector and yi is the binary target (0 or 1), the loss for the en re dataset is the sum of the
individual losses for each sample. σ denotes the sigmoid func on.
Ini aliza on:
Start with a random value for the parameters
Gradient Computa on:
At each step k, compute the gradient of the loss func on with respect to the parameters. The gradient is a vector
that points in the direc on of the steepest ascent of the loss func on.
Parameter Update:
Adjust the parameters in the opposite direc on of the gradient to minimize the loss.
η is the learning rate, a small posi ve scalar that controls the size of the update step.
Itera on:
Repeat steps 2 and 3 for a number of itera ons or un l the change in the loss func on is below a certain threshold.
Goal of Op miza on:
The overall goal is to find the parameter values that result in the minimum loss, meaning the model's predic ons are
as close as possible to the actual labels.
Numerical Solu on:
Because the loss func on for logis c regression is convex, gradient descent is guaranteed to find the global
minimum if the learning rate is properly chosen and enough itera ons are performed.
Model Structure Assump on:
Logis c regression assumes that the log-odds (the logarithm of the odds) of the probability of a binary outcome is a
linear func on of the input features. This means that the natural logarithm of the ra o of the probability of the
posi ve class to the probability of the nega ve class is linearly related to the input variables.
Logis c Func on:
The logis c (sigmoid) func on is applied to the linear combina on of the features and the model parameters to
output a probability between 0 and 1.
Model Parameters:
These parameters are learned from the training data and determine the log-odds of the target variable. The model
predicts the probability of the posi ve class
Loss Func on:
The loss func on used in logis c regression is the binary cross-entropy (BCE), which is designed to quan fy the
difference between the predicted probabili es and the actual binary labels. It heavily penalizes predic ons that are
confident and wrong.
For a correctly predicted outcome with high confidence, the loss is close to zero, while for incorrect predic ons with
high confidence, the loss approaches infinity.
In essence, logis c regression is a sta s cal model used for binary classifica on that es mates probabili es using
the logis c func on and aims to find the best parameters that minimize the binary cross-entropy loss, typically using
an op miza on algorithm like gradient descent.
Ensemble Models: Random Forest
Random Forest: It is an ensemble learning method that operates by construc ng a mul tude of decision trees at
training me and outpu ng the class that is the mode of the classes (classifica on) or mean predic on (regression)
of the individual trees.
Random Trees: Random Forests build many individual decision trees to form the ensemble. Each tree in the forest is
created from a random vector sampled with replacement from the training dataset (known as bootstrapping).
Moreover, each node in the tree is split using the best among a subset of predictors randomly chosen at that node.
This introduces randomness into the model, which helps to make it more robust than a single decision tree and less
prone to overfi ng.
Usage: Random Forests can be used for both classifica on tasks (predic ng discrete class labels) and regression
tasks (predic ng con nuous outcomes).
Individual Training: Each tree is trained independently on a different bootstrap sample of the data. The randomness
in the sample and the subset of features considered for spli ng at each node ensure that the trees are
uncorrelated, which increases the diversity of the ensemble and leads to be er generaliza on performance.
Majority Vo ng: In classifica on tasks, each tree in the forest votes for a class, and the class receiving the most
votes is the model's predic on. In regression tasks, the predic ons of all trees are averaged to determine the final
predic on.
The essence of a Random Forest is that it combines the predic ons of several decision trees, reducing the risk of
overfi ng associated with individual trees and improving predic ve performance by averaging out errors.
Random Forests in Classifica on:
Input: The model takes an input dataset D, where xi is a feature vector, yi is the target label, and k is the number of
neighbors (although the number of neighbors is typically associated with k-nearest neighbors, not Random Forests).
Output: The model outputs a predic on ŷi for each sample xi in the dataset.
Classifica on Task: The task is to predict the class of an unknown data point. For regression tasks, the goal is to
predict con nuous values based on input variables.
Making Predic ons: Given decision boundaries or regions which the Random Forest model has learned during
training, the algorithm can classify a new unseen test sample. For instance, for a test sample xi = [8.1, 2.3] \), the
process would involve:
1. Loca ng which region the test sample falls into based on its feature values.
2. Using the class distribu ons within that region (which the Random Forest model has determined from the training
data) to es mate the probabili es of belonging to each class.
3. Assigning the class label to the test sample based on the highest probability, indica ng the most likely class this
sample belongs to. This is o en done by majority vo ng among the trees in the forest; the class that gets the most
votes becomes the predic on.
The essence of the image is to convey that Random Forests leverage the power of mul ple decision trees to make
more accurate and robust predic ons than a single decision tree could make on its own.
Algorithm
Random Forest Algorithm:
Input: The algorithm starts with a dataset D, where xi are the feature vectors, yi are the target labels, T is the number
of trees to grow, and D is the maximum depth of each tree.
Output: The expected output is a set of sample predic ons ŷi.
Goal: The main goal is to create an ensemble of decision trees, each tree being grown to the maximum extent
possible with many "pure" nodes (nodes with samples from a single class).
Building the Forest:
1. Bootstrap Sampling: For each tree, t, from 1 to T, create a bootstrap sample Dt from the original dataset D.
Bootstrapping is a sampling technique where samples are drawn with replacement.
2. Training Each Tree: Each decision tree Tt is trained on its respec ve bootstrap sample Dt:
The training involves crea ng random split func ons based on the features of the data. These func ons are denoted
as τ(f (x), 0), where (f (x) represents the features and 0 represents the parameters or thresholds for spli ng.
For each poten al split, calculate the informa on gain, and select the split that maximizes this gain.
Split the node into two child nodes and repeat this process recursively un l the maximum tree depth D is reached or
the current node is pure (contains samples from only one class) or contains too few samples to split further.
3. Output the Forest: Combine all the individual trees Tt to form the Random Forest. This ensemble represents the
final model where each tree contributes to the decision-making process.
Predic on: For a new sample, each tree in the forest makes a predic on, and the final output is typically determined
by majority vo ng for classifica on tasks or averaging for regression tasks.
Decision Tree Algorithm:
Ques on: The primary ques on addressed by the algorithm is how to determine the class label of a new sample xi
based on its features.
Dataset: The algorithm operates on a dataset D, which suggests a mul -class classifica on problem where each
feature vector xi is associated with one of three possible classes.
Process: To predict the class label of xi, the algorithm uses a series of decisions based on the values of the features
of xi. These decisions are represented as nodes in the decision tree.
Split Nodes (depicted as blue circles): These nodes make decisions by applying a split func on τ (f (x), 0), where (f (x)
is a feature of the data and 0 is the threshold. If the feature value is greater than or equal to 0, the algorithm follows
one branch (typically the right branch); if it is less, it follows the other (le branch).
Leaf Nodes (depicted as red circles): These nodes represent the final decision and assign a class label to the sample.
The path taken from the root to a leaf node is determined by the outcomes of the split func ons at each node along
the path.
Class Condi onal Distribu on: The probability p(Y = c | X = x) is the class condi onal distribu on, which es mates
the probability of each class given the feature vector. In the context of a decision tree, the class with the highest
es mated probability (o en represented by the majority class in a leaf node) is the one assigned to the sample.
To make a predic on for a new sample, the algorithm follows the decision path down the tree according to the
sample's feature values un l it reaches a leaf node. The class associated with that leaf node is the predicted class for
the sample. The specific values and thresholds used in the tree are determined during the training process of the
model.
In a Random Forest classifica on, to obtain the class label of a given sample, you would follow these steps:
1. Present the Sample: The sample, represented by a feature vector, is input into each decision tree within the
Random Forest.
2. Decision Tree Predic ons: Each decision tree in the Random Forest makes an independent predic on of the class
label for the sample. This predic on is based on the condi ons at each node of the tree, which test the value of a
par cular feature of the sample.
3. Aggrega on of Predic ons: A er all trees have made their predic ons, the Random Forest algorithm aggregates
these predic ons. The most common aggrega on method is majority vo ng, where each tree has one vote, and the
class label that receives the majority of votes is chosen as the final predic on.
4. Output the Class Label: The class label that gets the majority of votes from all the individual trees is considered
the class label for the sample by the Random Forest classifier.
This process allows the Random Forest to make a decision that is less likely to be influenced by noise and overfi ng,
as it considers the collec ve decision of mul ple trees, each trained on a different subset of the data.
In a Random Forest regression to predict the value for a new sample, the following steps are taken:
1. Introduce the Sample: The feature vector of the new sample is input into each decision tree within the Random
Forest.
2. Individual Tree Predic ons: Each decision tree in the forest provides a numerical predic on for the target variable
based on the sample's features. The predic on is made by traversing the tree from the root to a leaf node, with each
node in the tree represen ng a decision point based on a single feature.
3. Aggrega on of Tree Predic ons: The predic ons from all individual trees are combined to produce the final
predic on. In regression tasks, this is typically done by calcula ng the average (mean) of all the predic ons.
4. Output the Predicted Value: The aggregated predic on, which is the average of the predic ons from all the trees,
is output as the predicted value for the target variable for the given sample.
This ensemble method benefits from the diversity of the trees and helps to reduce variance, leading to a more
robust and generalized predic on than a single decision tree would provide.
Random Forests (RFs) are a powerful machine learning method that involves crea ng a collec on of decision trees
to make be er predic ons than any single tree could alone. Here's a summary based on the provided image:
Ensemble Method: RFs combine mul ple decision trees to improve predic on accuracy. This ensemble approach
leverages the power of mul ple learning models, increasing the overall effec veness of the predic ve model.
Support for Mul ple Classes: RFs can handle classifica on problems with more than two classes. Each tree in the
forest gives a vote for the class, and the class with the majority of votes is chosen as the final predic on.
Incorpora on of Randomness: Randomness is introduced in two main ways:
Bagging: Each tree is built from a bootstrap sample, meaning a random selec on with replacement from the original
dataset. This ensures that each tree is slightly different, which increases diversity among the trees and leads to a
more robust model.
Feature Selec on: When spli ng nodes, a random subset of features is considered. This further increases the
diversity among the trees and contributes to a model less likely to overfit.
Paralleliza on: The independent nature of the trees in RFs makes the algorithm well-suited for parallel processing.
Each tree can be trained simultaneously on different processors, leading to significant computa onal efficiency.
Handling Different Feature Types: RFs can manage various types of features, whether categorical or numerical. The
algorithm does not require extensive preprocessing to handle different types of data.
Versa lity in Applica on: RFs are versa le and can be used for both regression and classifica on tasks. For
regression, the final predic on is typically the average of the predic ons from all trees.
Feature Importance: RFs can also be used to iden fy the importance of each feature in predic on, giving insight into
the underlying processes that generate the data.
Gradient boos ng in Random forest
**Gradient Boos ng Overview:**
1. **Ensemble Technique**: Gradient Boos ng is an ensemble learning method that builds a series of learners
(o en decision trees), each one correc ng the errors of its predecessor.
2. Sequen al Training: Unlike Random Forests, which train each tree independently, Gradient Boos ng trains each
tree sequen ally, with each tree focusing on the errors of the previous one.
3. Loss Func on: A differen able loss func on L is used to measure the error of the model. Gradient Boos ng aims
to minimize this loss func on by adding new models that correct the errors of the combined ensemble.
4. Algorithm Steps:
The first learner T1 is trained on the original dataset, and predic ons ŷ1 are made.
The subsequent learners \( T2, T3, ..., TT are trained on the residuals, i.e., the differences between the observed
values and the predic ons of the current ensemble.
Each new learner is typically a decision tree, and it contributes a correc on term weighted by a learning rate η to the
ensemble's predic on.
5. Output: The final predic on ŶT is a sum of the ini al predic on and the weighted contribu ons of all T learners.
6. Learning Rate: There is a learning rate η, which scales the contribu on of each tree. A smaller learning rate
requires more trees to model all the complexi es but generally leads to a more robust model.
This method is par cularly powerful because it combines the predic ons of mul ple weak learners to form a strong
learner. Each tree in the ensemble focuses on the most difficult cases, thereby improving the overall performance on
the dataset. Gradient Boos ng is o en used when the performance is of utmost importance and can outperform
Random Forests if tuned properly.
Model Generaliza on: This refers to a model's ability to perform well on new, unseen data a er being trained on a
dataset. A model that generalizes well performs similarly on both training data and unseen data.
2. True Parameter 0: This represents the actual value of the parameter in the model that we're trying to es mate. In
the context of machine learning, this might be the actual underlying pa ern or rela onship that the model seeks to
learn from the data.
3. Es mated Parameter Ô: This is the es mate of the parameter obtained from the model a er it has been trained
on the dataset. In prac ce, this is rarely equal to the true parameter due to imperfec ons in the data or the model.
4. Variance: This quan fies how much the es mates Ô will vary if we train the model on different training sets. High
variance indicates that the model is very sensi ve to the specific data it was trained on, which can lead to
overfi ng.
5. Bias: This measures how far off our es mates are from the true parameter on average. High bias can indicate that
the model is too simplis c and does not capture the complexi es of the data, leading to underfi ng.
6. Bias-Variance Tradeoff: The image likely illustrates the trade-off between bias and variance, a fundamental
concept in machine learning. Minimizing both bias and variance is key to crea ng a model that generalizes well.
Typically, a model with high bias has low variance, and vice versa. The goal is to find a balance that minimizes the
total error.
Understanding the bias-variance tradeoff is crucial when designing machine learning models because it helps in
selec ng the right model complexity to achieve the best performance on unseen data. It's also essen al for
understanding why certain models might perform poorly when deployed in real-world scenarios, despite showing
high accuracy on training data.
Evalua on Protocol, Bias-variance Tradeoff
Bias-Variance Tradeoff: This is a fundamental issue in supervised learning where we need to manage the tradeoff
between two types of error: bias and variance.
High Bias (Underfi ng): When a model has high bias, it means it's too simple and doesn't capture the complexity of
the data well. This o en results in a model that performs poorly on both the training set and unseen data because it
is not flexible enough to learn the true underlying pa erns.
Good Fit: A good model fit means that the model has balanced bias and variance, capturing the underlying pa ern
of the dataset without being swayed by the noise. It performs well on both the training data and unseen test data.
High Variance (Overfi ng): High variance indicates that the model is too complex and fits not only the underlying
data but also the noise. Such a model will have low training error but high test error because it's too tailored to the
specific details of the training set and doesn't generalize well.
Recogni on of Underfi ng and Overfi ng: The image may provide ps on how to recognize these issues.
Underfi ng is o en detected when both training and test errors are high, while overfi ng is characterized by low
training error but high test error.
Model Generaliza on: In the context of the bias-variance tradeoff, a model's ability to generalize well means it has
achieved a balance between bias and variance, performing well on new, unseen data.
Hyperparameter Search, Holdout Methods
Holdout Method:
Par oning: The dataset is split into two separate sets, typically a training set and a test set. A common ra o is 70%
of the samples for training and 30% for tes ng.
Training Set: This subset is used for learning the model, allowing the algorithm to uncover any pa erns or
rela onships within the data.
Test Set: A er training, the test set is used to evaluate the performance and generalizability of the model. It
provides an unbiased assessment of the model's accuracy on new, unseen data.
Computa on Time: The holdout method is rela vely quick to compute because it requires only a single split and a
single evalua on.
Quality of Par oning: The effec veness of the holdout method can depend significantly on how the data is
divided. Poorly par oned data can lead to misleading evalua ons.
Data Scarcity: In cases where datasets are small, dividing the data can result in insufficient training examples, which
may not adequately represent the problem space.
Hyperparameter Search:
Tuning: This is the process of searching for the op mal set of hyperparameters for a learning algorithm.
Hyperparameters are the configura on se ngs used to structure the machine learning model.
Methods: Methods for hyperparameter search can include grid search, random search, Bayesian op miza on, or
more complex methods like gene c algorithms.
Evalua on: The holdout method can be used in conjunc on with hyperparameter search to evaluate the
performance of different hyperparameter configura ons.
Objec ve: The goal of hyperparameter search is to find the hyperparameters that result in the best performing
model on the test set, indica ng a model that has achieved a good balance between bias and variance.
1. Training Set: This is used to train the machine learning model. Typically, it comprises a large por on of the dataset
(e.g., 70%).
2. Valida on Set: The valida on set is used to fine-tune the model parameters and perform hyperparameter
op miza on. It can also be used for model selec on, such as choosing which model architecture to use.
3. Test Set: A er the model has been trained and validated, the test set is used to es mate the model's
performance. This set acts as new data to evaluate how well the model generalizes to unseen data. It's important
that once the model is evaluated on the test set, it should not be tuned any further to avoid informa on leak from
the test set into the model.
The process generally works as follows:
- The dataset is first divided as described above.
- The model is trained on the training set.
- Hyperparameter tuning and model selec on are performed on the valida on set. Different hyperparameter values
are tried, and the set of values that perform best on the valida on set is selected.
- Finally, the model's performance is evaluated on the test set to get an unbiased es mate of how it will perform on
unseen data.
K-Fold Cross-Valida on
The image you've uploaded likely explains the concept of K-Fold Cross-Valida on, which is a resampling procedure
used to evaluate machine learning models on a limited data sample.
Here's a summary of the K-Fold Cross-Valida on process:
The dataset D is randomly par oned into K exclusive subsets (or "folds"), each of approximately equal size.
The cross-valida on process is then repeated K mes (the "folds"), with each of the K subsets used exactly once as
the test set (or "valida on set").
The K-1 remaining subsets are put together to form a training set. Therefore, each data point gets to be in a test set
exactly once, and gets to be in a training set K - 1 mes.
The performance measure reported by k-fold cross-valida on is then the average of the values computed in the
loop. This approach can be computa onally expensive but does not waste too much data, which is a major
advantage in problems where the number of samples is very small.
The main goal of this method is to provide a robust way to test the model's ability to predict new data that was not
used in es ma ng it, by reducing the variance associated with a single trial of train/test split. It is par cularly useful
when the goal is to predict the performance of a model on an independent data set in situa ons where the data set
is not too large.
Evalua on Measurements
True Posi ves (TP): These are the cases where the model correctly predicts the posi ve class.
True Nega ves (TN): These are the cases where the model correctly predicts the nega ve class.
False Posi ves (FP): These are the cases where the model incorrectly predicts the posi ve class, also known as a
Type I error.
alse Nega ves (FN): These are the cases where the model incorrectly predicts the nega ve class, also known as a
Type II error.
The confusion matrix is a table used to describe the performance of a classifica on model on a set of test data for
which the true values are known. It allows you to visualize the performance of an algorithm.
Two commonly used evalua on metrics derived from the confusion matrix are:
Accuracy (ACC: This is the ra o of correctly predicted observa ons to the total observa ons and is given by the
formula… It’s a measure of how many classifica ons are correct.
Error Rate (ERR): This is the ra o of incorrectly predicted observa ons to the total observa ons and is given by the
formula. It’s a measure of how many classifica ons are incorrect.
The ques on "How to choose the best classifier?" refers to the process of selec ng the model that performs best
according to these (and possibly other) metrics. The choice of the "best" classifier can depend on the specific
requirements of the task, such as the cost of false posi ves versus false nega ves, the need for a balanced accuracy
across classes, the prevalence of classes, and so on.
To choose the best classifier, you would typically compare these metrics across different models. In some cases,
other metrics such as Precision, Recall, F1 Score, or the area under the ROC curve (AUC-ROC) might also be used,
especially when dealing with imbalanced datasets or when the cost of false posi ves and false nega ves is not the
same.
Precision vs. Recall
Precision (PRE): This is the propor on of true posi ve predic ons in the total number of posi ve predic ons made
by the model. It is calculated as (see PRE formula). High precision means that an algorithm returned substan ally
more relevant results than irrelevant ones.
Recall (REC): Also known as sensi vity, it is the propor on of true posi ve predic ons out of all actual posi ve
instances in the dataset. It is calculated as (see REC formula). High recall means that an algorithm returned most of
the relevant results.
For the "Normal" class:
Recall for Normal = 6/9 = 0.666 (Out of all the actual normal instances, the model correctly iden fied 66.6% of
them).
Precision for Normal = 6/8 = 0.75 (Out of all the instances predicted as normal by the model, 75% were actually
normal).
For the "COVID" class:
Recall for COVID = 7/9 = 0.77 (Out of all the actual COVID instances, the model correctly iden fied 77% of them).
Precision for COVID = 7/10 = 0.7 (Out of all the instances predicted as COVID by the model, 70% were actually
COVID).
These metrics are especially important in medical diagnos cs, where it is crucial to correctly iden fy as many true
cases as possible (high recall) while also minimizing the number of false alarms (high precision).
The balance between Precision and Recall is o en a trade-off, depending on the cost/consequences of making a
false posi ve error compared to a false nega ve error. For instance, in medical diagnosis, a false nega ve (missing a
diagnosis) can be much more detrimental than a false posi ve (a diagnosis that turns out to be a false alarm), so a
higher Recall might be priori zed.
A classifier that gives a perfect score will have a point at (1,1), which means 100% precision and 100% recall. Realworld classifiers typically show a trade-off: increasing precision o en reduces recall and vice versa. This curve helps
in selec ng the threshold that gives the best balance between precision and recall for a specific task.
Curve Shape: The closer the curve follows the top-right border of the plot, the more effec ve the classifier. A curve
that drops quickly toward the bo om right indicates lower effec veness.
Classifier Comparison: If one curve completely envelopes another, the former classifier is be er. For par al overlaps,
the best classifier may vary depending on the specific precision-recall trade-off one is interested in.
Thresholds (T): Specific points on the curve are marked to show the precision and recall corresponding to par cular
threshold se ngs. For example, a threshold of 0.99 might yield very high precision but lower recall, indica ng that
the classifier is very confident about its posi ve predic ons but fails to iden fy a significant number of actual
posi ves (high false nega ves).
Classifier 1 vs Classifier 2: Two classifiers are compared in this curve. The one whose curve is higher and to the right
(Classifier 1 in this case) generally has be er performance. Classifier 2 might only be preferable in scenarios where
high recall is more important than precision.
The Precision-Recall curve is par cularly useful when dealing with imbalanced datasets where the posi ve class (the
class of interest) is much less frequent than the nega ve class. In such cases, Precision and Recall can give a be er
insight into the classifier's performance than accuracy alone.
Underfi ng vs. Overfi ng: The graph compares train error and test error to illustrate underfi ng and overfi ng in
machine learning models. Underfi ng occurs when a model is too simple to capture the underlying pa ern in the
data, leading to high error on both the training and test datasets. Overfi ng happens when a model is too complex
and starts to capture noise in the training data, leading to low error on the training dataset but high error on the test
dataset.
Model Capacity: The concept of model capacity is visualized, where the model's complexity increases from
underfi ng to overfi ng. An ideal model has the right capacity to generalize well from the training data to unseen
data.
Hyperparameter Search Strategies: The text highlights different strategies for searching hyperparameters, such as
using holdout sets or K-Fold cross-valida on. These methods are used to tune the model parameters to improve
performance.
Valida on Protocol: It emphasizes the importance of not using the test set during the hyperparameter tuning phase
because the test dataset should represent new, unseen data to evaluate the model's performance accurately.
Repor ng Results: Finally, it notes the importance of repor ng results on the test set to demonstrate the model's
generaliza on capabili es. This is crucial for assessing the model's performance in prac cal, real-world scenarios.
This summary provides an overview of the key evalua on measurements and prac ces to ensure that a machine
learning model is well-tuned and generalizes well to new data, avoiding common pi alls like underfi ng and
overfi ng.
Lecture #8: Unsupervised Learning Clustering
Data Clustering
Clustering: Method used in Machine Learning to group set of objects so that objects in the same group (clusters) are
more like each other than those in other groups (clusters).
There are 3 different approaches to Clustering:
Par
oning Clustering
Divides dataset into dis nct
groups based on certain
characteris cs.
- Goal: Par on dataset to
maximize similari es within
cluster AND to minimize
similari es between
different clusters.
- Common Algorithms: KMeans, Medoids
-
Density Clustering
- Groups data points based on
areas of high concentra on/
density of data points.
- Good for iden fica on of
clusters of arbitrary shapes.
- Common Methods: DBScan,
Op cs
Advantage
Advantage
-
-
Easy to understand.
Efficient for large dataset
Disadvantage
-
Doesn’t work for arbitrary
shapes.
Nr. Of clusters must be
defined
Sensi ve to ini aliza on
Discovers arbitrary shaped
clusters.
- No need to define the
number of clusters.
- Robust to noise and clusters
Disadvantage
-
Cannot cluster datasets with
varying densi es.
Can’t be applied on parallel
for mul ple processes
Hierarchical Clustering
- Creates tree of cluster
- Doesn’t require prespecifying the numbers of
clusters.
- Produces hierarchy from
most similar pairs of clusters
up to lever where all data
points are in one cluster.
- Methods: Agglomera ve
(bo om-up) or Divisive (topdown)
Advantage
-
No need to define Nr. Of
clusters
Disadvantage
-
Sensi ve to noise and
outliers
Not good for large datasets
Par
oning Clustering
The K-Means Algorithm: This is a popular method for par
different clusters.
oning clustering, where you divide a dataset into 'K'
Input: You need two things to start:
1. A dataset, where each data point is a vector in a 'd'-dimensional space.
2. The number 'K', which is the number of clusters you want to create.
Output: The algorithm will assign each data point in your dataset to one of the K clusters.
Goal: The purpose of the K-Means algorithm is to organize the data into clusters such that the total distance
between data points and their respec ve cluster centers (means) is as small as possible.
Ini aliza on: You begin by choosing 'K' random points in your dataset as the ini al cluster centers.
The Process:
1. Assignment Step: Assign each data point to the nearest cluster center. This is done by calcula ng the distance
from each data point to each cluster center and picking the smallest one.
2. Refi ng Step: A er all data points are assigned, recalculate the cluster centers by taking the mean of all the
points in each cluster.
Convergence: These two steps are repeated un l the assignments no longer change. This means the cluster centers
have stabilized and the algorithm has 'converged'.
The mathema cal nota ons and equa ons in the slide define this process formally. The goal is represented as a
minimiza on problem, where 'Cost' is a func on represen ng the total distance to be minimized.
The small graphs illustrate the steps of the algorithm:
- The first graph (top le ) might show the ini al random cluster centers.
- The second graph (top right) shows the assignment of points to the nearest cluster center.
- The third graph (bo om le ) shows the updated cluster centers a er the assignment.
- The last graph (bo om right) shows the new assignments to these updated centers.
This itera ve process (assignment and refi ng) con nues un l the cluster centers do not move anymore, indica ng
that the algorithm has found a stable set of clusters.
Elbow Method
This image explains a method for determining the op mal number of clusters to use in the K-Means clustering
algorithm, known as the Elbow Method.
Elbow Method Overview: This method involves running the K-Means algorithm several mes, each me with a
different number of clusters (K), and then evalua ng the results to find the best K.
Steps in the Elbow Method:
1. Run the Algorithm: Perform K-Means mul ple mes, each run with a different K value.
2. Compute Within-Cluster Distance: For each run, calculate the sum of the squared distances between each
data point and the center of the cluster it belongs to (this is the within-cluster distance).
3. Plot the Results: Create a plot with K on the horizontal axis and the within-cluster distance on the ver cal
axis.
4. Find the Elbow: Look for the point on the plot where the rate of decrease sharply changes, resembling an
"elbow". This point suggests that increasing the number of clusters beyond this point does not provide much
be er modeling of the data.
Visual Representa on:
The graph on the right side of the image shows a line plo ng the within-cluster distance for different values of K.
The "elbow" is the point a er which the decrease in distance is less pronounced, indicated by the arrow marked
"op mal clusters".
The series of plots below the graph depict different clustering results as K is increased. They show how the data
points are grouped into clusters with their centers (indicated by crosses).
Density-based Clustering
The image you've provided describes density-based clustering, which is an approach to iden fy clusters in data
based on the concept of density. Here's the simple explana on:
Idea: This approach groups data points together if they are closely packed (high density), while data points that lie
alone in low-density regions (surrounded by a region of low-density points) are typically considered noise or
outliers.
Clusters: They are defined as areas where there are many data points close together. These clusters can take any
shape and are separated into regions with fewer data points.
Assignment: Each data point is assigned to a cluster if it's in a high-density region. If a point is not in a high-density
area, it may not be assigned to any cluster.
Advantages: One of the main benefits of density-based clustering is that you don't need to decide how many
clusters there should be beforehand, which is a requirement in other clustering methods like K-Means.
Solu ons: The image lists three common algorithms used in density-based clustering:
- DBSCAN: This algorithm groups together points that are closely packed together, marking as outliers the
points that are alone in low-density regions.
- OPTICS: This algorithm is useful for finding clusters in data of varying density. Unlike DBSCAN, OPTICS deals
with the issue of varying densi es.
- DENCLUE: This algorithm uses mathema cal func ons to find the centers of high-density regions in the data.
It's good for data with noise and can find clusters of arbitrary shape.
Visualiza on: The sequence of images shows how a non-clustered set of data points (le ) goes through the process
of clustering, with the final image showing the iden fied clusters in different colors.
DBSCAN Algorithm:
- It's a clustering algorithm that groups together points that are closely packed together, marking as outliers
the points that are too far apart from any core points (points with many neighbors).
- This is par cularly good for data with clusters of irregular shape and is robust to outliers.
How DBSCAN Works:
1. Ini aliza on: It starts by selec ng a random point (sample) from the dataset.
2. Repeat Un l All Samples Visited:
o For each point, it checks how many neighboring points it has within a certain radius (ε - epsilon).
o If a point has enough neighbors (at least 'minPts'), it's considered a core point. If not, it might be
considered an outlier.
o It then marks the checked point as processed.
3. Expand:
o For each core point, the algorithm gathers all directly reachable points within ε and considers them
part of the same cluster. This process is recursive, which means that it also checks the neighbors of
the neighbors and so on.
o The cluster grows un l there are no more points within ε of the cluster.
Output:
Clusters of points (where each point is close to another point in the cluster) and outliers (points that don't belong to
any cluster).
Visual Examples:
The image likely includes visual aids to show how points are clustered based on their density, with some points
being marked as core points, some being reachable and included in the cluster, and others being marked as outliers.
In simple terms, DBSCAN looks for areas where points are densely packed together and groups them into clusters,
while iden fying and separa ng out the points that don't fit well into any cluster.
Hierarchical Clustering
Hierarchical Clustering Overview:
-
Idea: This method builds a hierarchy of clusters by either star ng with all data points as individual clusters
and merging them (agglomera ve) or star ng with one all-inclusive cluster and dividing it (divisive).
Clusters: They are structured in a tree-like diagram called a dendrogram, which represents the arrangements
of the clusters produced by the algorithm.
Defini on: Clusters are formed based on their proximity or distance from one another. The closer two
clusters are, the more similar they are.
Data Samples: In hierarchical clustering, it's possible for data samples to be part of more than one cluster,
especially at different levels of the hierarchy.
Process:
1. Agglomera ve (Bo om-Up):
- Start by trea ng each data point as a separate cluster.
- Merge clusters step by step based on their distance un l all points are merged into a single cluster.
- The distance between clusters can be measured in various ways, like the shortest distance between any two
points in the clusters (single linkage) or the longest distance (complete linkage).
2. Divisive (Top-Down):
- Start with one cluster containing all data points.
- Recursively split the cluster into smaller clusters based on distance metrics un l each data point is its own
cluster.
Visual Representa ons:
- The image might show a series of stages star ng from individual points (le ), progressing through levels of
clustering (middle), and ending with the data points organized into a final set of clusters (right).
- The series of images are likely intended to visually demonstrate how data points are progressively grouped
together or separated based on their similari es or differences.
In simpler terms, hierarchical clustering is like organizing data into a family tree where each branch represents a
cluster of data points that are more like each other than to those in different branches. The method doesn't require
specifying the number of clusters in advance, and the results can provide insights into the data's underlying
structure.
Lecture #09: Unsupervised Learning Dimensionality reduc on
Dimensionality Reduc on
Dimensionality Reduc on Overview:
Purpose: Dimensionality reduc on is used to simplify the amount of informa on that needs to be processed,
without losing significant amounts of important data. This is done for two main reasons:
1. Reducing Computa onal Complexity: By lowering the number of dimensions (features) of the data, it
becomes easier and faster for computa onal processes to analyze the data.
2. Interpretability: With fewer dimensions, data can be more easily visualized and understood, which is
important for finding pa erns or structures within the data.
Why is Dimensionality Reduc on Important?
-
Visualiza on: It helps in visualizing high-dimensional data in two or three dimensions, making it possible to
see pa erns and rela onships that were not apparent before.
Finding Meaningful Data Structures: By reducing dimensions, it becomes easier to iden fy the underlying
structure of the data.
Desired Proper es of Dimensionality Reduc on Algorithms:
-
Data Reconstruc on: The reduced-dimension data should s ll be able to approximately represent the
original high-dimensional data, meaning you can go from the lower dimension back to the higher dimension
without losing much informa on.
- Informa on Preserva on: Even with fewer dimensions, the most important or relevant informa on from the
original data should s ll be preserved.
- Distance Preserva on: The rela ve distances between data points should be preserved, meaning that similar
items are s ll similar in the reduced dimension, and dissimilar items remain dissimilar.
- Noise Reduc on: Unnecessary or redundant informa on (o en seen as 'noise') should be removed to make
the pa erns in the data clearer.
The visual might show an example of high-dimensional data (Data that has many a ributes and features) being transformed into a
lower-dimensional space while s ll maintaining the structure of the data. This is o en demonstrated with the help
of a sca er plot where each point represents a data sample, and similar samples cluster together even a er the
dimensionality reduc on.
Principal Component Analysis
PCA: Sta s cal technique used for dimensionality
reduc on.
PCA Goal: Reduce number of variables in a dataset
while preserving as much informa on as possible.
PCA Overview:
Data (-> D = the data set):
Xi = data point in a ‘d’-dimensional space
N = Number of data points
The process works as follows:
Standardize the Data: If the data isn’t already standardized (each dimension has a mean of 0 and a standard
devia on of 1), this step is necessary to prevent features with larger scales from domina ng the analysis.
Compute the Covariance Matrix: PCA looks at the covariance between features to iden fy which dimensions in the
data have the most variance.
Calculate Eigenvalues and Eigenvectors: These are computed from the covariance matrix. Eigenvectors point in the
direc on of the greatest variance, and eigenvalues indicate the magnitude of this variance.
Choose Principal Components: Eigenvectors are sorted in order of their eigenvalues, highest to lowest. The 'k'
eigenvectors with the highest eigenvalues are selected as the principal components.
Form Projec on Matrix W: The selected eigenvectors form the columns of matrix W.
Transform Original Data: Finally, the original data is projected onto the new subspace using W to get the new
coordinates, which are the principal components of the data.
Posi ve Covariance: When the value of one variable increases, the value of the other variable increases as well. In
the sca er plot, this would be represented by data points that form a pa ern extending from the bo om le to the
top right. The covariance matrix “C” with posi ve numbers off the diagonal indicates that both variables increase
together.
Nega ve Covariance: This occurs when the value of one variable increases while the value of the other decreases. In
the sca er plot, the pa ern would extend from the top le to the bo om right. The covariance matrix “C” with
nega ve numbers off the diagonal shows this inverse rela onship.
Zero Covariance: This suggests that the variables do not have any linear rela onship between them. The sca er plot
would show a more cloud-like or circular pa ern, with no clear direc onality. The covariance matrix “C” would have
zeros off the diagonal, indica ng no linear rela onship.
Low Variance for x (or y): Variance is a measure of how much a set of numbers is spread out. Low variance for one
of the variables, like 'x' or 'y', would be depicted by data points that are closely packed along the axis of that
variable. The covariance matrix “C” would show a small number for the variance of 'x' (or 'y'), indica ng that the
data points for 'x' (or 'y') do not spread out much.
In covariance matrices, the diagonal elements represent the variance of each variable (how much the individual
variable varies), and the off-diagonal elements represent the covariance between the variables. The matrices shown
in the image alongside the sca er plots would be examples of such matrices, giving numerical values that
correspond to the visual pa erns shown.
Top of Form
The lines with arrows are not labeled as eigenvalues; they are the eigenvectors. Each line represents an eigenvector
of the data's covariance matrix. The eigenvalues are the numbers labeled as λ1 and λ2, and they represent how
much variance there is in the data in the direc on of the corresponding eigenvector.
Eigenvalues (λ): These are scalars that give informa on about the scale of transforma on in the direc on of its
eigenvector. In the context of PCA, an eigenvalue represents the amount of variance in the direc on of its
corresponding eigenvector. (Tells how important each Eigenvector is)
are the numbers that quan fy how spread out the data is along each of these eigenvectors. A higher
eigenvalue means the data is more spread out in that direc on.
Eigenvectors (V) (the lines with arrows): These are vectors that are not rotated by a given transforma on. Instead,
they are only scaled by the eigenvalue. In the context of PCA, eigenvectors determine the direc ons of the new
feature space.
are the direc ons along which varia on in the data is measured. They are the axes along which the data is
most spread out.
The mathema cal review probably contains several covariance matrices (denoted as C) and their corresponding
eigenvalues and eigenvectors. For each matrix, there would be:
-
A covariance matrix C represen ng how much each variable in the dataset varies with every other variable.
A set of eigenvalues λ1,λ2,…, which represent the variance captured by each principal component.
A set of eigenvectors V, which represent the principal components themselves, giving the direc ons along
which, the data is spread out the most.
The visualiza ons in the image might be sca er plots that show how data is distributed along these principal
components, with the eigenvectors plo ed as lines or arrows indica ng the direc on of maximum variance and
their corresponding eigenvalues indica ng the magnitude or length.
The examples would illustrate different orienta ons and spreads of data points, showing how eigenvectors align
with these direc ons and the eigenvalues reflect the spread or concentra on along these eigenvectors.
Compute the Data Mean (µ): The average value of each feature across all data points.
Compute the Covariance Matrix (Σ): Imagine you're trying to see which items in your closet go together. The
covariance matrix tells you which features in your data change together (like matching shirts and pants).
Compute Top k Eigenvectors (Wk) and Eigenvalues (λk): Now you're picking the best combina ons (eigenvectors)
that give you the most variety (eigenvalues) from your closet.
Project Data X Using Wk (Z): You're now packing your suitcase with those best combina ons. In PCA, you're
transforming your data into a new set with fewer dimensions (less complexity).
Reconstruct Data X Using Z, µ (X): If you unpack your suitcase and lay out your ou its, you'll see they represent your
style without having everything from the closet. Similarly, you can approximately reconstruct your original data from
the reduced data, showing you've kept the essence.
The image you've provided appears to describe various methods for deciding how many principal components (PCs)
to keep when performing Principal Component Analysis (PCA). These methods help to simplify the dataset while
retaining the most significant features.
Rule of Thumb: This is a general guideline sugges ng that keeping between 2 to 5 principal components is o en
sufficient. This isn't a strict rule and depends on the dataset and the amount of variance you wish to retain.
Kaiser's Rule: This is a more specific criterion that says you should only keep principal components with eigenvalues
greater than or equal to 1. Eigenvalues measure the amount of variance captured by a principal component, so this
rule implies that any principal component that doesn't capture at least as much variance as a single original variable
should be dropped.
Scree Plot: This is a visual method where you plot the eigenvalues in descending order against the number of
corresponding components. You look for a point where the slope of the line changes most abruptly, which
resembles an "elbow." Principal components that appear before this elbow are considered significant and are
retained.
The scree plot typically shows a clear cutoff point — a er a certain number of components, the addi onal explained
variance they provide is minimal. This 'elbow' helps to visually iden fy the point a er which keeping addi onal
principal components is not adding much value.
1. Dimensionality Reduc on: This is the process of reducing the number of variables (or features) in a dataset.
Think of it like summarizing a book into a few key points instead of the full text.
2. Principal Component Analysis (PCA):
- Defini on: PCA is a technique that transforms a dataset with many dimensions (features) into one with fewer
dimensions. Imagine taking a complex object and cas ng a shadow of it that s ll retains the object's most
dis nct features.
- Objec ve: The goal of PCA is to keep as much informa on as possible despite reducing the number of
dimensions. This is like ensuring the shadow is as informa ve as possible about the shape of the object.
3. Mathema cal Founda on:
- Covariance Matrix: This matrix shows how variables in your dataset move together. If two variables increase
together, they have a posi ve rela onship; if one increases while the other decreases, they have a nega ve
rela onship.
- Eigenvalues: These are values that indicate how much variance (informa on and spread) there is in the data
for each principal component (new dimension). A higher eigenvalue means more informa on.
- Principal Components: These are the new direc ons in your data that maximize variance. They're like the
best angles to look at the object to understand its shape.
4. PCA Algorithm:
- Data Standardiza on: Before doing PCA, you usually need to make sure that all variables are on the same
scale, like ensuring all measurements are either in inches or cen meters, but not mixed.
- Compute Covariance Matrix: This involves calcula ng how each variable in your dataset relates to every
other variable.
- Find Eigenvectors and Eigenvalues: You calculate these from the covariance matrix to iden fy the principal
components and how much variance each one captures.
- Select Principal Components: You choose the principal components (the new dimensions) based on how
much informa on (variance) they capture, usually star ng with the ones with the highest eigenvalues.
- Project Input Data: Finally, you project (transform) your original data onto these new dimensions, effec vely
reducing the number of variables while keeping the most significant pa erns.
Lecture #10: Introduc on to Deep Learning
Ar ficial Neural Networks / The Perceptron Model
The image you’ve shared is likely explaining the concept of an ar ficial neuron, which is a fundamental building
block of an ar ficial neural network, o en compared to neurons in the human brain. Here’s a simple breakdown of
the components and how they work:
1. Inputs (x1, x2, ..., xd): These are the signals or data that the neuron receives, like the way a neuron in the
brain receives signals from other neurons.
2. Weights (w1, w2, ..., wd): Each input has an associated weight that represents its importance. The neuron in
a neural network learns to adjust these weights based on the data it receives over me, just as the synap c
strength between neurons in the brain can change.
3. Cell Body: In the metaphor, this is where all the inputs and weights are combined. The cell body sums up all
the weighted inputs.
4. Bias (b): This is like an offset or intercept in the neuron's ac vity. It allows the neuron to adjust its output
independently of its inputs, providing flexibility to the model.
5. Ac va on Func on (f): A er the inputs are weighted and summed, the ac va on func on is applied to this
sum. This func on determines whether the neuron should "fire" and by how much. The ac va on func on
introduces non-linearity into the model, which allows the neural network to handle complex pa erns.
6. Output (ŷ): This is the result of the neuron's processing — the signal it sends to the next layer of neurons or
as the final output of the network.
In summary, the image would be illustra ng how an ar ficial neuron takes in mul ple inputs, each of which is
mul plied by a learned weight, sums these together with a bias term, and then applies an ac va on func on to
produce an output, which is then sent to the next layer of the network or becomes part of the final output. This
process allows neural networks to learn from data and make predic ons or decisions.
Sigmoid Func on
- Squishes input values to
range between 0 and 1
- Useful to predict
probabili es.
- Example: Email spam /no
spam
Hyperbolic Tangent (Tanh) Func on Rec fied Linear Unit (ReLU) Func on
- Transforms inputs to values
- Sets all nega ve input values to
between -1 and 1
zero and keeps posi ve input
- Useful for tasks that need
values as they are
to differen ate between 2
- Used because it helps with
opposite classes or
computa onal efficiency and
direc ons
o en leads to good
- Example: Steering
performance in many different
mechanism for autonomous
types of neural networks
vehicle, turning le = -1,
- Commision-based salary model.
straight = 0, turning right =
If you don't make any sales
1
(nega ve input), you don't make
any money (output is 0).
However, the more sales you
make (posi ve input), the more
money you earn (output
increases linearly with input). So
if you don't perform, there's no
nega ve salary, but
performance directly translates
into earnings.
Mul -Layer Perceptron
The image likely provides an overview of a Mul -layer Perceptron (MLP), which is a type of ar ficial neural network
used for tasks such as classifica on and regression. Here's a simple explana on of the key points:
1. MLP as a Supervised Learning Approach:
- An MLP is used in supervised learning, meaning it learns to map input data to the correct output using
examples (data points with known outputs).
2. Func on Learning:
- The MLP's job is to learn a func on that can take a set of inputs and predict the correct output. This func on
is complex and non-linear, allowing the MLP to capture intricate pa erns in the data.
3. Layers of MLP:
- Input Layer: The star ng point of the network, which receives the ini al data. Each neuron in this layer
represents one feature of the input data.
- Hidden Layers: These layers are the 'thinking' part of the network, where the actual processing happens.
Each hidden layer transforms the inputs from the previous layer using weights (parameters), biases (offsets),
and ac va on func ons (non-linear transforma ons).
- Output Layer: The final layer that provides the predic ons or decisions made by the network. The number of
neurons in this layer typically corresponds to the number of classes in a classifica on task or just one neuron
for regression tasks.
4. Weights and Biases:
- Weights and biases are parameters that the MLP adjusts during training. Weights control the strength of the
connec on between neurons, and biases allow the ac va on of a neuron to be shi ed.
5. Hyperparameters:
- These are se ngs like the number of layers, number of neurons in each layer, learning rate, etc., that need to
be selected before training the network. They can significantly affect the network's performance and must
be chosen carefully, o en through a process of experimenta on.
An image of this sort would typically also show the connec ons between layers with lines and may include
mathema cal nota ons that represent the summing and ac va on steps within the neurons. It serves as a visual
guide to understanding how MLPs are structured and how they process informa on to learn from data.
In essence, the perceptron is the simplest form of an ar ficial neural network, while the mul -layer perceptron is a
more advanced and capable version that can solve more complex problems. The term "perceptron" o en refers to
the single-layer structure, whereas "mul -layer perceptron" refers to networks with mul ple layers that can learn
non-linear func ons.
Perceptron Model
- Type of linear classifier, which means it can only
separate data points using a straight line (or a
hyperplane in higher dimensions).
- It consists of a single layer of weights and is
used for simple tasks where a linear decision
boundary is sufficient.
- It takes input, mul plies it by weights, adds a
bias, and then passes it through a step func on
(a type of ac va on func on) to produce a
binary output.
- Examples: Email Spam Detec on, Binary
Classifica on
Mul -Layer Perceptron (MLP)
- More complex neural network that has one or
more hidden layers in addi on to the input and
output layers. Each layer consists of mul ple
perceptrons, hence the name "mul -layer."
- MLPs can model complex, non-linear
rela onships thanks to their mul ple layers and
non-linear ac va on func ons (like the sigmoid,
tanh, or ReLU func ons).
- MLPs can perform both classifica on and
regression tasks, including those that require
discovering intricate pa erns in the data.
- Examples: Handwri en Digit Recogni on,
Speech Recogni on, Stock Market Predic on,
Medical Diagnosis
The image you've shared seems to explain the training process of a Mul -layer Perceptron (MLP), a type of neural
network. Here's a simple breakdown:
Goal: The MLP aims to learn from data so that it can make accurate predic ons. It does this by adjus ng its internal
parameters (weights) to minimize errors in its predic ons. This process is akin to fine-tuning an instrument to get
the right pitch.
Input: You start with a dataset that has examples (inputs) and correct answers (outputs). These examples have
features (like the characteris cs of a song) and labels (like the genre of the song).
Output: A er training, the MLP gives you a set of learned weights. These weights represent the knowledge it gained
during training and are used to make predic ons.
Training Steps:
1. Ini alize Weights: The MLP starts with a set of random weights — think of these as random guesses at the
right se ngs.
2. Training Cycles (Epochs): The MLP goes through the dataset mul ple mes. Each complete pass is called an
epoch.
3. Batches: Instead of looking at the en re dataset at once, it looks at small subsets one by one. This is like
prac cing with just a few notes at a me instead of the en re song.
4. Compute Predic on: For each example in the batch, the MLP tries to predict the correct answer using its
current weights.
5. Compute Loss Func on: This is a way of measuring how wrong the MLP's predic ons are. A higher loss
means more error.
6. Update Parameters: Based on the loss, the MLP adjusts its weights. This is like tweaking the instrument's
se ngs to get closer to the right pitch.
7. Repeat: Steps 4-6 are repeated for several epochs, with the goal of con nually reducing the loss.
The image may also include mathema cal nota on showing how predic ons are made y^=f(W;x)) and how the loss
is calculated L(W;x,y)). It likely illustrates the gradient descent op miza on algorithm, which is how the MLP learns.
The η symbol represents the learning rate, which determines how big of a step to take when adjus ng weights.
In essence, the MLP is learning through trial and error, guided by the loss func on, to find the weight se ngs that
lead to the best performance on the training data. A er training, these weights can be used to make predic ons on
new, unseen data.
How do we op mize the weights?
The image you've shared seems to describe the process of op mizing the weights in an ar ficial neural network.
Goal: The purpose of training a neural network is to find the best set of weights (parameters) that allows the
network to make accurate predic ons.
Process:
1. Input Data (X): You have a dataset consis ng of examples. Each example has features (like the characteris cs
of an item) and a label (the correct answer or outcome).
2. Neural Network Func on (f(X, W)): The neural network takes the features of each example and uses its
current weights to make a predic on.
3. Predic on (^y^): The result of the neural network's func on is a predic on, which is the network's guess of
the label based on the input features and the current weights.
4. Loss Func on (L(W; x, y)): This func on measures how far off the predic ons are from the true labels. It's a
way of quan fying the network's error or "loss."
5. Op mizing Weights: The network's goal is to adjust its weights to minimize this loss across all examples in
the dataset. This process involves a lot of calcula ons to figure out whether to increase or decrease each
weight and by how much.
6. Op mal Weights (^W^): A er training, you end up with the op mal weights that give you the lowest possible
loss for your dataset.
In essence, training a neural network is like tuning an instrument to play the right notes: you keep adjus ng
(op mizing the weights) un l the music (predic ons) is just right (minimized loss).
Weight Ini aliza on: Xavier
The image appears to describe the Xavier (also
known as Glorot) ini aliza on method for se ng
the ini al weights in an ar ficial neural network.
Here's a simple explana on of the content:
In summary, Xavier ini aliza on is a strategy to
start the neural network's training process with
weights that are neither too small nor too large,
helping to ensure that the learning process
proceeds smoothly.
Xavier Weight Ini aliza on:
When you build a neural network, you start with
random weights. The Xavier method is a specific
way to choose these ini al random weights to help
the network learn effec vely.
Method:
1. Random Weight Ini aliza on
o Ini al weights are picked randomly.
o Random weight nr. Chosen from distribu on with mean of 0 and a specific variance.
2. Scale Weights:
o Weights are scaled according to number of input features.
o Helps keep outputs of neurons in each layer around the same scale.
o Cri cal for stable learning
The image you've shared likely illustrates the concept
of Batch Normaliza on; a technique used to improve
the training of deep neural networks. Here's what the
process typically involves, explained in simple terms:
Purpose: Make training of neural networks more
efficient and stable. Ensures that distribu on of each
layer’s input doesn’t change much, to prevent
problems during training.
Process:
1.
Compute Mini-batch Sta s cs: For each batch of
data processed by network, the algorithm calculates 2
sta s cs. Mean and Standard devia on
2.
Normalize and Scale Mini-batch Values: When
Mean and Standard devia on are known algorithm adjust outputs of neurons of batch, so the mean is 0 and
standard devia on is 1. Normalized values then scaled and shi ed using (γ and β).
Gradient Descent is an op miza on algorithm used to minimize the loss func on in neural networks. Here's what
the content might explain in simple terms:
Goal: The aim is to adjust the neural network's weights and biases to reduce errors in its predic ons. Think of it like
fine-tuning your radio to get the clearest signal.
Loss Func on (L(W, b)): This is a formula that tells us how far off our predic ons are from the actual values. The
lower the loss, the be er our model's predic ons.
Process:
1. Star ng Point: You begin with random guesses for the weights (W) and biases (b) of the network.
2. Training Loop: For a set number of cycles (epochs), you do the following:
o Calculate Gradient: Figure out which way to adjust the weights and biases to decrease the loss, much
like finding the steepest part of a hill to walk down.
o Update Parameters: Adjust the weights and biases slightly in the direc on that reduces the loss, using
the learning rate (η) to control how big of a step to take.
Gradient (∇L): This is a vector that points in the direc on of the steepest increase of the loss func on. By moving in
the opposite direc on, we can decrease the loss.
Learning Rate (η): This is a small number that determines how much we adjust the weights and biases by. If it's too
big, we might overshoot the lowest loss; if it's too small, the training might take too long.
Visual Representa on: There's likely a graph showing a curve that represents the loss func on. The goal of gradient
descent is to reach the lowest point of this curve.
The image may also show mathema cal equa ons that detail how the weights and biases are updated on each step
of the training process. The visualiza on helps to convey the concept that we're itera vely moving towards the best
set of parameters that make our model most accurate.
Summary: AI Neural Networks
Overview of ANNs:
- Defini on: ANNs are compu ng systems vaguely inspired by the neural networks that cons tute animal
brains. They are designed to recognize pa erns and interpret sensory data through a kind of machine
percep on, labeling, or raw input processing.
- Basic Unit: The neuron is the fundamental processing unit of an ANN, similar to the neurons in biological
brains. Each ar ficial neuron receives input, processes it, and passes on the output to the next layer of
neurons.
Architecture of Neural Networks:
- Input Layer: This is the entry point where the ANN receives the data to be processed.
- Hidden Layers: These layers are where the bulk of computa on takes place. They extract features and
pa erns from the input data, transforming it step by step. The network can have one or many hidden layers.
- Output Layer: This layer produces the final output of the network, such as a predic on or classifica on.
Neural Network Ac va on Func on:
- These func ons determine how much signal a neuron should pass forward. They introduce non-linearity to
the network's decision-making process, allowing it to handle complex tasks.
- Common Ac va on Func ons: ReLU (Rec fied Linear Unit) is great for avoiding the vanishing gradient
problem and is efficient to compute. Sigmoid and TanH are older func ons that map input values to a specific
range, with Sigmoid outpu ng between 0 and 1 (useful for probabili es) and TanH between -1 and 1.
Training Neural Networks:
- Backpropaga on: This is the key algorithm for training ANNs. It involves moving backward from the output
layer to the input layer, repeatedly adjus ng the weights of the connec ons between neurons to reduce the
error margin of the output.
- Cost Func on: Also known as a loss func on, it quan fies the difference between the network's predicted
output and the actual output. The goal of training is to minimize this cost func on.
Lecture #11 Deep Learning for Computer Vision
Computer Vision
Computer Vision: Field of AI that enables computers to interpret & understand visual informa on from the work,
like the way humans do. Involves extrac ng, analyzing, and understanding useful informa on from Images and
videos.
Convolu onal Neural Networks (CNNs): Specialized kinds of Neural Networks for processing data that has a grid-like
topology, such as images. Good for image and video recogni on tasks
Components of a CNN:
1. Convolu onal Layers: These layers perform convolu ons, which involve sliding a filter or kernel over the
input image to produce a feature map. This process extracts important features such as edges, textures, or
specific shapes.
2. Pooling Layers: Also known as subsampling, pooling layers reduce the spa al size of the feature map to
decrease the amount of computa on needed and to make the detec on of features invariant to scale and
orienta on.
3. Fully Connected Layers: A er several convolu onal and pooling layers, the high-level reasoning in the neural
network is done by fully connected layers. They take the features detected by the convolu onal layers and
use them to determine the final output, such as the classifica on of the image.
The Process in a CNN:
1. The network takes an input image and processes it through a series of convolu onal and pooling layers,
where each layer detects more complex features.
2. A er passing through the convolu onal layers, the data is fla ened into a one-dimensional array to be fed
into fully connected layers.
3. The fully connected layers func on similarly to a regular neural network, taking the extracted features to
make a final decision, like iden fying the object within an image.
Convolu onal Layers: Performs mathema cal opera ons called convolu on (linear opera on)
Process:
Start with input image (height, width,
depth (color images depth is = 3 (RGB))
Layer uses filter (Kernel) = small window
that slides over the image. Kernel has set of
weights = “w” , learned during training
As filter slides over image, performs an
element-wise mul plica on and sums results
into single number (convolu on opera on) = “z”
Resul ng Feature Map
- A er sliding the Kernel over all posi ons in the input image we get a FEATURE MAP.
- We can have mul ple feature maps, increases the depth of the output.
Why use convolu onal Layer?
- Good for capturing spa al hierarchies in images by recognizing pa erns (edges, corners, textures)
- Each Kernel detects different types of features.
CNN: Pooling Layer
Purpose: Used to reduce spa al dimensions
(height and width) of input feature maps
Opera on: Operates on each feature map
independently. Par ons Feature Maps into set
of non-overlapping rectangles & outputs the
maximum (max pooling) or average (average
pooling) = down sampling
No trainable Parameters: Unlike convolu onal
layers, pooling has no weights or biases to
learn.
Benefits: Reduces Size (make feature map
smaller), Controls Overfi ng, Spa al Invariance
(recognize features regardless of spa al
loca on)
Fully Connected Layer
Fla ening: Process where mul -dimensional
feature map done by convolu onal and pooling
layer gets transformed into a one-dimensional
vector.
Fully Connected Layer:
- A er fla ening, all data goes through one or
more layers where every input is connected to
every neuron (node)
- These layers responsible for high-level reasoning
in network
Output Layer: The connec ons between the last
hidden layer and the output layer are weighted
(denoted by Wo,bo in the image), and these
weights are adjusted during the training process to
map the learned features to the correct output.
Transfer Learning: Technique where model developed
for one task is reused as the star ng point for a model
on a second task.
Strategies Based on Data Availability and Similarity:
Different strategies for applying transfer learning
based on how much data you have for the new task
and how similar that new task is to the original task
the CNN was trained on:
Very Li le Data, Very Similar Dataset: If the new
dataset is very similar to ImageNet and you don't have
much data, you might "fine-tune" only the top layer of
the network. Essen ally, you use the CNN as a feature
extractor and train a linear classifier on top of these
features.
Lots of Data, Very Similar Dataset: If you have a lot of data and it's like ImageNet, you might fine-tune a few more
layers in the network since you have enough data to learn some new features without overfi ng.
Very Li le Data, Very Different Dataset: With a small dataset that's quite different from ImageNet, you might s ll use
the pre-trained network as a feature extractor, but you may need to collect more data or apply data augmenta on
techniques to effec vely train the new top layer.
Lots of Data, Very Different Dataset: If you have a lot of data but it's very different from ImageNet, you might choose
to fine-tune a larger number of layers or even the whole network. Since the dataset is significantly different, you
need to adjust more of the network's weights to adapt it to the new task.
Lecture #12: Deep Learning for Natural Language Processing
Natural Language Processing
Defini on: To build machines that understand and respond to text or voice data, and respond with text or speech of
their own -> just as humans
How are words represented in NLP?
One-Hot Encoding: Method to convert
categorical data (like words) into numerical
format that models can work with.
How it works: Each word in vocabulary is
represented as a unique vector in a high
dimensional space where the dimensionality
equals the number of words in the vocabulary.
Bag-of-Words (BoW) Model: Way to extract
features from text for use in machine learning
algorithms. Involves represen ng text data as a
“bag” of words without considering grammar
and word order.
How it works: Vocabulary is created with all
unique words from training set. Each word
assigned unique index.
Text documents then represented as vectors.
Word2Vec: Technique that transforms word
into numerical vectors, capturing seman c
rela onships between them.
How it works: Trains shallow neural network
model on large corpus of text. Models learns
to predict word based on its context (word
before and a er it).
Vector Representa on: A er training, each
work in vocabulary is associated with dese
vector that the model has learned.
Model
What It Is
Benefits
Bag-ofWords
(BoW)
A representa on of
text that describes the
occurrence of words
within a document. It
involves a vocabulary - Simple to
of known words and a understand and
measure of the
implement<br>presence of these
Works well with
words.
small vocabularies
Disadvantages
Examples of Use
- High-dimensional
and sparse<br>Loses the order of
- Document
words<br>- Does not classifica on<br>capture seman cs
Spam filtering
A Word2Vec
architecture that
predicts the target
word from a context.
Averages the context
of a word (e.g., the
Word2Vec words surrounding a
CBOW
target word).
- Efficient on small
datasets<br>Be er
representa on for
more frequent
words
- Less accurate with
rare words<br>- Genera ng word
Context window may embeddings<br>not capture enough Feeding into deeper
word rela onships language models
A Word2Vec
architecture that uses
a target word to
predict the
Word2Vec surrounding context
SG
words.
- Handles rare
words well<br>Captures more
word rela onships
due to predic ng
mul ple context
words
- Requires large
amounts of
data<br>- Slower to
train than CBOW
One-Hot
Encoding
- Genera ng word
embeddings<br>Understanding word
rela onships
A method to convert
categorical variables
into a binary vector
represen ng the
- Very high
presence of each
dimensional
category. In NLP, each
space<br>- Does not - Preliminary text data
word is represented by - Easy to
capture seman c
representa on<br>a vector where only
implement<br>meaning<br>Input for simpler
one element is '1', and Clear dis nc on
Inefficient for large machine learning
all others are '0'.
between categories vocabularies
models
One-Hot Encoding is o en the first step in transforming text data into a format that can be used by machine learning
algorithms. However, due to its limita ons in handling large vocabularies and inability to capture seman c
rela onships, it is usually replaced by more advanced techniques such as Word2Vec in prac cal applica ons.
Top of Form
Sequen al Models
Recurrent Neural Networks (RNNs)
How RNNs Work:
-An RNN processes one element of a sequence at a me (e.g., one word of a sentence or one frame of a video).
-At each me step “t”, the network takes two inputs: the current element “xt” from the sequence and the hidden
state “ht−1” from the previous me step, which contains informa on from earlier in the sequence.
-The hidden state “ht” at me step “t” is updated based on the previous hidden state and the current input. This is
done using a func on “f” with parameters “W”, which can be learned during training.
-The RNN can produce an output “yt” at each me step, which can be used for predic ons.
Long-Short Term Memory
Components of LSTM:
Forget Gate: Decides what informa on
we’re going to throw away from the
cell state.
Input Gate: Decides what new
informa on we’re going to store in the
cell state.
Cell State: The internal memory of the
LSTM, which carries informa on
throughout the processing of the
sequence.
Output Gate: Decides what the next
hidden state should be, which is used
in the predic on and passed to the
next me step.
Process in LSTM:
1. The forget gate takes the previous hidden state and the current input, and decides what informa on is to be
discarded from the cell state.
2. The input gate and a poten al update to the cell state create new cell state informa on.
3. The cell state is updated with this new informa on, effec vely allowing the LSTM to "remember" or "forget"
things.
4. Finally, the output gate decides what the next hidden state should be, which contains informa on based on
the input and the long-term memory of the cell state.
Transformers
Main Idea: Sentences are processed.
Tradi onal models processed sentences word by word in order, but Transformers can look at the en re sentence at
once. This helps the model understand the context be er.
Self-a en on: A 'unit' to compute similarity scores between words.
Self-a en on is a mechanism that allows each word in a sentence to consider (or a end to) all other words when
figuring out its own meaning. It's like every word in a sentence asking every other word, "How relevant are you to
me?" and using this informa on to adjust its own understanding.
Posi onal Embeddings: Replacement of recurrence. Encode informa on related to a specific posi on of a token in
a sentence.
Since Transformers process all words at once, they need a way to take into account the order of words, because in
language, order can change meaning. Posi onal embeddings are a way to give the model informa on about the
posi on of each word in the sentence.
Aspect
RNNs
LSTMs
Transformers
What They
Are
Networks with loops to
process sequence data.
Advanced RNNs with gates
for be er memory.
Networks using a en on
for parallel processing.
Differences
Sequen al processing,
prone to forge ng.
Sequen al but with longterm memory.
Parallel processing,
excellent long-term
memory.
Advantages
Simpler models, good for Can handle long sequences
short sequences.
be er than RNNs.
Struggle with long
sequences, slower
Disadvantages training.
Example Use
More complex and
computa onally heavy.
Text genera on with short Complex text genera on,
contexts.
speech recogni on.
Can process very long
sequences efficiently.
Requires lots of data and
compute power.
Large-scale NLP tasks,
advanced transla on.
0
You can add this document to your study collection(s)
Sign in Available only to authorized usersYou can add this document to your saved list
Sign in Available only to authorized users(For complaints, use another form )