Machine Learning Unit - 5
Machine Learning Unit - 5
DISTANCE MEASURES
They provide the foundation for many popular and effective machine learning
algorithms like k-nearest neighbors for supervised learning and k-means
clustering for unsupervised learning.
Different distance measures must be chosen and used depending on the types of
the data. As such, it is important to know how to implement and calculate a range
of different popular distance measures and the intuitions for the resulting scores.
1. Euclidean Distance
2. Manhattan Distance
3. Minkowski Distance
4. Hamming Distance
Euclidean Distance
Euclidean Distance represents the shortest distance between two [Link] is the
square root of the sum of squares of differences between corresponding elements.
So, the Euclidean Distance between these two points, A and B, will be:
We use this formula when we are dealing with 2 dimensions. We can generalize
this for an n-dimensional space as:
n = number of dimensions
pi, qi = data points
Manhattan Distance
Manhattan Distance is the sum of absolute differences between points across all
the dimensions.
Where,
n = number of dimensions
pi, qi = data points
Minkowski Distance
Minkowski Distance is the generalized form of Euclidean and Manhattan Distance.
Hamming Distance
Hamming Distance measures the similarity between two strings of the same length.
The Hamming Distance between two strings of the same length is the number of
positions at which the corresponding characters are different.
Let’s understand the concept using an example. Let’s say we have two strings:
Look carefully – seven characters are different, whereas two characters (the last
two characters) are similar:
Most commonly, the two objects are rows of data that describe a subject (such as
a person, car, or house), or an event (such as a purchase, a claim, or a diagnosis).
Perhaps the most likely way you will encounter distance measures is when you
are using a specific machine learning algorithm that uses distance measures at its
core. The most famous algorithm of this type is the k-nearest neighbors
algorithm, or KNN for short.
In the KNN algorithm, a classification or regression prediction is made for new
examples by calculating the distance between the new example (row) and all
examples (rows) in the training dataset. The k examples in the training dataset
with the smallest distance are then selected and a prediction is made by
averaging the outcome (mode of the class label or mean of the real value for
regression).
— Page 135, Data Mining: Practical Machine Learning Tools and Techniques, 4th
edition, 2016.
A short list of some of the more popular machine learning algorithms that use
distance measures at their core is as follows:
K-Nearest Neighbors
Learning Vector Quantization (LVQ)
Self-Organizing Map (SOM)
K-Means Clustering
There are many kernel-based methods may also be considered distance-based
algorithms. Perhaps the most widely known kernel method is the support vector
machine algorithm, or SVM for short.
o K-NN algorithm stores all the available data and classifies a new data point
based on the similarity. This means when new data appears then it can be
easily classified into a well suite category by using K- NN algorithm.
o K-NN algorithm can be used for Regression as well as for Classification but
mostly it is used for the Classification problems.
o It is also called a lazy learner algorithm because it does not learn from the
training set immediately instead it stores the dataset and at the time of
classification, it performs an action on the dataset.
o KNN algorithm at the training phase just stores the dataset and when it gets
new data, then it classifies that data into a category that is much similar to
the new data.
Suppose there are two categories, i.e., Category A and Category B, and we have a
new data point x1, so this data point will lie in which of these categories. To solve
this type of problem, we need a K-NN algorithm. With the help of K-NN, we can
easily identify the category or class of a particular dataset. Consider the below
diagram:
The K-NN working can be explained on the basis of the below algorithm:
o Step-4: Among these k neighbors, count the number of the data points in
each category.
o Step-5: Assign the new data points to that category for which the number of
the neighbor is maximum.
o Firstly, we will choose the number of neighbors, so we will choose the k=5.
o Next, we will calculate the Euclidean distance between the data points. The
Euclidean distance is the distance between two points, which we have
already studied in geometry. It can be calculated as:
o As we can see the 3 nearest neighbors are from category A, hence this new
data point must belong to category A.
Below are some points to remember while selecting the value of K in the K-NN
algorithm:
o A very low value for K such as K=1 or K=2, can be noisy and lead to the effects
of outliers in the model.
o Large values for K are good, but it may find some difficulties.
o It is simple to implement.
o Always needs to determine the value of K which may be complex some time.
k-means algorithm:
Hence each cluster has datapoints with some commonalities, and it is away from
other clusters.
The below diagram explains the working of the K-means Clustering Algorithm:
Step-2: Select random K points or centroids. (It can be other from the input
dataset).
Step-3: Assign each data point to their closest centroid, which will form the
predefined K clusters.
Step-4: Calculate the variance and place a new centroid of each cluster.
Step-5: Repeat the third steps, which means reassign each datapoint to the new
closest centroid of each cluster.
Suppose we have two variables M1 and M2. The x-y axis scatter plot of these two
variables is given below:
o Let's take number k of clusters, i.e., K=2, to identify the dataset and to put
them into different clusters. It means here we will try to group these datasets
into two different clusters.
o We need to choose some random k points or centroid to form the cluster.
These points can be either the points from the dataset or any other point.
So, here we are selecting the below two points as k points, which are not the
o Now we will assign each data point of the scatter plot to its closest K-point
or centroid. We will compute it by applying some mathematics that we have
studied to calculate the distance between two points. So, we will draw a
median between both the centroids. Consider the below image:
From the above image, it is clear that points left side of the line is near to the K1 or
blue centroid, and points to the right of the line are close to the yellow centroid.
Let's color them as blue and yellow for clear visualization.
o Next, we will reassign each datapoint to the new centroid. For this, we will
repeat the same process of finding a median line. The median will be like
From the above image, we can see, one yellow point is on the left side of the line,
and two blue points are right to the line. So, these three points will be assigned to
new centroids.
As reassignment has taken place, so we will again go to the step-4, which is finding
new centroids or K-points.
o As we got the new centroids so again will draw the median line and reassign
the data points. So, the image will be:
o We can see in the above image; there are no dissimilar data points on either
side of the line, which means our model is formed. Consider the below
As our model is ready, so we can now remove the assumed centroids, and the two
final clusters will be as shown in the below image:
K-Medoids:
Medoid: A Medoid is a point in the cluster from which the sum of distances to other data
points is minimal.
(or)
A Medoid is a point in the cluster from which dissimilarities with all the other points in the
clusters are minimal.
PAM is the most powerful algorithm of the three algorithms but has the disadvantage of
time complexity. The following K-Medoids are performed using PAM. In the further parts,
we'll see what CLARA and CLARANS are.
Algorithm:
Given the value of k and unlabelled data:
1. Choose k number of random points from the data and assign these k points to k number
of clusters. These are the initial medoids.
2. For all the remaining data points, calculate the distance from each medoid and assign it
to the cluster with the nearest medoid.
3. Calculate the total cost (Sum of all the distances from all the data points to the medoids)
4. Select a random point as the new medoid and swap it with the previous medoid. Repeat
2 and 3 steps.
5. If the total cost of the new medoid is less than that of the previous medoid, make the new
medoid permanent and repeat step 4.
6. If the total cost of the new medoid is greater than the cost of the previous medoid, undo
the swap and repeat step 4.
7. The Repetitions have to continue until no change is encountered with new medoids to
classify data points.
Both algorithms group n objects into k clusters based on similar traits where k is pre-defined.
Clustering is done based on distance from centroids. Clustering is done based on distance
from medoids.
A centroid can be a data point or some other point in A medoid is always a data point in the cluster.
the cluster
Can't cope with outlier data Can manage outlier data too
Sometimes, outlier sensitivity can turn out to be useful Tendency to ignore meaningful clusters in
outlier data
What Is Ensemble?
The ensemble methods in machine learning combine the insights obtained from
multiple learning models to facilitate accurate and improved decisions. These methods
follow the same principle as the example of buying an air-conditioner cited above.
BAGGING VS BOOSTING
We all use the Decision Tree Technique on day to day life to make the decision.
Organizations use these supervised machine learning techniques like Decision trees
to make a better decision and to generate more surplus and profit.
There are two techniques given below that are used to perform ensemble decision
tree.
Bagging is used when our objective is to reduce the variance of a decision tree. Here
the concept is to create a few subsets of data from the training sample, which is
chosen randomly with replacement. Now each collection of subset data is used to
prepare their decision trees thus, we end up with an ensemble of various models.
The average of all the assumptions from numerous tress is used, which is more
powerful than a single decision tree.
Random Forest is an expansion over bagging. It takes one additional step to predict
a random subset of data. It also makes the random selection of features rather than
using all features to develop trees. When we have numerous random trees, it is
called the Random Forest.
These are the following steps which are taken to implement a Random forest:
o The given steps are repeated, and prediction is given, which is based on the
collection of predictions from n number of trees.
BOOSTING:
If a given input is misclassifieyed by theory, then its weight is increased so that the
upcoming hypothesis is more likely to classify it correctly by consolidating the
entire set at last converts weak learners into better performing models.
It utilizes a gradient descent algorithm that can optimize any differentiable loss
function. An ensemble of trees is constructed individually, and individual trees are
summed successively. The next tree tries to restore the loss ( It is the difference
between actual and predicted values).
The greater number of trees in the forest leads to higher accuracy and prevents
the problem of overfitting.
The below diagram explains the working of the Random Forest algorithm:
Since the random forest combines multiple trees to predict the class of the dataset,
it is possible that some decision trees may predict the correct output, while others
may not. But together, all the trees predict the correct output. Therefore, below
are two assumptions for a better Random forest classifier:
o There should be some actual values in the feature variable of the dataset so
that the classifier can predict accurate results rather than a guessed result.
o The predictions from each tree must have very low correlations.
Below are some points that explain why we should use the Random Forest
algorithm:
<="" li="">
o It predicts output with high accuracy, even for the large dataset it runs
efficiently.
Below are some points that explain why we should use the Random Forest
algorithm:
<="" li="">
o It predicts output with high accuracy, even for the large dataset it runs
efficiently.
The Working process can be explained in the below steps and diagram:
Step-2: Build the decision trees associated with the selected data points (Subsets).
Step-3: Choose the number N for decision trees that you want to build.
The working of the algorithm can be better understood by the below example:
Example: Suppose there is a dataset that contains multiple fruit images. So, this
dataset is given to the Random forest classifier. The dataset is divided into subsets
and given to each decision tree. During the training phase, each decision tree
produces a prediction result, and when a new data point occurs, then based on the
majority of results, the Random Forest classifier predicts the final decision.
Consider the below image:
There are mainly four sectors where Random forest mostly used:
2. Medicine: With the help of this algorithm, disease trends and risks of the
disease can be identified.
3. Land Use: We can identify the areas of similar land use by this algorithm.
o It enhances the accuracy of the model and prevents the overfitting issue.
o Although random forest can be used for both classification and regression
tasks, it is not more suitable for Regression tasks.
Since deep learning has been evolved by the machine learning, which itself is a
subset of artificial intelligence and as the idea behind the artificial intelligence is to
mimic the human behavior, so same is "the idea of deep learning to build such
algorithm that can mimic the brain".
Deep learning is implemented with the help of Neural Networks, and the idea
behind the motivation of Neural Network is the biological neurons, which is
nothing but a brain cell.
So basically, deep learning is implemented by the help of deep networks, which are
nothing but neural networks with multiple hidden layers.
In the example given above, we provide the raw data of images to the first layer of
the input layer. After then, these input layer will determine the patterns of local
Dept of CSE, ASGI B. Uma Maheswari
Assistant Professor
contrast that means it will differentiate on the basis of colors, luminosity, etc. Then
the 1st hidden layer will determine the face feature, i.e., it will fixate on eyes, nose,
and lips, etc. And then, it will fixate those face features on the correct face
template. So, in the 2nd hidden layer, it will actually determine the correct face here
as it can be seen in the above image, after which it will be sent to the output layer.
Likewise, more hidden layers can be added to solve more complex problems, for
example, if you want to find out a particular kind of face having large or light
complexions. So, as and when the hidden layers increase, we are able to solve
complex problems.
Architectures
o DeepNeuralNetworks
It is a neural network that incorporates the complexity of a certain level,
which means several numbers of hidden layers are encompassed in between
the input and output layers. They are highly proficient on model and process
non-linear associations.
o DeepBeliefNetworks
A deep belief network is a class of Deep Neural Network that comprises of
multi-layer belief networks.
Steps to perform DBN:
2. Next, the formerly trained features are treated as visible units, which
perform learning of features.
o RecurrentNeuralNetworks
It permits parallel as well as sequential computation, and it is exactly similar
to that of the human brain (large feedback network of connected neurons).
Since they are capable enough to reminisce all of the imperative things
related to the input they have received, so they are more precise.
o Self-DrivingCars
In self-driven cars, it is able to capture the images around it by processing a
huge amount of data, and then it will decide which actions should be
incorporated to take a left or right or should it stop. So, accordingly, it will
decide what actions it should take, which will further reduce the accidents
that happen every year.
o VoiceControlledAssistance
When we talk about voice control assistance, then Siri is the one thing that
comes into our mind. So, you can tell Siri whatever you want it to do it for
you, and it will search it for you and display it for you.
o AutomaticImageCaptionGeneration
Whatever image that you upload, the algorithm will work in such a way that
it will generate caption accordingly. If you say blue colored eye, it will display
a blue-colored eye with a caption at the bottom of the image.
Limitations
Advantages
Disadvantages
o Since there is no labeled data, so the agent is bound to learn by its experience
only.
o The agent interacts with the environment and explores it by itself. The
primary goal of an agent in reinforcement learning is to improve the
performance by getting the maximum positive rewards.
o The agent learns with the process of hit and trial, and based on the
experience, it learns to perform the task in a better way. Hence, we can say
that "Reinforcement learning is a type of machine learning method where
an intelligent agent (computer program) interacts with the environment
and learns to act within that." How a Robotic dog learns the movement of
his arms is an example of Reinforcement learning.
o It is a core part of Artificial intelligence, and all AI agent works on the concept
of reinforcement learning. Here we do not need to pre-program the agent,
as it learns from its own experience without any human intervention.
o The agent learns that what actions lead to positive feedback or rewards and
what actions lead to negative feedback penalty. As a positive reward, the
agent gets a positive point, and as a penalty, it gets a negative point.
o Agent(): An entity that can perceive/explore the environment and act upon
it.
o Policy(): Policy is a strategy applied by the agent for the next action based on
the current state.
o In RL, the agent is not instructed about the environment and what actions
need to be taken.
o The agent takes the next action and changes states according to the feedback
of the previous action.
o Negative Reinforcement
Positive Reinforcement:
This type of reinforcement can sustain the changes for a long time, but too much
positive reinforcement may lead to an overload of states that can reduce the
consequences.
Negative Reinforcement:
o Q-Learning:
o It learns the value function Q (S, a), which means how good to take
action "a" at a particular state "s."
o SARSA stands for State Action Reward State action, which is an on-
policy temporal difference learning method. The on-policy control
method selects the action for each state while learning using a specific
policy.
o In SARSA, new action and reward are selected using the same policy,
which has determined the original action.