Unit II
Unit II
LINEAR METHODS:
The term linear model implies that the model is specified as a linear combination of features.
Based on training data, the learning process computes one weight for each feature to form a
model that can predict or estimate the target value.
REGRESSION:
Regression is a supervised learning technique which helps in finding the correlation between
variables and enables us to predict the continuous output variable based on the one or more
predictor variables. It is mainly used for prediction, forecasting, time series modeling, and
determining the causal-effect relationship between variables.
Regression analysis is a statistical method to model the relationship between a dependent (target)
and independent (predictor) variables with one or more independent variables. More specifically,
Regression analysis helps us to understand how the value of the dependent variable is changing
corresponding to an independent variable when other independent variables are held fixed. It
predicts continuous/real values such as temperature, age, salary, price, etc.
We can understand the concept of regression analysis using the below example:
Example: Suppose there is a marketing company A, who does various advertisement every year
and get sales on that. The below list shows the advertisement made by the company in the last 5
years and the corresponding sales:
Now, the company wants to do the advertisement of $200 in the year 2019 and wants to know
the prediction about the sales for this year. So to solve such type of prediction problems in
machine learning, we need regression [Link] Tutorial
Regression is a Supervised learning technique which helps in finding the correlation between
variables and enables us to predict the continuous output variable based on the one or more
predictor variables. It is mainly used for prediction, forecasting, time series modeling, and
determining the causal-effect relationship between variable
In Regression, we plot a graph between the variables which best fits the given datapoints, using
this plot, the machine learning model can make predictions about the data. In simple
words, "Regression shows a line or curve that passes through all the datapoints on target-
predictor graph in such a way that the vertical distance between the datapoints and the
regression line is minimum." The distance between datapoints and line tells whether a model
has captured a strong relationship or not.
As mentioned above, Regression analysis helps in the prediction of a continuous variable. There
are various scenarios in the real world where we need some future predictions such as weather
condition, sales prediction, marketing trends, etc., for such case we need some technology which
can make predictions more accurately. So for such case we need Regression analysis which is a
statistical method and used in machine learning and data science. Below are some other reasons
for using Regression analysis:
o Regression estimates the relationship between the target and the independent variable.
o It is used to find the trends in data.
o It helps to predict real/continuous values.
o By performing the regression, we can confidently determine the most important factor,
the least important factor, and how each factor is affecting the other factors.
Types of Regression
There are various types of regressions which are used in data science and machine learning. Each
type has its own importance on different scenarios, but at the core, all the regression methods
analyze the effect of the independent variable on dependent variables. Here we are discussing
some important types of regression which are given below:
o Linear Regression
o Logistic Regression
o Polynomial Regression
o Support Vector Regression
o Decision Tree Regression
o Random Forest Regression
o Ridge Regression
o Lasso Regression:
Linear Regression:
o Linear regression is a statistical regression method which is used for predictive analysis.
o It is one of the very simple and easy algorithms which works on regression and shows the
relationship between the continuous variables.
o It is used for solving the regression problem in machine learning.
o Linear regression shows the linear relationship between the independent variable (X-axis)
and the dependent variable (Y-axis), hence called linear regression.
o If there is only one input variable (x), then such linear regression is called simple linear
regression. And if there is more than one input variable, then such linear regression is
called multiple linear regression.
o The relationship between variables in the linear regression model can be explained using
the below image. Here we are predicting the salary of an employee on the basis of the
year of experience.
Y= aX+b
Here,
Logistic Regression:
o Logistic regression is another supervised learning algorithm which is used to solve the
classification problems. In classification problems, we have dependent variables in a
binary or discrete format such as 0 or 1.
o Logistic regression algorithm works with the categorical variable such as 0 or 1, Yes or
No, True or False, Spam or not spam, etc.
o It is a predictive analysis algorithm which works on the concept of probability.
o Logistic regression is a type of regression, but it is different from the linear regression
algorithm in the term how they are used.
o Logistic regression uses sigmoid function or logistic function which is a complex cost
function. This sigmoid function is used to model the data in logistic regression. The
function can be represented as:
When we provide the input values (data) to the function, it gives the S-curve as follows:
o It uses the concept of threshold levels, values above the threshold level are rounded up to
1, and values below the threshold level are rounded up to 0.
o Binary(0/1, pass/fail)
o Multi(cats, dogs, lions)
o Ordinal(low, medium, high)
Polynomial Regression:
o The equation for polynomial regression also derived from linear regression equation that
means Linear regression equation Y= b0+ b1 x, is transformed into Polynomial regression
equation Y= b0+b1 x+ b2x2+ b3x3+.....+ bnxn.
o Here Y is the predicted/target output, b0, b1,... bn are the regression coefficients. x is
our independent/input variable.
o The model is still linear as the coefficients are still linear with quadratic
Support Vector Machine is a supervised learning algorithm which can be used for regression as
well as classification problems. So if we use it for regression problems, then it is termed as
Support Vector Regression.
Support Vector Regression is a regression algorithm which works for continuous variables.
Below are some keywords which are used in Support Vector Regression:
o Kernel: It is a function used to map a lower-dimensional data into higher dimensional
data.
o Hyperplane: In general SVM, it is a separation line between two classes, but in SVR, it
is a line which helps to predict the continuous variables and cover most of the datapoints.
o Boundary line: Boundary lines are the two lines apart from hyperplane, which creates a
margin for datapoints.
o Support vectors: Support vectors are the datapoints which are nearest to the hyperplane
and opposite class.
In SVR, we always try to determine a hyperplane with a maximum margin, so that maximum
number of datapoints are covered in that margin. The main goal of SVR is to consider the
maximum datapoints within the boundary lines and the hyperplane (best-fit line) must contain
a maximum number of datapoints. Consider the below image:
Here, the blue line is called hyperplane, and the other two lines are known as boundary lines.
o Decision Tree is a supervised learning algorithm which can be used for solving both
classification and regression problems.
o It can solve problems for both categorical and numerical data
o Decision Tree regression builds a tree-like structure in which each internal node
represents the "test" for an attribute, each branch represent the result of the test, and each
leaf node represents the final decision or result.
o A decision tree is constructed starting from the root node/parent node (dataset), which
splits into left and right child nodes (subsets of dataset). These child nodes are further
divided into their children node, and themselves become the parent node of those nodes.
Consider the below image:
Above image showing the example of Decision Tee regression, here, the model is trying to
predict the choice of a person between Sports cars or Luxury car.
o Random forest is one of the most powerful supervised learning algorithms which is
capable of performing regression as well as classification tasks.
o The Random Forest regression is an ensemble learning method which combines multiple
decision trees and predicts the final output based on the average of each tree output. The
combined decision trees are called as base models, and it can be represented more
formally as:
o Ridge regression is one of the most robust versions of linear regression in which a small
amount of bias is introduced so that we can get better long term predictions.
o The amount of bias added to the model is known as Ridge Regression penalty. We can
compute this penalty term by multiplying with the lambda to the squared weight of each
individual features.
o The equation for ridge regression will be:
o A general linear or polynomial regression will fail if there is high collinearity between the
independent variables, so to solve such problems, Ridge regression can be used.
o Ridge regression is a regularization technique, which is used to reduce the complexity of
the model. It is also called as L2 regularization.
o It helps to solve the problems if we have more parameters than samples.
Lasso Regression:
o Lasso regression is another regularization technique to reduce the complexity of the
model.
o It is similar to the Ridge Regression except that penalty term contains only the absolute
weights instead of a square of weights.
o Since it takes absolute values, hence, it can shrink the slope to 0, whereas Ridge
Regression can only shrink it near to 0.
o It is also called as L1 regularization. The equation for Lasso regression will be:
CLASSIFICATION:
What is the Classification Algorithm?
The Classification algorithm is a Supervised Learning technique that is used to identify the
category of new observations on the basis of training data. In Classification, a program learns
from the given dataset or observations and then classifies new observation into a number of
classes or groups. Such as, Yes or No, 0 or 1, Spam or Not Spam, cat or dog, etc. Classes can
be called as targets/labels or categories.
Unlike regression, the output variable of Classification is a category, not a value, such as "Green
or Blue", "fruit or animal", etc. Since the Classification algorithm is a Supervised learning
technique, hence it takes labeled input data, which means it contains input with the
corresponding output.
The main goal of the Classification algorithm is to identify the category of a given dataset, and
these algorithms are mainly used to predict the output for the categorical data.
Classification algorithms can be better understood using the below diagram. In the below
diagram, there are two classes, class A and Class B. These classes have features that are similar
to each other and dissimilar to other classes.
The algorithm which implements the classification on a dataset is known as a classifier. There
are two types of Classifications:
o Binary Classifier: If the classification problem has only two possible outcomes, then it is
called as Binary Classifier.
Examples: YES or NO, MALE or FEMALE, SPAM or NOT SPAM, CAT or DOG, etc.
o Multi-class Classifier: If a classification problem has more than two outcomes, then it is
called as Multi-class Classifier.
Example: Classifications of types of crops, Classification of types of music.
1. Lazy Learners: Lazy Learner firstly stores the training dataset and wait until it receives
the test dataset. In Lazy learner case, classification is done on the basis of the most
related data stored in the training dataset. It takes less time in training but more time for
predictions.
Example: K-NN algorithm, Case-based reasoning
2. Eager Learners:Eager Learners develop a classification model based on a training
dataset before receiving a test dataset. Opposite to Lazy learners, Eager Learner takes
more time in learning, and less time in prediction. Example: Decision Trees, Naïve
Bayes, ANN.
Classification Algorithms can be further divided into the Mainly two category:
o Linear Models
o Logistic Regression
o Support Vector Machines
o Non-linear Models
o K-Nearest Neighbours
o Kernel SVM
o Naïve Bayes
o Decision Tree Classification
o Random Forest Classification
?(ylog(p)+(1?y)log(1?p))
2. Confusion Matrix:
o The confusion matrix provides us a matrix/table as output and describes the performance
of the model.
o It is also known as the error matrix.
o The matrix consists of predictions result in a summarized form, which has a total number
of correct predictions and incorrect predictions. The matrix looks like as below table:
Actual Positive Actual Negative
3. AUC-ROC curve:
o ROC curve stands for Receiver Operating Characteristics Curve and AUC stands
for Area Under the Curve.
o It is a graph that shows the performance of the classification model at different
thresholds.
o To visualize the performance of the multi-class classification model, we use the AUC-
ROC Curve.
o The ROC curve is plotted with TPR and FPR, where TPR (True Positive Rate) on Y-axis
and FPR(False Positive Rate) on X-axis.
Classification algorithms can be used in different places. Below are some popular use cases of
Classification Algorithms:
PERCEPTRON:
In Machine Learning and Artificial Intelligence, Perceptron is the most commonly used term for
all folks. It is the primary step to learn Machine Learning and Deep Learning technologies,
which consists of a set of weights, input values or scores, and a threshold. Perceptron is a
building block of an Artificial Neural Network. Initially, in the mid of 19th century, Mr.
Frank Rosenblatt invented the Perceptron for performing certain calculations to detect input
data capabilities or business intelligence. Perceptron is a linear Machine Learning algorithm used
for supervised learning for various binary classifiers. This algorithm enables neurons to learn
elements and processes them one by one during preparation. In this tutorial, "Perceptron in
Machine Learning," we will discuss in-depth knowledge of Perceptron and its basic functions in
brief. Let's start with the basic introduction of Perceptron.
Perceptron model is also treated as one of the best and simplest types of Artificial Neural
networks. However, it is a supervised learning algorithm of binary classifiers. Hence, we can
consider it as a single-layer neural network with four main parameters, i.e., input values,
weights and Bias, net sum, and an activation function.
In Machine Learning, binary classifiers are defined as the function that helps in deciding whether
input data can be represented as vectors of numbers and belongs to some specific class.
Binary classifiers can be considered as linear classifiers. In simple words, we can understand it
as a classification algorithm that can predict linear predictor function in terms of weight
and feature vectors.
Mr. Frank Rosenblatt invented the perceptron model as a binary classifier which contains three
main components. These are as follows:
o Input Nodes or Input Layer:
This is the primary component of Perceptron which accepts the initial data into the system for
further processing. Each input node contains a real numerical value.
Weight parameter represents the strength of the connection between units. This is another most
important parameter of Perceptron components. Weight is directly proportional to the strength of
the associated input neuron in deciding the output. Further, Bias can be considered as the line of
intercept in a linear equation.
o Activation Function:
These are the final and important components that help to determine whether the neuron will fire
or not. Activation Function can be considered primarily as a step function.
o Sign function
o Step function, and
o Sigmoid function
The data scientist uses the activation function to take a subjective decision based on various
problem statements and forms the desired outputs. Activation function may differ (e.g., Sign,
Step, and Sigmoid) in perceptron models by checking whether the learning process is slow or has
vanishing or exploding gradients.
This step function or Activation function plays a vital role in ensuring that output is mapped
between required values (0,1) or (-1,1). It is important to note that the weight of input is
indicative of the strength of a node. Similarly, an input's bias value gives the ability to shift the
activation function curve up or down.
Step-1
In the first step first, multiply all input values with corresponding weight values and then add
them to determine the weighted sum. Mathematically, we can calculate the weighted sum as
follows:
Add a special term called bias 'b' to this weighted sum to improve the model's performance.
∑wi*xi + b
Step-2
In the second step, an activation function is applied with the above-mentioned weighted sum,
which gives us output either in binary form or a continuous value as follows:
Y = f(∑wi*xi + b)
Based on the layers, Perceptron models are divided into two types. These are as follows:
This is one of the easiest Artificial neural networks (ANN) types. A single-layered perceptron
model consists feed-forward network and also includes a threshold transfer function inside the
model. The main objective of the single-layer perceptron model is to analyze the linearly
separable objects with binary outcomes.
In a single layer perceptron model, its algorithms do not contain recorded data, so it begins with
inconstantly allocated input for weight parameters. Further, it sums up all inputs (weight). After
adding all inputs, if the total sum of all inputs is more than a pre-determined value, the model
gets activated and shows the output value as +1.
If the outcome is same as pre-determined or threshold value, then the performance of this model
is stated as satisfied, and weight demand does not change. However, this model consists of a few
discrepancies triggered when multiple weight inputs values are fed into the model. Hence, to find
desired output and minimize errors, some changes should be necessary for the weights input.
Like a single-layer perceptron model, a multi-layer perceptron model also has the same model
structure but has a greater number of hidden layers.
The multi-layer perceptron model is also known as the Backpropagation algorithm, which
executes in two stages as follows:
o Forward Stage: Activation functions start from the input layer in the forward stage and
terminate on the output layer.
o Backward Stage: In the backward stage, weight and bias values are modified as per the
model's requirement. In this stage, the error between actual output and demanded
originated backward on the output layer and ended on the input layer.
Hence, a multi-layered perceptron model has considered as multiple artificial neural networks
having various layers in which activation function does not remain linear, similar to a single
layer perceptron model. Instead of linear, activation function can be executed as sigmoid, TanH,
ReLU, etc., for deployment.
A multi-layer perceptron model has greater processing power and can process linear and non-
linear patterns. Further, it can also implement logic gates such as AND, OR, XOR, NAND,
NOT, XNOR, NOR.
Perceptron Function
Perceptron function ''f(x)'' can be achieved as output by multiplying the input 'x' with the learned
weight coefficient 'w'.
f(x)=1; if w.x+b>0
otherwise, f(x)=0
Characteristics of Perceptron
o The output of a perceptron can only be a binary number (0 or 1) due to the hard limit
transfer function.
o Perceptron can only be used to classify the linearly separable sets of input vectors. If
input vectors are non-linear, it is not easy to classify them properly.
Future of Perceptron
The future of the Perceptron model is much bright and significant as it helps to interpret data by
building intuitive patterns and applying them in the future. Machine learning is a rapidly growing
technology of Artificial Intelligence that is continuously evolving and in the developing phase;
hence the future of perceptron technology will continue to support and facilitate analytical
behavior in machines that will, in turn, add to the efficiency of computers.
The perceptron model is continuously becoming more advanced and working efficiently on
complex problems with the help of artificial neurons.
NEURAL NETWORKS
What are neural networks?
Neural networks, also known as artificial neural networks (ANNs) or simulated neural networks
(SNNs), are a subset of machine learning and are at the heart of deep learning algorithms. Their
name and structure are inspired by the human brain, mimicking the way that biological neurons
signal to one another.
Artificial neural networks (ANNs) are comprised of a node layers, containing an input layer, one
or more hidden layers, and an output layer. Each node, or artificial neuron, connects to another
and has an associated weight and threshold. If the output of any individual node is above the
specified threshold value, that node is activated, sending data to the next layer of the network.
Otherwise, no data is passed along to the next layer of the network.
Neural networks rely on training data to learn and improve their accuracy over time. However,
once these learning algorithms are fine-tuned for accuracy, they are powerful tools in computer
science and artificial intelligence, allowing us to classify and cluster data at a high velocity.
Tasks in speech recognition or image recognition can take minutes versus hours when compared
to the manual identification by human experts. One of the most well-known neural networks is
Google’s search algorithm.
Think of each individual node as its own linear regression model, composed of input data,
weights, a bias (or threshold), and an output. The formula would look something like this:
Once an input layer is determined, weights are assigned. These weights help determine the
importance of any given variable, with larger ones contributing more significantly to the output
compared to other inputs. All inputs are then multiplied by their respective weights and then
summed. Afterward, the output is passed through an activation function, which determines the
output. If that output exceeds a given threshold, it “fires” (or activates) the node, passing data to
the next layer in the network. This results in the output of one node becoming in the input of the
next node. This process of passing data from one layer to the next layer defines this neural
network as a feedforward network.
Let’s break down what one single node might look like using binary values. We can apply this
concept to a more tangible example, like whether you should go surfing (Yes: 1, No: 0). The
decision to go or not to go is our predicted outcome, or y-hat. Let’s assume that there are three
factors influencing your decision-making:
Now, we need to assign some weights to determine importance. Larger weights signify that
particular variables are of greater importance to the decision or outcome.
Finally, we’ll also assume a threshold value of 3, which would translate to a bias value of –3.
With all the various inputs, we can start to plug in values into the formula to get the desired
output.
In the example above, we used perceptrons to illustrate some of the mathematics at play here, but
neural networks leverage sigmoid neurons, which are distinguished by having values between 0
and 1. Since neural networks behave similarly to decision trees, cascading data from one node to
another, having x values between 0 and 1 will reduce the impact of any given change of a single
variable on the output of any given node, and subsequently, the output of the neural network.
As we start to think about more practical use cases for neural networks, like image recognition or
classification, we’ll leverage supervised learning, or labeled datasets, to train the algorithm. As
we train the model, we’ll want to evaluate its accuracy using a cost (or loss) function. This is also
commonly referred to as the mean squared error (MSE). In the equation below,
Ultimately, the goal is to minimize our cost function to ensure correctness of fit for any given
observation. As the model adjusts its weights and bias, it uses the cost function and
reinforcement learning to reach the point of convergence, or the local minimum. The process in
which the algorithm adjusts its weights is through gradient descent, allowing the model to
determine the direction to take to reduce errors (or minimize the cost function). With each
training example, the parameters of the model adjust to gradually converge at the minimum.
See this IBM Developer article for a deeper explanation of the quantitative concepts involved in
neural networks.
Most deep neural networks are feedforward, meaning they flow in one direction only, from input
to output. However, you can also train your model through backpropagation; that is, move in the
opposite direction from output to input. Backpropagation allows us to calculate and attribute the
error associated with each neuron, allowing us to adjust and fit the parameters of the model(s)
appropriately.
Neural networks can be classified into different types, which are used for different purposes.
While this isn’t a comprehensive list of types, the below would be representative of the most
common types of neural networks that you’ll come across for its common use cases:
The perceptron is the oldest neural network, created by Frank Rosenblatt in 1958. It has a single
neuron and is the simplest form of a neural network:
Feedforward neural networks, or multi-layer perceptrons (MLPs), are what we’ve primarily been
focusing on within this article. They are comprised of an input layer, a hidden layer or layers,
and an output layer. While these neural networks are also commonly referred to as MLPs, it’s
important to note that they are actually comprised of sigmoid neurons, not perceptrons, as most
real-world problems are nonlinear. Data usually is fed into these models to train them, and they
are the foundation for computer vision, natural language processing, and other neural networks.
Convolutional neural networks (CNNs) are similar to feedforward networks, but they’re usually
utilized for image recognition, pattern recognition, and/or computer vision. These networks
harness principles from linear algebra, particularly matrix multiplication, to identify patterns
within an image.
Recurrent neural networks (RNNs) are identified by their feedback loops. These learning
algorithms are primarily leveraged when using time-series data to make predictions about future
outcomes, such as stock market predictions or sales forecasting.
Deep Learning and neural networks tend to be used interchangeably in conversation, which can
be confusing. As a result, it’s worth noting that the “deep” in deep learning is just referring to the
depth of layers in a neural network. A neural network that consists of more than three layers—
which would be inclusive of the inputs and the output—can be considered a deep learning
algorithm. A neural network that only has two or three layers is just a basic neural network.
To learn more about the differences between neural networks and other forms of artificial
intelligence, like machine learning, please read the blog post “AI vs. Machine Learning vs. Deep
Learning vs. Neural Networks: What’s the Difference?”
The history of neural networks is longer than most people think. While the idea of “a machine
that thinks” can be traced to the Ancient Greeks, we’ll focus on the key events that led to the
evolution of thinking around neural networks, which has ebbed and flowed in popularity over the
years:
1943: Warren S. McCulloch and Walter Pitts published “A logical calculus of the ideas
immanent in nervous activity (PDF, 1 MB) (link resides outside IBM)” This research sought to
understand how the human brain could produce complex patterns through connected brain cells,
or neurons. One of the main ideas that came out of this work was the comparison of neurons with
a binary threshold to Boolean logic (i.e., 0/1 or true/false statements).
1958: Frank Rosenblatt is credited with the development of the perceptron, documented in his
research, “The Perceptron: A Probabilistic Model for Information Storage and Organization in
the Brain” (PDF, 1.6 MB) (link resides outside IBM). He takes McCulloch and Pitt’s work a step
further by introducing weights to the equation. Leveraging an IBM 704, Rosenblatt was able to
get a computer to learn how to distinguish cards marked on the left vs. cards marked on the right.
1974: While numerous researchers contributed to the idea of backpropagation, Paul Werbos was
the first person in the US to note its application within neural networks within his PhD
thesis (PDF, 8.1 MB) (link resides outside IBM).
1989: Yann LeCun published a paper (PDF, 5.7 MB) (link resides outside IBM) illustrating how
the use of constraints in backpropagation and its integration into the neural network architecture
can be used to train algorithms. This research successfully leveraged a neural network to
recognize hand-written zip code digits provided by the U.S. Postal Service.
For decades now, IBM has been a pioneer in the development of AI technologies and neural
networks, highlighted by the development and evolution of IBM Watson. Watson is now a
trusted solution for enterprises looking to apply advanced natural language processing and deep
learning techniques to their systems using a proven tiered approach to AI adoption and
implementation.
DECISION TREES:
o Decision Tree is a Supervised learning technique that can be used for both
the features of a dataset, branches represent the decision rules and each leaf node
Node. Decision nodes are used to make any decision and have multiple branches,
whereas Leaf nodes are the output of those decisions and do not contain any further
branches.
o The decisions or the test are performed on the basis of features of the given dataset.
o It is called a decision tree because, similar to a tree, it starts with the root node, which
o In order to build a tree, we use the CART algorithm, which stands for Classification
o A decision tree simply asks a question, and based on the answer (Yes/No), it further split
There are various algorithms in Machine learning, so choosing the best algorithm for the given
dataset and problem is the main point to remember while creating a machine learning model.
Below are the two reasons for using the Decision tree:
o Decision Trees usually mimic human thinking ability while making a decision, so it is
easy to understand.
o The logic behind the decision tree can be easily understood because it shows a tree-like
structure.
In a decision tree, for predicting the class of the given dataset, the algorithm starts from the root
node of the tree. This algorithm compares the values of root attribute with the record (real
dataset) attribute and, based on the comparison, follows the branch and jumps to the next node.
For the next node, the algorithm again compares the attribute value with the other sub-nodes and
move further. It continues the process until it reaches the leaf node of the tree. The complete
process can be better understood using the below algorithm:
o Step-1: Begin the tree with the root node, says S, which contains the complete dataset.
o Step-2: Find the best attribute in the dataset using Attribute Selection Measure (ASM).
o Step-3: Divide the S into subsets that contains possible values for the best attributes.
o Step-4: Generate the decision tree node, which contains the best attribute.
o Step-5: Recursively make new decision trees using the subsets of the dataset created in
step -3. Continue this process until a stage is reached where you cannot further classify
Example: Suppose there is a candidate who has a job offer and wants to decide whether he
should accept the offer or Not. So, to solve this problem, the decision tree starts with the root
node (Salary attribute by ASM). The root node splits further into the next decision node (distance
from the office) and one leaf node based on the corresponding labels. The next decision node
further gets split into one decision node (Cab facility) and one leaf node. Finally, the decision
node splits into two leaf nodes (Accepted offers and Declined offer). Consider the below
diagram:
Attribute Selection Measures
While implementing a Decision tree, the main issue arises that how to select the best attribute for
the root node and for sub-nodes. So, to solve such problems there is a technique which is called
as Attribute selection measure or ASM. By this measurement, we can easily select the best
attribute for the nodes of the tree. There are two popular techniques for ASM, which are:
o Information Gain
o Gini Index
1. Information Gain:
o According to the value of information gain, we split the node and build the decision tree.
o A decision tree algorithm always tries to maximize the value of information gain, and a
node/attribute having the highest information gain is split first. It can be calculated using
Where,
2. Gini Index:
o Gini index is a measure of impurity or purity used while creating a decision tree in the
o An attribute with the low Gini index should be preferred as compared to the high Gini
index.
o It only creates binary splits, and the CART algorithm uses the Gini index to create binary
splits.
Pruning is a process of deleting the unnecessary nodes from a tree in order to get the optimal
decision tree.
A too-large tree increases the risk of overfitting, and a small tree may not capture all the
important features of the dataset. Therefore, a technique that decreases the size of the learning
tree without reducing accuracy is known as Pruning. There are mainly two types of
tree pruning technology used:
o It is simple to understand as it follows the same process which a human follow while
o It may have an overfitting issue, which can be resolved using the Random Forest
algorithm.
o For more class labels, the computational complexity of the decision tree may increase.
Now we will implement the Decision tree using Python. For this, we will use the dataset
"user_data.csv," which we have used in previous classification models. By using the same
dataset, we can compare the Decision tree classifier with other classification models such
as KNN SVM, LogisticRegression, etc.
Steps will also remain the same, which are given below:
Support Vector Machine or SVM is one of the most popular Supervised Learning algorithms,
which is used for Classification as well as Regression problems. However, primarily, it is used
for Classification problems in Machine Learning.
The goal of the SVM algorithm is to create the best line or decision boundary that can segregate
n-dimensional space into classes so that we can easily put the new data point in the correct
category in the future. This best decision boundary is called a hyperplane.
SVM chooses the extreme points/vectors that help in creating the hyperplane. These extreme
cases are called as support vectors, and hence algorithm is termed as Support Vector Machine.
Consider the below diagram in which there are two different categories that are classified using a
decision boundary or hyperplane:
Example: SVM can be understood with the example that we have used in the KNN classifier.
Suppose we see a strange cat that also has some features of dogs, so if we want a model that can
accurately identify whether it is a cat or dog, so such a model can be created by using the SVM
algorithm. We will first train our model with lots of images of cats and dogs so that it can learn
about different features of cats and dogs, and then we test it with this strange creature. So as
support vector creates a decision boundary between these two data (cat and dog) and choose
extreme cases (support vectors), it will see the extreme case of cat and dog. On the basis of the
support vectors, it will classify it as a cat. Consider the below diagram:
SVM algorithm can be used for Face detection, image classification, text categorization, etc.
Types of SVM
o Linear SVM: Linear SVM is used for linearly separable data, which means if a dataset
can be classified into two classes by using a single straight line, then such data is termed
as linearly separable data, and classifier is used called as Linear SVM classifier.
o Non-linear SVM: Non-Linear SVM is used for non-linearly separated data, which means
if a dataset cannot be classified by using a straight line, then such data is termed as non-
The dimensions of the hyperplane depend on the features present in the dataset, which means if
there are 2 features (as shown in image), then hyperplane will be a straight line. And if there are
3 features, then hyperplane will be a 2-dimension plane.
We always create a hyperplane that has a maximum margin, which means the maximum distance
between the data points.
Support Vectors:
The data points or vectors that are the closest to the hyperplane and which affect the position of
the hyperplane are termed as Support Vector. Since these vectors support the hyperplane, hence
called a Support vector.
Linear SVM:
The working of the SVM algorithm can be understood by using an example. Suppose we have a
dataset that has two tags (green and blue), and the dataset has two features x1 and x2. We want a
classifier that can classify the pair(x1, x2) of coordinates in either green or blue. Consider the
below image:
So as it is 2-d space so by just using a straight line, we can easily separate these two classes. But
there can be multiple lines that can separate these classes. Consider the below image:
Hence, the SVM algorithm helps to find the best line or decision boundary; this best boundary or
region is called as a hyperplane. SVM algorithm finds the closest point of the lines from both
the classes. These points are called support vectors. The distance between the vectors and the
hyperplane is called as margin. And the goal of SVM is to maximize this margin.
The hyperplane with maximum margin is called the optimal hyperplane.
Non-Linear SVM:
If data is linearly arranged, then we can separate it by using a straight line, but for non-linear
data, we cannot draw a single straight line. Consider the below image:
So to separate these data points, we need to add one more dimension. For linear data, we have
used two dimensions x and y, so for non-linear data, we will add a third dimension z. It can be
calculated as:
z=x2 +y2
By adding the third dimension, the sample space will become as below image:
So now, SVM will divide the datasets into classes in the following way. Consider the below
image:
Since we are in 3-d Space, hence it is looking like a plane parallel to the x-axis. If we convert it
in 2d space with z=1, then it will become as:
Probabilistic Models
The Naïve Bayes algorithm is comprised of two words Naïve and Bayes,
• Naïve: It is called Naïve because it assumes that the occurrence of a certain feature is
independent of the occurrence of other features.
• Bayes: It is called Bayes because it depends on the principle of Bayes' Theorem
Bayes' Theorem:
• Bayes' theorem is used to determine the probability of a hypothesis with prior knowledge.
It depends on the conditional probability.
• The formula for Bayes' theorem is given as:
• Where,
• P(A|B) is Posterior probability: Probability of hypothesis A on the observed event B.
• P(B|A) is Likelihood probability: Probability of the evidence given that the probability
of a hypothesis is true.
• P(A) is Prior Probability: Probability of hypothesis before observing the evidence.
• P(B) is Marginal Probability: Probability of Evidence.
• Gaussian: The Gaussian model assumes that features follow a normal distribution. This
means if predictors take continuous values instead of discrete, then the model assumes
that these values are sampled from the Gaussian distribution.
• Multinomial: The Multinomial Naïve Bayes classifier is used when the data is
multinomial distributed. It is primarily used for document classification problems, it
means a particular document belongs to which category such as Sports, Politics,
education, etc.
The classifier uses the frequency of words for the predictors.
• Bernoulli: The Bernoulli classifier works similar to the Multinomial classifier, but the
predictor variables are the independent Booleans variables. Such as if a particular word is
present or not in a document. This model is also famous for document classification
tasks.
• Naive Bayes assumes that all features are independent or unrelated, so it cannot learn the
relationship between features.
Unsupervised Learning
Unsupervised learning is different from the Supervised learning technique; as its name
suggests, there is no need for supervision.
It means, in unsupervised machine learning, the machine is trained using the unlabeled
dataset, and the machine predicts the output without any supervision.
The main aim of the unsupervised learning algorithm is to group or categories the
unsorted dataset according to the similarities, patterns, and differences.
Machines are instructed to find the hidden patterns from the input dataset.
Example: Suppose the unsupervised learning algorithm is given an input dataset
containing images of different types of cats and dogs. The algorithm is never trained
upon the given dataset, which means it does not have any idea about the features of the
dataset. The task of the unsupervised learning algorithm is to identify the image features
on their own. Unsupervised learning algorithm will perform this task by clustering the
image dataset into the groups according to similarities between images.
• Unsupervised learning is helpful for finding useful insights from the data.
• It is much similar as a human learns to think by their own experiences, which makes it
closer to the real AI.
• It works on unlabeled and uncategorized data which make this more important.
• In real-world, we do not always have input data with the corresponding output so to solve
such cases, we need unsupervised learning.
• Clustering: Clustering is a method of grouping the objects into clusters such that objects
with most similarities remains into a group and has less or no similarities with the objects
of another group. Cluster analysis finds the commonalities between the data objects and
categorizes them as per the presence and absence of those commonalities.
• Association: An association rule is an unsupervised learning method which is used for
finding the relationships between variables in the large database. It determines the set of
items that occurs together in the dataset. Association rule makes marketing strategy more
effective. Such as people who buy X item (suppose a bread) are also tend to purchase Y
(Butter/Jam) item. A typical example of Association rule is Market Basket Analysis.
Unsupervised Learning
K-means clustering Neural Networks
Featurization
• Featurization is the process to convert varied forms of data to numerical data which
can be used for basic ML algorithms. Data can be text data, images, videos, graphs,
various database tables, time-series, categorical features, etc.
Why Featurization?
• The machine learning model cannot work with row text data directly. In the end, machine
learning models work with numerical (categorical, real,…) features. So it is import to
change some type of data into numerical vector so that we can leverage the whole power
of linear algebra (making the decision boundary between data points)and statistics tools
with other types of data also.
• BoW is a simple and flexible technique to change the text data into numerical vectors. It
is based upon counting the occurrence of a word in the document(sentence, review).
Tfidf Vectorizer
Weighted Word2Vec
Tfidf Word2Vec
• TF-IDF is a statistical measure that we can apply to terms in a document and then use
that to form a vector whereas word2vec will produce a vector for a term and then more
work may need to be done to convert that set of vectors into a singular vector or other
UNIT- III
RANKING:
Ranking is a type of supervised machine learning (ML) that uses labeled datasets
to train its data and models to classify future data to predict outcomes. Quite
simply, the goal of a ranking model is to sort data in an optimal and relevant order.
Ranking was first largely deployed within search engines. People search for a
topic, while the ranking algorithm reorders search results based on the PageRank,
and the search engine is able to display the most relevant results to its customers.
Until recently, most ranking models, and ML as whole, were limited in their scope
of use, as most companies didn’t have enough data to power these algorithms.
Better methods for data collection and more intuitive ML tools have made it
possible for nearly anyone to deploy a successful ranking model within their
business.
As we’ll discuss later in this blog, ranking is incredibly versatile and dependent on
the data a company has. Even so, a common framework guides the construction of
all ranking models.
Ranking models are made up of 2 main factors: queries and documents. Queries
are any input value, such as a question on Google or an interaction on an e-
commerce site. Documents are the output value or results of the query. Given the
query, and the associated documents, a function, given a list of parameters to rank
on, will score the documents to be sorted in order of relevancy.
The machine learning algorithm learning to rank takes the scores from this model,
and uses them to predict future outcomes on a new and unseen list of documents.
Ranking ensures that the most relevant results appear first on a customer’s search,
maximizing the chances they will find something of interest, and minimizing the
chances of churn. With so many options for organic web search, the need to stay
competitive has never been greater. According to a Google study, 61% of users
said if they didn’t find what they were looking for right away, they would quickly
move on to another site. Depending on available data, companies can use ranking
within their web pages and apps to serve their customers the most relevant results
as soon as they enter.
The most successful companies are using ranking within their software to improve
the user experience. Ranking has allowed these companies to create customized
feeds for each user based on their past search and buying history. Ranking carries
many use cases across industries, nearly anyone with data can and should be using
ranking in some capacity to optimize their business. A few use cases are:
1. Search results
2. Targeted ads
3. Recommendations
Here are a few companies who have used ranking to maximize user engagement.
Amazon
With millions of listings or documents, for every product search or query,
Amazon needed to find a way to rank its products in order to maximize the
chance of purchase. Using a combination of individual preferences, gathered
from users' search and purchasing history and a product’s popularity,
Amazon created a ranking system that would display the most relevant
products at the top of their feed. Additionally, ranking was used in
Amazon’s recommendation system, which would use users' ranked
preferences in order to predict what products a user is most likely to
purchase in the future.
Netflix
Similar to Amazon, Netflix uses ranking to fuel their recommendation
system. The recommendation system predicts what content a user is most
likely to watch and displays the most relevant content at the top of the home
page. Netflix uses a few different features to rank and recommend content;
such as: watch history, search history, and general popularity. They also use
ranking to fuel their collaborative filtering.
TikTok
TikTok’s standout feature is the For You page which is built on a ranking
system. This feature has allowed TikTok to customize each home page to be
reflective of the preferences and interests of its user. TikTok uses similar
metrics to Netflix to rank its content: watch history, re-watch rate, and
engagement. Similar to Netflix, TikTok’s ranking system also aids in
collaborative filtering.
- Starbucks
Starbucks found great success with their mobile app, which is one of the most
downloaded apps on the App Store. The app allows Starbucks to create a custom
user experience for their customers even when they’re not within a physical coffee
shop. The app uses ranking to recommend the most relevant products to users.
Taking into account order history, new products and general popularity of other
products, Starbucks is able to keep customers' favorite orders at the top of the
recommended search while introducing them to new products that they are most
likely to enjoy.
Fastest way to build ranking model:
For the companies listed above, entire teams of data scientists and AI engineers
were built to create and maintain the ranking systems in place. The cost to build
these teams is impractical for most businesses. Recently, there have been great
tools emerging which allow for the easy building and deployment of ranking
models–this with little to no programming experience.
Mage allows for the building and deployment of a ranking model with no ML
programming knowledge. To use Mage, a database containing a list of queries and
documents is first uploaded. Queries could contain a list of clothes or menu items,
their documents could be the number of engagement (clicks and purchases) each
received. The greater the quality and quantity of data uploaded, the better that
Mage is able to produce ranking predictions.
Once the data is uploaded, users will be given the option to transform their datasets
by removing and adding columns, applying transformer actions: split and filter
data, group values, aggregate data, and identifying what columns they would like
to rank. Mage will then produce a ranking model which can be deployed into your
data warehouses, downloaded to a CSV file, or saved directly to a Mage dataset.
PIPELINES:
What is a Machine Learning Pipeline?
Pre-processing
Data preprocessing is a Data Mining technique that involves transferring raw data
into an understandable format. Real-world data is usually incomplete, inconsistent,
and lacks certain behaviors or trends, most likely to contain many inaccuracies.
The process of getting usable data for a Machine Learning algorithm follows steps
such as Feature Extraction and Scaling, Feature Selection, Dimensionality
reduction, and sampling. The product of Data Pre-processing is the final dataset
used for training the model and testing purposes.
Learning
Evaluation
To Evaluate the Machine Learning model's performance, fit a model to the training
data, and predict the labels of the test set. Further, count the number of wrong
predictions on the test dataset to compute the model’s prediction accuracy.
Prediction
The model's performance to determine the outcomes of the test data set was not
used for any training or cross-validation activities.
What are the benefits?
Why it is Matters?
As machines begin to learn through algorithms, it will help companies interpret
uncovered patterns to make better decisions.\
Real-Time Predictions
ML algorithms are super fast. As a consequence that Large Data Processing takes
place rapidly. This, in turn, helps in making Real-Time predictions very beneficial
for businesses.
Transforming Industries
There are various metrics which we can use to evaluate the performance of ML
algorithms, classification as well as regression algorithms. We must carefully
choose the metrics for evaluating ML performance because −
How the performance of ML algorithms is measured and compared will be
dependent entirely on the metric you choose.
How you weight the importance of various characteristics in the result will
be influenced completely by the metric you choose.
Performance Metrics for Classification Problems
We have discussed classification and its algorithms in the previous chapters. Here,
we are going to discuss various performance metrics that can be used to evaluate
predictions for classification problems.
Confusion Matrix
It is the easiest way to measure the performance of a classification problem where
the output can be of two or more type of classes. A confusion matrix is nothing but
a table with two dimensions viz. “Actual” and “Predicted” and furthermore, both
the dimensions have “True Positives (TP)”, “True Negatives (TN)”, “False
Positives (FP)”, “False Negatives (FN)” as shown below −
Explanation of the terms associated with confusion matrix are as follows −
True Positives (TP) − It is the case when both actual class & predicted class
of data point is 1.
True Negatives (TN) − It is the case when both actual class & predicted
class of data point is 0.
False Positives (FP) − It is the case when actual class of data point is 0 &
predicted class of data point is 1.
False Negatives (FN) − It is the case when actual class of data point is 1 &
predicted class of data point is 0.
We can use confusion_matrix function of [Link] to compute Confusion
Matrix of our classification model.
Classification Accuracy
It is most common performance metric for classification algorithms. It may be
defined as the number of correct predictions made as a ratio of all predictions
made. We can easily calculate it by confusion matrix with the help of following
formula −
In the above equation, numerator is MSE and the denominator is the variance in 𝑌
values.
We can use r2_score function of [Link] to compute R squared value.
Example
The following is a simple recipe in Python which will give us an insight about how
we can use the above explained performance metrics on regression model −
from [Link] import r2_score
from [Link] import mean_absolute_error
from [Link] import mean_squared_error
X_actual = [5, -1, 2, 10]
Y_predic = [3.5, -0.9, 2, 9.9]
print ('R Squared =',r2_score(X_actual, Y_predic))
print ('MAE =',mean_absolute_error(X_actual, Y_predic))
print ('MSE =',mean_squared_error(X_actual, Y_predic))
Output
R Squared = 0.9656060606060606
MAE = 0.42499999999999993
MSE = 0.5674999999999999
AZURE MACHINE LEARNING:
Azure Machine Learning is a cloud service for accelerating and managing the
machine learning project lifecycle. Machine learning professionals, data scientists,
and engineers can use it in their day-to-day workflows: Train and deploy models,
and manage MLOps.
You can create a model in Azure Machine Learning or use a model built from an
open-source platform, such as Pytorch, TensorFlow, or scikit-learn. MLOps tools
help you monitor, retrain, and redeploy models.
Azure Machine Learning is for individuals and teams implementing MLOps within
their organization to bring machine learning models into production in a secure and
auditable production environment.
Data scientists and ML engineers will find tools to accelerate and automate their
day-to-day workflows. Application developers will find tools for integrating
models into applications or services. Platform developers will find a robust set of
tools, backed by durable Azure Resource Manager APIs, for building advanced
ML tooling.
Enterprises working in the Microsoft Azure cloud will find familiar security and
role-based access control (RBAC) for infrastructure. You can set up a project to
deny access to protected data and select operations.
Machine learning projects often require a team with varied skillsets to build and
maintain. Azure Machine Learning has tools that help enable collaboration, such
as:
Studio UI
The Azure Machine Learning studio is a graphical user interface for a project
workspace. In the studio, you can:
Plus, the designer has a drag-and-drop interface where you can train and deploy
models.
If you're a ML Studio (classic) user, learn about Studio (classic) deprecation and
the difference between it and Azure Machine Learning studio.
Azure Machine Learning integrates with the Azure cloud platform to add security
to ML projects.
Other integrations with Azure services support a machine learning project from
end-to-end. They include:
Project lifecycle
While the project lifecycle can vary by project, it will often look like this:
A workspace organizes a project and allows for collaboration for many users all
working toward a common objective. Users in a workspace can easily share the
results of their runs from experimentation in the studio user interface or use
versioned assets for jobs like environments and storage references.
Models can be deployed to the managed inferencing solution, for both real-time
and batch deployments, abstracting away the infrastructure management typically
required for deploying models.
In Azure Machine Learning, you can run your training script in the cloud or build a
model from scratch. Customers often bring models they've built and trained in
open-source frameworks, so they can operationalize them in the cloud.
Data scientists can use models in Azure Machine Learning that they've created in
common Python frameworks, such as:
PyTorch
TensorFlow
scikit-learn
XGBoost
LightGBM
R
.NET
Hyperparameter optimization
Efficiency of training for deep learning and sometimes classical machine learning
training jobs can be drastically improved via multinode distributed training. Azure
Machine Learning compute clusters offer the latest GPU options.
The MPI distribution can be used for Horovod or custom multinode logic.
Additionally, Apache Spark is supported via Azure Synapse Analytics Spark
clusters (preview).
3. Matplot
Matplotlib is as old as the dinosaurs, but it's not extinct or obsolete when it comes
to data visualisation. In fact, it's one of the most advanced data visualisation
libraries for Python, and the ML community loves it. Here are some of the great
features of the Matplotlib library:
Provides a comprehensive list of plots suitable for any use case
The interactive plots and charts allow compelling data storytelling
Plots and charts are highly customisable and exportable to different file formats
Provides embeddable visualisations with various GUI applications
A wide array of Python libraries and frameworks extend Matplotlib.
Matplotlib is another one of the gems offered by the open-source ecosystem. Here
is a link to the Matplotlib cheat sheets to serve as a quick start guide.
4. OpenCV
5. Scikit Learn
Every data scientist and ML enthusiast has used scikit-learn at some point in their
AI journey. It is a comprehensive machine learning framework. Sometimes people
tend to overlook it due to the availability of more advanced Python libraries and
frameworks. Still, it is a powerful library and does an excellent job solving some
complex Machine Learning tasks. Here are a few important features scikit-learn
includes:
6. Keras
Released in 2015, Keras is an advanced open-source Python deep learning API and
framework built on top of Tensorflow-another powerful ML platform. Although
similar to Tensorflow in many aspects, it is designed with a human-centric
approach to make ML and DL easy and accessible for everyone. Key elements of
Keras include:
Everything that TensorFlow offers but simpler and easier to understand
Running different DL iterations quickly with full deployment capabilities
Support for large GPU clusters and TPUs, enabling industrial-scale Python
machine learning
From computer vision to natural language processing, and generative deep learning
to reinforcement learning, Keras offers wide-ranging applications for structured,
audio, graph, and timeseries data. Here’s a brief Keras cheat sheet to get you up to
speed.
7. Tensor Flow
Developed by Google and open-sourced later, TensorFlow powers some of the
biggest state-of-the-art AI models worldwide. It's an end-to-end Machine Learning
and Deep Learning library to solve real-world challenges. Some key features
included in TensorFlow are listed below:
Complete control over building a robust neural network and machine learning
model
Deploy models on web, cloud, mobile, or edge devices using [Link],
TensorFlow Lite, and TFX
Supports numerous libraries and extensions for solving complex problems
Supports various tools for integrating Responsible AI into ML solutions
TensorFlow Deep Learning framework is used by some of the top
companies worldwide. For example, Paypal applies TensorFlow to develop deep
transfer learning and generative modelling methods to recognise complex fraud
patterns. Spotify uses TFX to improve user recommendations. And, Airbnb uses
TensorFlow to detect objects and classify images to enhance the guest experience.
Hmm, the more you know!
8. PyTorch
Natural Language Processing (NLP) has recently seen rapid growth with the
release of massive language models like BERT and GPT-3, making waves
worldwide. One of the fundamental Python libraries for performing NLP tasks is
NLTK. Developers interested in NLP should gain hands-on experience with this
Python library. Some key features include:
10. SpaCy
And last, but certainly not lesay we have SpaCY. Meant for solving advanced NLP
problems, SpaCy is an industrial-scale open-source Python library for NLP. SpaCy
is written in Cython with memory management optimisation to ensure state-of-the-
art speed. Some key aspects of this Python library include:
60+ trained NLP pipelines supporting 19 languages
Pre-trained word embeddings
Production-ready pipelines
Supports custom models that written in TensorFlow and PyTorch
SpaCy Universe offers a wide variety of Python packages, plugins, and extensions
for NLP
SpaCy API supports many NLP tasks like lemmatisation, entity recognition,
tagging, sentence recognition, tokenisation, and more.
Open-source Python libraries and frameworks have greatly democratised AI
research and development. Every day AI practitioners are coming up with bigger
and better models for solving real-world problems. AI is not just a buzzword
anymore, it has penetrated our lives much more than we can imagine, and Python
programming lies at its core.
Python programming language has significantly matured over the last two decades
and we can't wait to see where it goes next. Learning these Python libraries and
frameworks will definitely benefit all current and future Python Developers and
Data Scientists.
SAGEMAKER:
Machine learning has a range of uses and benefits. Among them are advanced
analytics for customer data and back-end security threat detection.
Many companies don't have the budget to bring in specialists and maintain
resources dedicated to AI development. AWS SageMaker uses integrated tools to
automate labor-intensive manual processes and reduce human error and hardware
costs. ML modeling components are packaged in an AWS SageMaker tool set.
Software capabilities are abstracted in intuitive SageMaker templates. They
provide a framework to build, host, train and deploy ML models at scale in the
Amazon public cloud.
The notebooks include drivers, packages and libraries for common deep
learning platforms and frameworks. Developers can launch a prebuilt notebook,
which AWS supplies for a variety of applications and use cases. They can then
customize it according to the data set and schema that needs to be trained.
Developers also can use custom-built algorithms written in one of the supported
ML frameworks or any code that has been packaged as a Docker container image.
SageMaker can pull data from Amazon Simple Storage Service (S3), and there is
no practical limit to the size of the data set.
To get started, a developer logs into the SageMaker console and launches a
notebook instance. SageMaker provides a variety of built-in training algorithms,
such as linear regression and image classification, or the developer can import
custom algorithms.
Developers doing model training specify the location of the data in an Amazon S3
bucket and the preferred instance type. They then initiate the training process.
SageMaker Model Monitor provides continuous automatic model tuning to find the
set of parameters, or hyperparameters, to best optimizes the algorithm. During this
step, data is transformed to enable feature engineering.
There is no problem predictive analytics can solve that machine learning cannot.
But predictive analytics always has an intended audience, whereas machine
learning does not. Let’s explore.
Use cases
predictive analytics is usually conducted on numerical data. Predictive analytics is
used to figure out:
Through the use of machine learning, predictive analytics can expand how it
conducts its sentiment analysis to see how happy its customers and employees are.
“Insight is the value obtained through the use of analytics. The insights gained
through analytics are incredibly powerful, and can be used to grow your business
while identifying areas of opportunity.” – Localytics Blog
One of the best ways to understand and communicate meaningful insights from
data is to use tools that help visualize a model’s outcomes and give different ways
to explore and understand your data. This translates to real business value in the
form of increased ROI on advertising efforts, more accurate loan default
predictions, and much more. The clarity of vision from data insights allows users
to make better decisions based on increased model interpretability, allowing
analysts and other users to explain model outcomes to key stakeholders.
Insights allow users of all skill levels to understand what the model is doing
“behind the scenes,” which is especially important when it comes to highly
regulated industries like banking and healthcare. If you don’t understand why your
model is drawing the conclusions it does (i.e., you don’t have any insight into the
inner workings), the model’s practical usefulness is limited.
Data visualization tools help users understand and explain insights from machine
learning model outcomes. Whether it is through simple graphical representations
like word clouds or more complicated and flexible data visualization tools
like Tableau dashboards, these tools make it easier to understand and
communicate the value uncovered by the model and drive better business decision-
making.
The example below shows words from just such a dataset which relate to patient
readmission rates. The red words are correlated with high-risk patient notes and the
blue words are correlated with low-risk patient notes. The size of the word
represents how frequently it occurs in the dataset.
DataRobot also includes tools that measure and rank the impact of individual
features (see Feature Impact) and provide details of how the model works and the
processes it runs on input data, as well as Prediction Explanations that give the top
reasons for the model’s outcome for each individual record.
An actionable insight is a process that is derived from raw data analysis. For
example, business leaders could track a customer's behavior on a platform that can
indicate their sentiment regarding a product. These data points are fed into an
analytics platform, from which users can derive conclusions.
Business leaders might notice that customers aren't as keen on a product feature
that was popular in the past and that they're asking for a new feature or
enhancement. Social media listening strategies also help to gather raw data and
turn them into actionable insights.
Every industry could use actionable insights. "Actionable insights arising from
analytics and AI are no longer a luxury, but a necessity for achieving
competitiveness," said Eitan Sofer, head of developer platform at Sisense, an
analytics provider.
While the human agent still has discretion over the process, the algorithm makes
their job easier and more efficient.
While ML algorithms offer great insights, they're fully dependent on the data
they're fed during their learning and maturity stages.
"Analytics must cope with both structured and unstructured data to achieve optimal
results," Sofer said.
One of the main challenges of generating actionable insights is the need to deal
with both structured and unstructured data.
Unstructured data is more challenging. Examples of this data include raw text,
social media comments, log files and call transcripts. Unstructured data needs to be
stored in a NoSQL database or a data lake, is free-form and doesn't adhere to
schemas.
Unstructured data, by some estimates, comprises 80% of all available data, and
using a powerful business intelligence (BI) platform can simplify turning this data
into actionable insights. A platform that connects to multiple sources will make it
easier to import disparate data and create efficient workflows.
Actionable insights aren't the only kind of insight an analytics platform can
provide. For example, a company may receive confirmation of a business strategy
that requires no further action. These insights are just as valuable as actionable
ones.
Every data collection method has bias within it. For example, log files could
indicate that customers spend a lot of time on one particular function within the
platform. The company may conclude that this is the most important feature and
work to enhance it. However, the customers could be spending time there because
the feature is inefficient or unintuitive.
Always pay attention to the context in which the data was collected. "Tunnel vision
is a problem across a variety of fields, from sports to industry," said George
Walker, managing director at Novotek U.K. and Ireland. "It is easy to fixate on a
single goal and forget to take a step back for a wider view of the situation. Yet
taking this step back can provide invaluable insight and understanding of the
reality of a situation."
However, the future can change only if insights are used to drive decision-making.
Many companies derive insights but neglect to act on them. To take full advantage
of a BI analytics platform, an organization must create an optimization plan. A Six
Sigma action plan can help integrate new ideas and findings into workflows, define
the problem and measure the effectiveness of the current process.
Use the BI platform to analyze the root causes of these issues and make
improvements to processes. Once implemented, measure and control the new
process for effectiveness.
Creating actionable insights is a process like any other, and it's perhaps the most
important factor for a business' overall success.
DATA EXPLORIATION
Data exploration definition: Data exploration refers to the initial step in data analysis
in which data analysts use data visualization and statistical techniques to describe
dataset characterizations, such as size, quantity, and accuracy, in order to better
understand the nature of the data.
Data exploration techniques include both manual analysis and automated data
exploration software solutions that visually explore and identify relationships between
different data variables, the structure of the dataset, the presence of outliers, and the
distribution of data values in order to reveal patterns and points of interest, enabling
data analysts to gain greater insight into the raw data.
Data is often gathered in large, unstructured volumes from various sources and data
analysts must first understand and develop a comprehensive view of the data before
extracting relevant data for further analysis, such as univariate, bivariate, multivariate,
and principal components analysis.
Manual data exploration methods entail either writing scripts to analyze raw data or
manually filtering data into spreadsheets. Automated data exploration tools, such as
data visualization software, help data scientists easily monitor data sources and
perform big data exploration on otherwise overwhelmingly large datasets. Graphical
displays of data, such as bar charts and scatter plots, are valuable tools in visual data
exploration.
A popular tool for manual data exploration is Microsoft Excel spreadsheets, which
can be used to create basic charts for data exploration, to view raw data, and to
identify the correlation between variables. To identify the correlation between two
continuous variables in Excel, use the function CORREL() to return the correlation.
To identify the correlation between two categorical variables in Excel, the two-way
table method, the stacked column chart method, and the chi-square test are effective.
Humans process visual data better than numerical data, therefore it is extremely
challenging for data scientists and data analysts to assign meaning to thousands of
rows and columns of data points and communicate that meaning without any visual
components.
Data visualization in data exploration leverages familiar visual cues such as shapes,
dimensions, colors, lines, points, and angles so that data analysts can effectively
visualize and define the metadata, and then perform data cleansing. Performing the
initial step of data exploration enables data analysts to better understand and visually
identify anomalies and relationships that might otherwise go undetected.
In this chapter we discuss the ways in which concepts from information theory can
be used to build prediction models. We start by discussing decision trees, the
fundamental structure used in information-based machine learning, before
presenting the fundamental measures of information content that are used: entropy
and information gain. We then present the ID3 algorithm, the standard algorithm
used to induce a decision tree from a dataset. The extensions and variations to this
standard approach that we present describe how different data types can be
handled, how overfitting can be avoided using decision tree pruning, and how
multiple prediction models can be combined in ensembles to improve prediction
accuracy.
DECISION TREES:
o Decision Tree is a Supervised learning technique that can be used for both
classification and Regression problems, but mostly it is preferred for solving
Classification problems. It is a tree-structured classifier, where internal
nodes represent the features of a dataset, branches represent the
decision rules and each leaf node represents the outcome.
o In a Decision tree, there are two nodes, which are the Decision
Node and Leaf Node. Decision nodes are used to make any decision and
have multiple branches, whereas Leaf nodes are the output of those
decisions and do not contain any further branches.
o The decisions or the test are performed on the basis of features of the given
dataset.
o It is a graphical representation for getting all the possible solutions to a
problem/decision based on given conditions.
o It is called a decision tree because, similar to a tree, it starts with the root
node, which expands on further branches and constructs a tree-like structure.
o In order to build a tree, we use the CART algorithm, which stands
for Classification and Regression Tree algorithm.
o A decision tree simply asks a question, and based on the answer (Yes/No), it
further split the tree into subtrees.
o Below diagram explains the general structure of a decision tree:
Why use Decision Trees?
There are various algorithms in Machine learning, so choosing the best algorithm
for the given dataset and problem is the main point to remember while creating a
machine learning model. Below are the two reasons for using the Decision tree:
In a decision tree, for predicting the class of the given dataset, the algorithm starts
from the root node of the tree. This algorithm compares the values of root attribute
with the record (real dataset) attribute and, based on the comparison, follows the
branch and jumps to the next node.
For the next node, the algorithm again compares the attribute value with the other
sub-nodes and move further. It continues the process until it reaches the leaf node
of the tree. The complete process can be better understood using the below
algorithm:
29.2K
Machine Learning - Data Description - Measures of Central Tendency: Mean,
Median and Mode
o Step-1: Begin the tree with the root node, says S, which contains the
complete dataset.
o Step-2: Find the best attribute in the dataset using Attribute Selection
Measure (ASM).
o Step-3: Divide the S into subsets that contains possible values for the best
attributes.
o Step-4: Generate the decision tree node, which contains the best attribute.
o Step-5: Recursively make new decision trees using the subsets of the dataset
created in step -3. Continue this process until a stage is reached where you
cannot further classify the nodes and called the final node as a leaf node.
Example: Suppose there is a candidate who has a job offer and wants to decide
whether he should accept the offer or Not. So, to solve this problem, the decision
tree starts with the root node (Salary attribute by ASM). The root node splits
further into the next decision node (distance from the office) and one leaf node
based on the corresponding labels. The next decision node further gets split into
one decision node (Cab facility) and one leaf node. Finally, the decision node splits
into two leaf nodes (Accepted offers and Declined offer). Consider the below
diagram:
Attribute Selection Measures
While implementing a Decision tree, the main issue arises that how to select the
best attribute for the root node and for sub-nodes. So, to solve such problems there
is a technique which is called as Attribute selection measure or ASM. By this
measurement, we can easily select the best attribute for the nodes of the tree. There
are two popular techniques for ASM, which are:
o Information Gain
o Gini Index
1. Information Gain:
Where,
2. Gini Index:
Pruning is a process of deleting the unnecessary nodes from a tree in order to get
the optimal decision tree.
A too-large tree increases the risk of overfitting, and a small tree may not capture
all the important features of the dataset. Therefore, a technique that decreases the
size of the learning tree without reducing accuracy is known as Pruning. There are
mainly two types of tree pruning technology used:
o It may have an overfitting issue, which can be resolved using the Random
Forest algorithm.
o For more class labels, the computational complexity of the decision tree may
increase.
Python Implementation of Decision Tree
Now we will implement the Decision tree using Python. For this, we will use the
dataset "user_data.csv," which we have used in previous classification models. By
using the same dataset, we can compare the Decision tree classifier with other
classification models such as KNN SVM, LogisticRegression, etc.
Steps will also remain the same, which are given below:
Similarity-based approaches to machine learning come from the idea that the best
way to make a predictions is to simply look at what has worked well in the past
and predict the same thing again. The fundamental concepts required to build a
system based on this idea are feature spaces and measures of similarity, and
these are covered in the fundamentals section of this chapter. These concepts allow
us to understand the standard approach to building similarity-based models: the
nearest neighbor algorithm. After covering the standard algorithm, we then look
at extensions and variations that allow us to handle noisy data (the k nearest
neighbor, or k-NN, algorithm), to make predictions more efficiently (k-d trees), to
predict continuous targets, and to handle different kinds of descriptive features
with varying measures of similarity. We also take the opportunity to introduce the
use of data normalization and feature selection in the context of similarity-based
learning. These techniques are generally applicable to all machine learning
algorithms but are especially important when similarity-based approaches are used.
KNN Algorithm
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:
Suppose we have a new data point and we need to put it in the required category.
Consider the below image:
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:
Below are some points to remember while selecting the value of K in the K-NN
algorithm:
o There is no particular way to determine the best value for "K", so we need to
try some values to find the best out of them. The most preferred value for K
is 5.
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.
The Naïve Bayes algorithm is comprised of two words Naïve and Bayes,
Bayes' Theorem:
• Naïve Bayes is one of the fast and easy ML algorithms to predict a class of
datasets.
• It can be used for Binary as well as Multi-class Classifications.
• It is the most popular choice for text classification problems.
Support Vector Machine or SVM is one of the most popular Supervised Learning
algorithms, which is used for Classification as well as Regression problems.
However, primarily, it is used for Classification problems in Machine Learning.
The goal of the SVM algorithm is to create the best line or decision boundary that
can segregate n-dimensional space into classes so that we can easily put the new
data point in the correct category in the future. This best decision boundary is
called a hyperplane.
SVM chooses the extreme points/vectors that help in creating the hyperplane.
These extreme cases are called as support vectors, and hence algorithm is termed
as Support Vector Machine. Consider the below diagram in which there are two
different categories that are classified using a decision boundary or hyperplane:
Example: SVM can be understood with the example that we have used in the
KNN classifier. Suppose we see a strange cat that also has some features of dogs,
so if we want a model that can accurately identify whether it is a cat or dog, so
such a model can be created by using the SVM algorithm. We will first train our
model with lots of images of cats and dogs so that it can learn about different
features of cats and dogs, and then we test it with this strange creature. So as
support vector creates a decision boundary between these two data (cat and dog)
and choose extreme cases (support vectors), it will see the extreme case of cat and
dog. On the basis of the support vectors, it will classify it as a cat. Consider the
below diagram:
SVM algorithm can be used for Face detection, image classification, text
categorization, etc.
Types of SVM
if a dataset can be classified into two classes by using a single straight line,
then such data is termed as linearly separable data, and classifier is used
such data is termed as non-linear data and classifier used is called as Non-
The dimensions of the hyperplane depend on the features present in the dataset,
which means if there are 2 features (as shown in image), then hyperplane will be a
straight line. And if there are 3 features, then hyperplane will be a 2-dimension
plane.
We always create a hyperplane that has a maximum margin, which means the
maximum distance between the data points.
Support Vectors:
The data points or vectors that are the closest to the hyperplane and which affect
the position of the hyperplane are termed as Support Vector. Since these vectors
support the hyperplane, hence called a Support vector.
Linear SVM:
The working of the SVM algorithm can be understood by using an example.
Suppose we have a dataset that has two tags (green and blue), and the dataset has
two features x1 and x2. We want a classifier that can classify the pair(x1, x2) of
coordinates in either green or blue. Consider the below image:
So as it is 2-d space so by just using a straight line, we can easily separate these
two classes. But there can be multiple lines that can separate these classes.
Consider the below image:
Hence, the SVM algorithm helps to find the best line or decision boundary; this
best boundary or region is called as a hyperplane. SVM algorithm finds the
closest point of the lines from both the classes. These points are called support
vectors. The distance between the vectors and the hyperplane is called as margin.
And the goal of SVM is to maximize this margin. The hyperplane with maximum
margin is called the optimal hyperplane.
Non-Linear SVM:
If data is linearly arranged, then we can separate it by using a straight line, but for
non-linear data, we cannot draw a single straight line. Consider the below image:
So to separate these data points, we need to add one more dimension. For linear
data, we have used two dimensions x and y, so for non-linear data, we will add a
third dimension z. It can be calculated as:
z=x2 +y2
By adding the third dimension, the sample space will become as below image:
So now, SVM will divide the datasets into classes in the following way. Consider
the below image:
Since we are in 3-d Space, hence it is looking like a plane parallel to the x-axis. If
we convert it in 2d space with z=1, then it will become as:
EVALUATION:
I'll also note that it's very important to shuffle the data before making these splits
so that each split has an accurate representation of the dataset.
Metrics
Classification metrics
When performing classification predictions, there's four types of outcomes that could
occur.
True positives are when you predict an observation belongs to a class and it
actually does belong to that class.
True negatives are when you predict an observation does not belong to a class and
it actually does not belong to that class.
False positives occur when you predict an observation belongs to a class when in
reality it does not.
False negatives occur when you predict an observation does not belong to a class
when in fact it does.
These four outcomes are often plotted on a confusion matrix. The following
confusion matrix is an example for the case of binary classification. You would
generate this matrix after making predictions on your test data and then identifying
each prediction as one of the four possible outcomes described above.
You can also extend this confusion matrix to plot multi-class classification
predictions. The following is an example confusion matrix for classifying
observations from the Iris flower dataset.
The three main metrics used to evaluate a classification model are accuracy,
precision, and recall.
Accuracy is defined as the percentage of correct predictions for the test data. It can
be calculated easily by dividing the number of correct predictions by the number of
total predictions.
accuracy=correctpredictionsallpredictionsaccuracy=correctpredictionsallprediction
s
Precision is defined as the fraction of relevant examples (true positives) among all
of the examples which were predicted to belong in a certain class.
precision=truepositivestruepositives+falsepositivesprecision=truepositivestrueposit
ives+falsepositives
Recall is defined as the fraction of examples which were predicted to belong to a
class with respect to all of the examples that truly belong in the class.
recall=truepositivestruepositives+falsenegativesrecall=truepositivestruepositives+f
alsenegatives
The following graphic does a phenomenal job visualizing the difference between
precision and recall.
Precision and recall are useful in cases where classes aren't evenly distributed. The
common example is for developing a classification algorithm that predicts whether
or not someone has a disease. If only a small percentage of the population (let's say
1%) has this disease, we could build a classifier that always predicts that the person
does not have the disease, we would have built a model which is 99% accurate and
0% useful.
However, if we measured the recall of this useless predictor, it would be clear that
there was something wrong with our model. In this example, recall ensures that
we're not overlooking the people who have the disease, while precision ensures
that we're not misclassifying too many people as having the disease when they
don't. Obviously, you wouldn't want a model that incorrectly predicts a person has
cancer (the person would end up in a painful and expensive treatment process for a
disease they didn't have) but you also don't want to incorrectly predict a person
does not have cancer when in fact they do. Thus, it's important to evaluate both the
precision and recall of a model.
Ultimately, it's nice to have one number to evaluate a machine learning model just
as you get a single grade on a test in school. Thus, it makes sense to combine the
precision and recall metrics; the common approach for combining these metrics is
known as the f-score.
Regression metrics
Evaluation metrics for regression models are quite different than the above metrics
we discussed for classification models because we are now predicting in a
continuous range instead of a discrete number of classes. If your regression model
predicts the price of a house to be $400K and it sells for $405K, that's a pretty
good prediction. However, in the classification examples we were only concerned
with whether or not a prediction was correct or incorrect, there was no ability to
say a prediction was "pretty good". Thus, we have a different set of evaluation
metrics for regression models.
Explained variance compares the variance within the expected outcomes, and
compares that to the variance in the error of our model. This metric essentially
represents the amount of variation in the original dataset that our model is able to
explain.
Mean squared error is simply defined as the average of squared differences
between the predicted output and the true output. Squared error is commonly used
because it is agnostic to whether the prediction was too high or too low, it just
reports that the prediction was incorrect.
The R2 coefficient represents the proportion of variance in the outcome that our
model is capable of predicting based on its features.
Bias vs Variance
The ultimate goal of any machine learning model is to learn from examples and
generalize some degree of knowledge regarding the task we're training it to
perform. Some machine learning models provide the framework for generalization
by suggesting the underlying structure of that knowledge. For example, a linear
regression model imposes a framework to learn linear relationships between the
information we feed it. However, sometimes we provide a model with too much
pre-built structure that we limit the model's ability to learn from the examples -
such as the case where we train a linear model on a exponential dataset. In this
case, our model is biased by the pre-imposed structure and relationships.
Models with high bias pay little attention to the data presented; this is also known
as underfitting.
It's also possible to bias a model by trying to teach it to perform a task without
presenting all of the necessary information. If you know the constraints of the
model are not biasing the model's performance yet you're still observed signs of
underfitting, it's likely that you are not using enough features to train the model.
On the other extreme, sometimes when we train our model it learns too much from
the training data. That is, our model captures the noise in the data in addition to the
signal. This can cause wild fluctuations in the model that does not represent the
true trend; in this case, we say that the model has high variance. In this case, our
model does not generalize well because it pays too much attention to the training
data without consideration for generalizing to new data. In other words,
we've overfit the model to the training data.
In summary, a model with high bias is limited from learning the true trend and
underfits the data. A model with high variance learns too much from the training
data and overfits the data. The best model sits somewhere in the middle of the two
extremes.
Next, I'll discuss two common tools that are used to diagnosed whether a model is
susceptible to high bias or variance.
Validation curves
As we discussed in the previous section, the goal with any machine learning model
is generalization. Validation curves allow us to find the sweet spot between
underfitting and overfitting a model to build a model that generalizes well.
A typical validation curve is a plot of the model's error as a function of some
model hyperparameter which controls the model's tendency to overfit or underfit
the data. The parameter you choose depends on the specific model you're
evaluating; for example, you might choose to plot the degree of polynomial
features (typically, this means you have polynomial features up to this degree) for
a linear regression model. Generally, the chosen parameter will have some degree
of control over the model's complexity. On this curve, we plot both the training
error and the validation error of the model. Using both of these errors combined,
we can diagnose whether a model is suffering from high bias or high variance.
In the region where both the training error and validation error are high, the model
is subject to high bias. Here, it was not able to learn from the data and it
performing poorly.
In the region where the training error and validation error diverge, with the training
error staying low and validation error increasing, we're beginning to see the effects
of high variance. The training error is low because we're overfitting the data and
learning too much from the training examples, while the validation error remains
high because our model isn't able to generalize from the training data to new data.
Learning curves
The second tool we'll discuss for diagnosing bias and variance in a model is
learning curves. Here, we'll plot the error of a model as a function of the number of
training examples. Similar to validation curves, we'll plot the error for both the
training data and validation data.
If our model has high bias, we'll observe fairly quick convergence to a high error
for the validation and training datasets. If the model suffers from high bias, training
on more data will do very little to improve the model. This is because models
which underfit the data pay little attention to the data, so feeding in more data will
be useless. A better approach to improving models which suffer from high bias is
to consider adding additional features to the dataset so that the model can be more
equipped to learn the proper relationships.
If our model has high variance, we'll see a gap between the training and validation
error. This is because the model is performing well for the training data, since it
has been overfit to that subset, and performs poorly for the validation data since it
was not able to generalize the proper relationships. In this case, feeding more data
during training can help improve the model's performance.
IMAGE RECOGNITION:
When we see an object or an image, we, as human people, are able to know
immediately and precisely what it is. People class everything they see on different
sorts of categories based on attributes we identify on the set of objects. That way,
even though we don’t know exactly what an object is, we are usually able to
compare it to different categories of objects we have already seen in the past and
classify it based on its attributes. Let’s take the example of an animal that is
unknown to us. Even if we cannot clearly identify what animal it is, we are still
able to identify it as an animal.
People rarely think about what they are observing and how they can identify
objects, it completely happens subconsciously. People aren’t focused on
everything that surrounds them all the time. Our brain has been trained to identify
objects quite easily, based on our previous experiences, that is to say, objects we
have already encountered in the past. We do have an extraordinary power of
deduction: when we see something that resembles an object we have already seen
before, we are able to deduce that it belongs to a certain category of items. We
don’t necessarily need to look at every part of an image to identify the objects in it.
As soon as you see a part of the item that you recognized, you know what it is. We
usually use colors and contrasts to identify items.
For humans, most image recognition works subconsciously. But it is a lot more
complicated when it comes to image recognition with machines.
How does image recognition work with machines?
For a machine, an image is only composed of data, an array of pixel values. Each
pixel contains information about red, green, and blue color values (from 0 to 255
for each of them). For black and white images, the pixel will have information
about darkness and whiteness values (from 0 to 255 for both of them).
Machines don’t have a look at the whole image; they are only interested in pixel
values and patterns in these values. They simply take pixel patterns of an item and
compare them with other patterns. If two patterns are close enough, the machine
will associate them and recognize the second pattern as something it has already
encountered in the past. In that sense, what is happening is the machine will look
for groups of similar pixel values across images and will try to place them in
specific image categories.
It is very rare that a program recognizes an image at 100%. Pixel patterns are very
rarely 100% the same when comparing them. Solving these problems and finding
improvements is the job of IT researchers, the goal being to propose the best
experience possible to users.
The goal of image recognition is to identify, label and classify objects which are
detected into different categories. Object or image recognition is a whole process
that involves various traditional computer vision tasks:
For the past few years, this computer vision task has achieved big successes,
mainly thanks to machine learning applications.
In order to go through these 4 tasks and to complete them, machine learning and
image recognition systems do require going through a few important steps.
First of all, the machine has to know exactly what it has to look for. Thus, it is
necessary to give it the parameters you decide to work on. Defining the dimensions
of bounding boxes and what elements are inside is crucial. To do so, the machine
has to be provided with some references, which can be pictures, videos or
photographs, etc. These elements will allow it to be more efficient when analyzing
future data. This will create a sort of data library that will then be used by
the Neural Network to distinguish the various objects. A Neural Network is
composed of multiple artificial neurons. These neurons are meant to imitate the
human brain. It works with a set of various algorithms also inspired by the way the
brain functions. If we want the image recognition model to analyze and categorize
different races of dogs, the model will need to have a database of the various races
in order to recognize them.
Second, the model needs to go on a training phase. The dataset needs to be entered
within a program in order to function properly. And this phase is only meant to
train the Convolutional Neural Network (CNN) to identify specific objects and
organize them accurately in the correspondent classes.
Hereafter are some of the most popular Image Recognition with Machine Learning
Models and how they work.
Support Vector Machines (SVM)
SVM models use a set of techniques in order to create an algorithm that will
determine whether an image corresponds to the target object or if it does not. From
the dataset it was set with, the SVM model is trained to separate a hyper plan into
several categories. During the process, depending on the pixel values, the objects
are being placed in the hyper plan their position predicts a category based on the
category separation learned from the training phase.
This bag of features models takes into account the image to be analyzed and a
reference sample photo. Then, the algorithm in the model tries to match pixel
patterns from the sample photo with some parts of the target picture to analyze.
Viola-Jones Algorithm
This is one of the most famous ones used for facial recognition. It was used even
before using CNNs. It scans the faces of people, extracts some of the features from
the faces, and classifies them. It also uses a boosting algorithm which is meant to
help have a much more accurate classification.
We have dealt with CNN earlier in this article. But it is necessary to go a little
deeper with this concept.
Machine learning relies on the things the Human Brain gave it. It is mainly
supervised by people, first when it comes to delivering the set of the reference
images, to training the machine into distinguishing the objects and testing the
method. CNN is a specific model architecture from Deep Learning techniques.
CNN algorithm allows machines to detect and classify with quite an impressive
precision all of the objects which are observed in a picture.
This type of algorithm works with different layers of perception. It is often hard to
interpret a specific layer role in the final prediction but research has made progress
on it. We can for example interpret that a layer analyzes colors, another one
shapes, a next one textures of the objects, etc. At the end of the process, it is the
superposition of all layers that makes a prediction possible.
Popular Image recognition Algorithms
Deep Learning has shown to be extremely efficient for detecting objects and
classifying them. Different approaches are available and each has their own
characteristics. Here are three of these proceedings.
Using the Single Shot Detector algorithm is directly linked to RCNN. When
identifying and drawing bounding boxes, most of the time, they overlap each other.
This is mainly why SSDs are used. To prevent these boxes from overlapping,
SSDs use a grid with various ratios to divide the image. Then if we observe a box
being placed on top of another one, for example, because the system detected a girl
in front of a car, the algorithm proposes to create two different anchor boxes, in
order to separate the two items. That way, the picture is divided into different
feature plans and is treated separately, and the machine is able to handle the
analysis of more objects. This technique reveals to be very successful, accurate,
and can be executed quite rapidly.
As the name of the algorithm might suggest, the technique processes the whole
picture only one-time thanks to a fixed-size grid. It looks for elements in each part
of the grid and determines if there is any item. If so, it will be identified with
abounding boxes and then classify it with a category. Looking at the grid only once
makes the process quite rapid, but there is a risk that the method does not go deep
into details. The results are less accurate than with the SSD method.
Programming Image recognition
Some accessible solutions exist for anybody who would like to get familiar with
these techniques. An introduction tutorial is even available on Google on that
specific topic.
Various methods are used to detect items in a picture and classify them. But how
do we apply them to our devices?
To start working on this topic, Python and the necessary extension packages
should be downloaded and installed on your system. Some of the packages include
applications with easy-to-understand coding and make AI an approachable method
to work on. It is recommended to own a device that handles images quite
effectively. We are talking about good quality graphics cards for instance. The next
step will be to provide Python and the image recognition application with a free
downloadable and already labeled dataset, in order to start classifying the various
elements. Finally, a little bit of coding will be needed, including drawing the
bounding boxes and labeling them.
Programming item recognition using this method can be done fairly easily and
rapidly. That way, you can deploy the program within a short period of time. But,
it should be taken into consideration that choosing this solution, taking images
from an online cloud, might lead to privacy and security issues. This process
should be used for testing or at least an action that is not meant to be permanent.
Edge AI
Edge AI is very often used with real-time videos. In most cases, it will be used
with connected objects or any item equipped with motion sensors.
AI Platform
Some online platforms are available to use in order to create an image recognition
system, without starting from zero. If you don’t know how to code, or if you are
not so sure about the procedure to launch such an operation, you might consider
using this type of pre-configured platform.
The different fields of application for image recognition with machine learning
Nowadays, Computer Vision and recognition are always around us. From
unlocking your phone with your face in the morning to coming into a mall to do
some shopping. Many different industries have decided to implement Artificial
Intelligence in their processes.
Facial recognition
Smart Farming
Farmers’ daily lives are far from being easy. To keep taking good care of both their
animals and their plantations, they need to monitor them both.
Monitoring their animals has become a comfortable way for farmers to watch their
cattle. With cameras equipped with motion sensors and image detection programs,
they are able to make sure that all their animals are in good health. They can also
monitor animal births. Farmers can easily detect if a cow is having difficulties
giving birth to its calf. They can intervene rapidly to help the animal deliver the
baby, thus preventing the potential death of two animals.
Farmers also grow their own plants, mainly to feed their cattle. To see if the fields
are in good health, image recognition can be programmed to detect the presence of
a disease on a plant for example. The farmer can treat the plantation rapidly and be
able to harvest peacefully.
Security and safety are two major concerns in today’s society. Thanks to image
recognition and detection, it gets easier to identify criminals or victims, and even
weapons. In an airport for example, where safety is crucial. All-day long, security
agents are scrutinizing screens. Helped by Artificial Intelligence, they are able to
detect dangers extremely rapidly. When a piece of luggage is unattended, the
watching agents can immediately get in touch with the field officers, in order to get
the situation under control and to protect the population as soon as possible. When
a passport is presented, the individual's fingerprints and face are analyzed to make
sure they match with the original document.
Ecommerce
Online stores are experiencing a boom since the beginning of the COVID-19
pandemic. They managed to develop their activities exponentially thanks to
various elements.
One of the recent advances they have come up with is image recognition to better
serve their customer. Many platforms are now able to identify the favorite products
of their online shoppers and to suggest them new items to buy, based on what they
have watched previously.
On another note, some new applications propose their users simply snap a picture
of an item found on somebody they have met in the street, in order to find a store
that has a similar or the same item available for purchase. The algorithm is then
able to give a list of places where you can buy the shoes your friend was wearing
today.
Improvements made in the field of AI and picture recognition for the past decades
have been tremendous. There is absolutely no doubt that researchers are already
looking for new techniques based on all the possibilities provided by these
exceptional technologies
SPEECH RECOGNITION:
Speech recognition software must adapt to the highly variable and context-specific
nature of human speech. The software algorithms that process and organize audio
into text are trained on different speech patterns, speaking styles, languages,
dialects, accents and phrasings. The software also separates spoken audio from
background noise that often accompanies the signal.
To meet these requirements, speech recognition systems use two types of models:
Mobile devices. Smartphones use voice commands for call routing, speech-to-text
processing, voice dialing and voice search. Users can respond to a text without
looking at their devices. On Apple iPhones, speech recognition powers the
keyboard and Siri, the virtual assistant. Functionality is available in secondary
languages, too. Speech recognition can also be found in word processing
applications like Microsoft Word, where users can dictate words to be turned into
text.
Disability assistance. Speech recognition software can translate spoken words into
text using closed captions to enable a person with hearing loss to understand what
others are saying. Speech recognition can also enable those with limited use of
their hands to work with computers, using voice commands instead of typing.
Language weighting. This feature tells the algorithm to give special attention
to certain words, such as those spoken frequently or that are unique to the
conversation or subject. For example, the software can be trained to listen for
specific product references.
Acoustic training. The software tunes out ambient noise that pollutes spoken
audio. Software programs with acoustic training can distinguish speaking
style, pace and volume amid the din of many people speaking in an office.
Speaker labeling. This capability enables a program to label individual
participants and identify their specific contributions to a conversation.
Profanity filtering. Here, the software filters out undesirable words and
language.
What are the different speech recognition algorithms?
The power behind speech recognition features comes from a set of algorithms and
technologies. They include the following:
But, in the figure shown below, it can be observed that the quantity of such
emails has decreased significantly after 2016 because of the evolution of the
software that can detect these spam emails and can filter them out.
Many several techniques are present in the market to detect spam e-mails. If we
want to classify broadly, there are 5 different techniques based on which
algorithms decide whether any mail is spam or not.
Content-Based Filtering Technique
Algorithms analyze words, the occurrence of words, and the distribution of words
and phrases inside the content of e-mails and segregate them into spam and non-
spam categories
Algorithms use pre-defined rules in the form of a regular expression to give a score
to the messages present in the e-mails. Based on the scores generated, they
segregate emails into spam and non-spam categories.
Algorithms classify the incoming mails into various groups and, based on the
comparison scores of every group with the defined set of groups, spam, and non-
spam emails got segregated.
This article will give an idea for implementing content-based filtering using one of
the most famous algorithms for spam detection, which is K-Nearest Neighbour
(KNN).
k-NN based algorithms are widely used for clustering tasks. Let’s quickly know
the entire architecture of this implementation first and then explore every step.
Executing these 5 steps, one after the other will help us implement our spam
classifier smoothly.
Training Testing Phase
1. Enron corpus datasets (Created in 2006 and having 55% spam emails)
2. Tre c 2007 dataset ( Created in 2007 and having 67% spam emails)
Train/Test Split: Split the dataset into train and test datasets but make sure that
both sets must balance the numbers of ham and spam emails (ham is a fancy name
for non-spam emails).
Enron Corpus Dataset on Kaggle
These days, senders have options to attach inline images to the mail. These emails
can be categorized as spam emails not based on their mail content but on the
images' content. This was not an easy task until Google came up with the open-
source library Tesser act. This library extracts the words from images
automatically with certain accuracy. But still, Times New Roman and Captcha
words are difficult to read automatically.
You must be clear that the more the number of attributes → more the time
complexity of the model. These attributes can be huge, and hence techniques like
Stemming, noise removal ,and stop-words removal can be used. One of the famous
stemming algorithms is the Porter Stemmer Algorithm. Some general things that
we do in stemming are:
To find the nearest instance, one can use the Euclidean distance. One can use the
Scikit-learn library to implement the K-NN algorithm for this task.
Step 5: Performance Analysis
Now our algorithm is ready, so we must check the performance of the model. Even
a single missed important message may cause a user to reconsider the value of
spam filtering. So we must be sure that our algorithm will be as close to
100%accurate. But some researchers feel that considering only the accuracy as the
evaluation parameter for spam classification is not enough.
According to the below table (also known as the confusion matrix), we must
evaluate our spam-classification model based on 4 different parameters.
More advanced algorithms are available in the market for this classification, but
you can easily achieve more than 90% accuracy using k-NN based
implementation.
Preventing, detecting, and eliminating fraud are some of the primary concerns of
the e-commerce and banking industries at present. One of the most promising
means for achieving them are machine learning development services.
Machine learning has already been used to successfully detect email spam. It also
makes focused product recommendations for millions of online shoppers. The
availability of big data allows machine learning to develop at a great scale and
improve significantly over a very short time. Advances in statistical modeling and
constantly increasing processing power make it possible for machine learning to
enter the e-commerce and banking sectors. These industries are placing big hopes
on effective fraud detection using machine learning as a tool that can prevent cyber
crime. Let’s see how this goal can be achieved.
Fraud detection machine learning models are more effective than humans
The concept behind using machine learning in fraud detection is that fraudulent
transactions have specific features that legitimate transactions do not. Based on this
assumption, machine learning algorithms detect patterns in financial operations
and decide whether a given transaction is legitimate. Machine learning fraud
detection algorithms are way more effective than humans. They can process a raft
of information faster than a team of the best analysts ever could. What’s more, ML
algorithms can spot patterns that seem unrelated or go unnoticed by a human. By
exploring and studying tons of cases of fraudulent behavior, ML algorithms
determine the most stealthy fraudulent patterns and remember them forever.
ML handles overload well
The traditional fraud detection model is based on a static rules-based system, also
referred to as a production or expert system. Although these systems have been
effective for a long time, some of their major disadvantages make them unsuitable
for modern digital environments. A static rules-based system is heavily dependent
on human labor. But naturally, top analysts are expensive. And their work takes
time. What’s more, even top experts create rules based on their knowledge, skills,
and experience, which are always limited. Such rules can grow to enormous sizes
and get so complex that it’s nearly impossible for an outsider to understand them
when needed. Also, creating a new rule and implementing it takes a while when
done by hand.
Fraud detection using machine learning can solve all of these issues. It can beat
traditional fraud detection systems in terms of speed, quality, and cost-
effectiveness. An unsupervised machine learning system can process new data
autonomously all the time and update its models and patterns immediately. As the
data assets of every business become more and more overwhelming, it becomes
clear that only machine learning can cope with this volume of information. The
more data ML algorithms process, the better they get and the more they learn.
Eventually, more data and higher workloads mean better and more precise fraud
detection algorithms.
Supervised learning
Unsupervised learning
Semi-supervised learning
Reinforcement learning
Supervised learning
Semi-supervised learning
Reinforcement learning
MEDICAL DIAGNOSIS
To demonstrate how machine learning and deep learning are able to provide a
medical diagnosis, I’ll walk you through a step-by-step example of how the
technology can be used to detect and diagnose breast cancer using a publicly
available data set.
Challenges of Applying Machine Learning in Healthcare
The breast cancer data set consists of 699 tumor samples where 458 (65.5%) are
benign (non-cancer) tumors and 241 (34.5%) malignant (cancer) tumors. Instances
in the data set have the following attributes:
In our example, given the relatively small sizes of data sets, my intuition was to
start modeling using traditional machine learning algorithms (e.g. SVM, KNN etc.)
and shallow neural networks. To demonstrate some initial results using machine
learning to diagnose breast cancer, the following set of metrics are used: ROC
curve ≈ 0.99, Precision-Recall curve ≈ 0.99, and F1 ≈ 0.97.
In order to get started modeling, the data set was split into two parts:
Next, we need to define the key metrics to measure the efficiency of the models. In
order to describe the classifiers’ performance in the digital diagnoses problem, we
have four basic characteristics (numbers) based on which we can define derivative
measurement metrics. These four numbers are:
The next step involves using precision and recall metrics to evaluate the models.
For the sake of simplifying the comparison of various models, we will use the
harmonic mean of precision and recall which is called an F1 score (F1 Score =
2*(Recall * Precision) / (Recall + Precision)).
As you can see from the graph, the classifiers are showing pretty good results in
terms of being able to better distinguish patients who have cancer versus those who
are healthy by reaching 0.94 F1 scores. Where the best value for F1 is 1, and the
worst value is 0. In order to gain higher scores, ensembles of these models were
created by using bagging techniques.
Cross-validation scores of the ensemble Machine Learning models.
As shown in the graph, the ensembles of models performed even better by reaching
0.95 F1 scores.
This neural network classifier has resulted in 0.97 F1 mean scores on cross-
validation. This new neural network model’s F1 score is better compared to the
best model’s score gained in Step 3. Here are the top three models results so far.
As it’s shown in the graph, neural network classifier have performed better by
gaining 0.97 F1 scores on the test set.
In order to further evaluate classifiers’ output quality, let’s view their receiver
operating characteristic (ROC) curves.
The ROC graph efficiency is measured by the area under the curve. An area of 1
represents a perfect classifier, an area of 0.5 represents a worthless classifier (navy
color, dashed line in the graph). Here is the academic point system for judging
classifiers efficiency given to area under the curve.
As it’s shown in the graph, all of three classifiers have above 0.99 area under the
curve which is considered excellent.
Let’s also look at the precision-recall curves associated with these classifiers.
The navy dashed line represents the baseline, where the perfect model is the one
with 1 average precision. As you can see, all three models’ average precision is
close to 1, which are excellent scores.
Conclusion