Unit II Notes
Unit II Notes
Instance-based learning
It is called instance-based because it constructs hypotheses directly from the training instances
themselves. This means that the hypothesis complexity can grow with the data: in the worst case, a
hypothesis is a list of n training items and the computational complexity of classifying a single new
instance is O(n). One advantage that instance-based learning has over other methods of machine
learning is its ability to adapt its model to previously unseen data. Instance-based learners may
simply store a new instance or throw an old instance away.
Examples of instance-based learning algorithm are the k-nearest neighbors algorithm, kernel
machines and RBF networks. These store (a subset of) their training set; when predicting a
value/class for a new instance, they compute distances or similarities between this instance and the
training instances to make a decision.
To battle the memory complexity of storing all training instances, as well as the risk of overfitting to
noise in the training set, instance reduction algorithms have been proposed.
Gagliardi applies this family of classifiers in medical field as second-opinion diagnostic tools and as
tools for the knowledge extraction phase in the process of knowledge discovery in databases. One of
these classifiers (called Prototype exemplar learning classifier (PEL-C) is able to extract a mixture
of abstracted prototypical cases (that are syndromes) and selected atypical clinical cases.
3.1 − Calculate the distance between test data and each row of training data with the help of
any of the method namely: Euclidean, Manhattan or Hamming distance. The most commonly
used method to calculate distance is Euclidean.
3.2 − Now, based on the distance value, sort them in ascending order.
3.3 − Next, it will choose the top K rows from the sorted array.
3.4 − Now, it will assign a class to the test point based on most frequent class of these rows.
Step 4 − End
EXAMPLE
Nearest-Neighbor Classifiers
o Require three things
The set of stored examples
Distance Metric to compute distance between examples
The value of k, the number of nearest neighbors to retrieve
o To classify an unknown example:
Compute distance to other training examples
Identify k nearest neighbors
Use class labels of nearest neighbors to determine the class label of unknown
example (e.g., by taking majority vote)
Distance Functions
o Computes the distance between two examples so that we can find the “nearest neighbor” to a
given example
o General Idea: reduce the distance d (x1, x2) of two examples to the distances d A (v1, v2)
between two values for attribute A
o Popular choices
Curse of Dimensionality
The curse of dimensionality refers to the phenomena that occur when classifying, organizing, and
analyzing high dimensional data that does not occur in low dimensional spaces, specifically the issue
of data sparsity and “closeness” of data. The size of the data space grows exponentially with the
number of dimensions. This means that the size of your data set must also grow exponentially in
order to keep the same density. If you don‟t, then data points start getting farther and farther apart.
Consider an example in which we have a set of images, each of which depicts either a cat or a dog.
We would like to create a classifier that is able to distinguish dogs from cats automatically. To do so,
we first need to think about a descriptor for each object
class that can be expressed by numbers, such that a
mathematical algorithm, i.e. a classifier, can use these
numbers to recognize the object. We could for instance
argue that cats and dogs generally differ in color.
However, these three color-describing numbers, called
features, will obviously not suffice to obtain a perfect
classification. To obtain an even more accurate
classification, we could add more features, based on
color or texture Maybe we can obtain a perfect classification by carefully defining a few hundred of
these features? The answer to this question might sound a bit counter-intuitive: no we can not!. In
fact, after a certain point, increasing the dimensionality of the problem by adding new features would
actually degrade the performance of our classifier. This is illustrated by figure 1, and is often referred
to as „The Curse of Dimensionality‟.
Why is this especially problematic for k-nearest neighbors?
The special challenge with k-nearest neighbors is that it requires a point to be close in every single
dimension. Some algorithms can create regressions based on single dimensions, and only need points
to be close together along that axis. k-nearest neighbors doesn‟t work that way. It needs all points to
be close along every axis in the data space. And each new axis added, by adding a new dimension,
makes it harder and harder for two specific points to be close to each other in every axis.
Feature Reduction in ML
In machine learning classification problems, there are often too many factors on the basis of
which the final classification is done. These factors are basically variables called features. The
higher the number of features, the harder it gets to visualize the training set and then work on it.
Sometimes, most of these features are correlated, and hence redundant. This is where
dimensionality reduction algorithms come into play. Dimensionality reduction is the process of
reducing the number of random variables under consideration, by obtaining a set of principal
variables.
It can be divided into
1. feature selection and
2. feature extraction.
A. Filter Methods
Filter methods are generally used as a preprocessing step. The selection of features is
independent of any machine learning algorithms. Instead, features are selected on the basis
of their scores in various statistical tests for their correlation with the outcome variable.
The correlation is a subjective term here. For basic guidance, you can refer to the following
table for defining correlation co-efficients.
Pearson’s Correlation: It is used as a measure for quantifying linear dependence between
two continuous variables X and Y. Its value varies from -1 to +1. Pearson‟s correlation is
given as:
OR
LDA: Linear discriminant analysis is used to find a linear combination of features that
characterizes or separates two or more classes (or levels) of a categorical variable.
ANOVA: ANOVA stands for Analysis of variance. It is similar to LDA except for the fact
that it is operated using one or more categorical independent features and one continuous
dependent feature. It provides a statistical test of whether the means of several groups are
equal or not.
Chi-Square: It is a is a statistical test applied to the groups of categorical features to evaluate
the likelihood of correlation or association between them using their frequency distribution.
B. Wrapper Methods
In wrapper methods, we try to use a subset of features and train a model using them. Based
on the inferences that we draw from the previous model, we decide to add or remove features
from your subset. The problem is essentially reduced to a search problem. These methods are
usually computationally very expensive.
Some common examples of wrapper methods are forward feature selection, backward feature
elimination, recursive feature elimination, etc.
Forward Selection: Forward selection is an iterative method in which we start with
having no feature in the model. In each iteration, we keep adding the feature which best
improves our model till an addition of a new variable does not improve the performance
of the model.
Backward Elimination: In backward elimination, we start with all the features and
removes the least significant feature at each iteration which improves the performance of
the model. We repeat this until no improvement is observed on removal of features.
Recursive Feature elimination: It is a greedy optimization algorithm which aims to find
the best performing feature subset. It repeatedly creates models and keeps aside the best
or the worst performing feature at each iteration. It constructs the next model with the left
features until all the features are exhausted. It then ranks the features based on the order
of their elimination.
It works in the following steps:
1. Firstly, it adds randomness to the given data set by creating shuffled copies of all
features (which are called shadow features).
2. Then, it trains a random forest classifier on the extended data set and applies a
feature importance measure (the default is Mean Decrease Accuracy) to evaluate
the importance of each feature where higher means more important.
3. At every iteration, it checks whether a real feature has a higher importance than the
best of its shadow features (i.e. whether the feature has a higher Z-score than the
maximum Z-score of its shadow features) and constantly removes features which
are deemed highly unimportant.
4. Finally, the algorithm stops either when all features get confirmed or rejected or it
reaches a specified limit of random forest runs.
C. Embedded Methods
Embedded methods combine the qualities‟ of filter and wrapper methods. It‟s
implemented by algorithms that have their own built-in feature selection methods.
Some of the most popular examples of these methods are LASSO and RIDGE regression
which have inbuilt penalization functions to reduce overfitting.
Lasso regression performs L1 regularization which adds penalty equivalent to
absolute value of the magnitude of coefficients.
Ridge regression performs L2 regularization which adds penalty equivalent to square
of the magnitude of coefficients.
This method was introduced by Karl Pearson. It works on a condition that while the data in a
higher dimensional space is mapped to data in a lower dimension space, the variance of the data
in the lower dimensional space should be maximum.
N
z1 a1T x j ai1 xij , j 1,2,, p.
i 1
Listed below are the 5 general steps for performing a linear discriminant analysis.
Compute the d-dimensional mean vectors for the different classes from the dataset.
Compute the scatter matrices (in-between-class and within-class scatter matrix).
Compute the eigenvectors and corresponding eigenvalues for the scatter matrices.
Sort the eigenvectors by decreasing eigenvalues and k eigenvectors with the largest
eigenvalues to form a d×k dimensional matrix WW (where every column represents
an eigenvector).
Use this d×k eigenvector matrix to transform the samples onto the new subspace. This
can be summarized by the matrix multiplication: YY=XX×WW (where XX is a n×d-
dimensional matrix representing the n samples, and yy are the transformed n×k-
dimensional samples in the new subspace).
Content-based approach requires a good amount of information of items’ own features, rather than
using users’ interactions and feedbacks. For example, it can be movie attributes such as genre, year,
director, actor etc., or textual content of articles that can extracted by applying Natural Language
Processing.
Collaborative Filtering, on the other hand, doesn’t need anything else except users’ historical
preference on a set of items. Because it’s based on historical data, the core assumption here is that the
users who have agreed in the past tend to also agree in the future. In terms of user preference, it
usually expressed by two categories.
Explicit Rating, is a rate given by a user to an item on a sliding scale, like 5 stars for Titanic.
This is the most direct feedback from users to show how much they like an item.
Implicit Rating, suggests users preference indirectly, such as page views, clicks, purchase
records, whether or not listen to a music track, and so on. In this article, I will take a close
look at collaborative filtering that is a traditional and powerful tool for recommender systems.
user-based CF and
item-based CF.
Let‟s first look at User-based CF. We have an n × m matrix of ratings, with user uᵢ, i = 1, ...n and
item pⱼ, j=1, …m. Now we want to predict the rating rᵢⱼ if target user i did not watch/rate an item j.
The process is to calculate the similarities between target user i and all other users, select the top X
similar users, and take the weighted average of ratings from these X users with similarities as
weights.
Source: [Link]
While different people may have different baselines when giving ratings, some people tend to give
high scores generally, some are pretty strict even though they are satisfied with items. To avoid this
bias, we can subtract each user’s average rating of all items when computing weighted average, and
add it back for target user, shown as below.
Two ways to calculate similarity are Pearson Correlation and Cosine Similarity.
Basically, the idea is to find the most similar users to your target user (nearest neighbors) and weight
their ratings of an item as the prediction of the rating of this item for target user.
Without knowing anything about items and users themselves, we think two users are similar when
they give the same item similar ratings . Analogously, for Item-based CF, we say two items are
similar when they received similar ratings from a same user. Then, we will make prediction for a
target user on an item by calculating weighted average of ratings on most X similar items from this
user. One key advantage of Item-based CF is the stability which is that the ratings on a given item
will not change significantly overtime, unlike the tastes of human beings.
There are quite a few limitations of this method. It doesn‟t handle sparsity well when no one in the
neighborhood rated an item that is what you are trying to predict for target user. Also, it‟s not
computational efficient as the growth of the number of users and products.
Matrix Factorization
Since sparsity and scalability are the two biggest challenges for standard CF method, it comes a more
advanced method that decompose the original sparse matrix to low-dimensional matrices with latent
factors/features and less sparsity. That is Matrix Factorization.
Beside solving the issues of sparsity and scalability, there‟s an intuitive explanation of why we need
low-dimensional matrices to represent users‟ preference. A user gave good ratings to movie Avatar,
Gravity, and Inception. They are not necessarily 3 separate opinions but showing that this users might
be in favor of Sci-Fi movies and there may be many more Sci-Fi movies that this user would like.
Unlike specific movies, latent features is expressed by higher-level attributes, and Sci-Fi category is
one of latent features in this case. What matrix factorization eventually gives us is how much a user is
aligned with a set of latent features, and how much a movie fits into this set of latent features. The
advantage of it over standard nearest neighborhood is that even though two users haven‟t rated any
same movies, it‟s still possible to find the similarity between them if they share the similar underlying
tastes, again latent features.
To see how a matrix being factorized, first thing to understand is Singular Value
Decomposition(SVD). Based on Linear Algebra, any real matrix R can be decomposed into 3
matrices U, Σ, and V. Continuing using movie example, U is an n × r user-latent feature matrix, V is
an m × r movie-latent feature matrix. Σ is an r × r diagonal matrix containing the singular
values of original matrix, simply representing how important a specific feature is to predict
user preference.
To sort the values of Σ by decreasing absolute value and truncate matrix Σ to first k dimensions( k
singular values), we can reconstruct the matrix as matrix A. The selection of k should make sure that
A is able to capture the most of variance within the original matrix R, so that A is the approximation
of R, A ≈ R. The difference between A and R is the error that is expected to be minimized. This is
exactly the thought of Principle Component Analysis.
When matrix R is dense, U and V could be easily factorized analytically. However, a matrix of movie
ratings is super sparse. Although there are some imputation methods to fill in missing values , we will
turn to a programming approach to just live with those missing values and find factor matrices U and
V. Instead of factorizing R via SVD, we are trying find U and V directly with the goal that when U
and V multiplied back together the output matrix R‟ is the closest approximation of R and no more a
sparse matrix. This numerical approximation is usually achieved with Non-Negative Matrix
Factorization for recommender systems since there is no negative values in ratings.
See the formula below. Looking at the predicted rating for specific user and item, item i is noted as a
vector qᵢ, and user u is noted as a vector pᵤ such that the dot product of these two vectors is the
predicted rating for user u on item i. This value is presented in the matrix R‟ at row u and column i.
How do we find optimal qᵢ and pᵤ? Like most of machine learning task, a loss function is defined to
minimize the cost of errors.
rᵤᵢ is the true ratings from original user-item matrix. Optimization process is to find the optimal matrix
P composed by vector pᵤ and matrix Q composed by vector qᵢ in order to minimize the sum square
error between predicted ratings rᵤᵢ‟ and the true ratings rᵤᵢ. Also, L2 regularization has been added to
prevent overfitting of user and item vectors. It‟s also quite common to add bias term which usually
has 3 major components: average rating of all items μ, average rating of item i minus μ(noted as bᵤ),
average rating given by user u minus u(noted as bᵢ).
Before we dive into Bayes theorem, let‟s review marginal, joint, and conditional probability.
Recall that marginal probability is the probability of an event, irrespective of other random
variables. If the random variable is independent, then it is the probability of the event directly,
otherwise, if the variable is dependent upon other variables, then the marginal probability is the
probability of the event summed over all outcomes for the dependent variables, called the sum
rule.
The joint probability is the probability of two (or more) simultaneous events, often described in
terms of events A and B from two dependent random variables, e.g. X and Y. The joint
probability is often summarized as just the outcomes, e.g. A and B.
Joint Probability: Probability of two (or more) simultaneous events, e.g. P(A and B) or
P(A, B).
The conditional probability is the probability of one event given the occurrence of another event,
often described in terms of events A and B from two dependent random variables e.g. X and Y.
Conditional Probability: Probability of one (or more) event given the occurrence of
another event, e.g. P(A given B) or P(A | B).
The joint probability can be calculated using the conditional probability; for example:
This is called the product rule. Importantly, the joint probability is symmetrical, meaning that:
P(A, B) = P(B, A)
The conditional probability can be calculated using the joint probability; for example:
P(A | B) != P(B | A)
Specifically, one conditional probability can be calculated using the other conditional probability; for
example:
This alternate approach of calculating the conditional probability is useful either when the joint
probability is challenging to calculate (which is most of the time), or when the reverse conditional
probability is available or easy to calculate.
This alternate calculation of the conditional probability is referred to as Bayes Rule or Bayes
Theorem, named for Reverend Thomas Bayes, who is credited with first describing it. It is
grammatically correct to refer to it as Bayes‟ Theorem (with the apostrophe), but it is common to
omit the apostrophe for simplicity.
Bayes Theorem: Principled way of calculating a conditional probability without the joint
probability.
It is often the case that we do not have access to the denominator directly, e.g. P(B).
This gives a formulation of Bayes Theorem that we can use that uses the alternate calculation of
P(B), described below:
As such, if we have P(A), then we can calculate P(not A) as its complement; for example:
P(not A) = 1 – P(A)
Additionally, if we have P(not B|not A), then we can calculate P(B|not A) as its complement; for
example:
Now that we are familiar with the calculation of Bayes Theorem, let‟s take a closer look at the
meaning of the terms in the equation.
The terms in the Bayes Theorem equation are given names depending on the context where the
equation is used.
It can be helpful to think about the calculation from these different perspectives and help to map your
problem onto the equation.
Firstly, in general, the result P(A|B) is referred to as the posterior probability and P(A) is referred
to as the prior probability.
Sometimes P(B|A) is referred to as the likelihood and P(B) is referred to as the evidence.
P(B|A): Likelihood.
P(B): Evidence.
It provides a way of thinking about the relationship between data and a model.
A machine learning algorithm or model is a specific way of thinking about the structured
relationships in the data. In this way, a model can be thought of as a hypothesis about the
relationships in the data, such as the relationship between input (X) and output (y). The practice of
applied machine learning is the testing and analysis of different hypotheses (models) on a given
dataset.
Bayes Theorem provides a probabilistic model to describe the relationship between data (D) and a
hypothesis (h); for example:
Breaking this down, it says that the probability of a given hypothesis holding or being true given
some observed data can be calculated as the probability of observing the data given the hypothesis
multiplied by the probability of the hypothesis being true regardless of the data, divided by the
probability of observing the data regardless of the hypothesis.
Under this framework, each piece of the calculation has a specific name; for example:
This gives a useful framework for thinking about and modeling a machine learning problem.
If we have some prior domain knowledge about the hypothesis, this is captured in the prior
probability. If we don‟t, then all hypotheses may have the same prior probability.
If the probability of observing the data P(D) increases, then the probability of the hypothesis holding
given the data P(h|D) decreases. Conversely, if the probability of the hypothesis P(h) and the
probability of observing the data given hypothesis increases, the probability of the hypothesis
holding given the data P(h|D) increases.
The notion of testing different models on a dataset in applied machine learning can be thought of as
estimating the probability of each hypothesis (h1, h2, h3, … in H) being true given the observed
data.
The optimization or seeking the hypothesis with the maximum posterior probability in modeling is
called maximum a posteriori or MAP for short.
Under this framework, the probability of the data (D) is constant as it is used in the assessment of
each hypothesis. Therefore, it can be removed from the calculation to give the simplified
unnormalized estimate as follows:
If we do not have any prior information about the hypothesis being tested, they can be assigned a
uniform probability, and this term too will be a constant and can be removed from the calculation to
give the following:
That is, the goal is to locate a hypothesis that best explains the observed data.
Fitting models like linear regression for predicting a numerical value, and logistic regression for
binary classification can be framed and solved under the MAP probabilistic framework. This
provides an alternative to the more common maximum likelihood estimation (MLE) framework.
Classification is a predictive modeling problem that involves assigning a label to a given input data
sample.
The problem of classification predictive modeling can be framed as calculating the conditional
probability of a class label given a data sample, for example:
This calculation can be performed for each class in the problem and the class that is assigned the
largest probability can be selected and assigned to the input data.
In practice, it is very challenging to calculate full Bayes Theorem for classification.
The priors for the class and the data are easy to estimate from a training dataset, if the dataset is
suitability representative of the broader problem.
The conditional probability of the observation based on the class P(data|class) is not feasible unless
the number of examples is extraordinarily large, e.g. large enough to effectively estimate the
probability distribution for all different possible combinations of values. This is almost never the
case, we will not have sufficient coverage of the domain.
As such, the direct application of Bayes Theorem also becomes intractable, especially as the number
of variables or features (n) increases.
The solution to using Bayes Theorem for a conditional probability classification model is to simplify
the calculation.
The Bayes Theorem assumes that each input variable is dependent upon all other variables. This is a
cause of complexity in the calculation. We can remove this assumption and consider each input
variable as being independent from each other.
This changes the model from a dependent conditional probability model to an independent
conditional probability model and dramatically simplifies the calculation.
This means that we calculate P(data|class) for each input variable separately and multiple the results
together, for example:
We can also drop the probability of observing the data as it is a constant for all calculations, for
example:
This simplification of Bayes Theorem is common and widely used for classification predictive
modeling problems and is generally referred to as Naive Bayes.
The word “naive” is French and typically has a diaeresis (umlaut) over the “i”, which is commonly
left out for simplicity, and “Bayes” is capitalized as it is named for Reverend Thomas Bayes.
The Bayes optimal classifier is a probabilistic model that makes the most likley prediction for a new
example, given the training dataset.
This model is also referred to as the Bayes optimal learner, the Bayes classifier, Bayes optimal
decision boundary, or the Bayes optimal discriminant function.
Bayes Classifier: Probabilistic model that makes the most probable prediction for new examples.
This is different from the MAP framework that seeks the most probable hypothesis (model). Instead,
we are interested in making a specific prediction.
The equation below demonstrates how to calculate the conditional probability for a new instance (vi)
given the training data (D), given a space of hypotheses (H).
Where vj is a new instance to be classified, H is the set of hypotheses for classifying the
instance, hi is a given hypothesis, P(vj | hi) is the posterior probability for vi given hypothesis hi,
and P(hi | D) is the posterior probability of the hypothesis hi given the data D.
Selecting the outcome with the maximum probability is an example of a Bayes optimal
classification.
Any model that classifies examples using this equation is a Bayes optimal classifier and no other
model can outperform this technique, on average.
Because the Bayes classifier is optimal, the Bayes error is the minimum possible error that can be
made.
Bayes Error: The minimum possible error that can be made when making predictions.
The Naive Bayes classifier is an example of a classifier that adds some simplifying assumptions and
attempts to approximate the Bayes Optimal Classifier.
Developing classifier models may be the most common application on Bayes Theorem in machine
learning.
Nevertheless, there are many other applications. Two important examples are optimization and
causal models.
Bayesian Optimization
Global optimization is a challenging problem of finding an input that results in the minimum or
maximum cost of a given objective function.
Typically, the form of the objective function is complex and intractable to analyze and is often non-
convex, nonlinear, high dimension, noisy, and computationally expensive to evaluate.
Bayesian Optimization provides a principled technique based on Bayes Theorem to direct a search of
a global optimization problem that is efficient and effective. It works by building a probabilistic
model of the objective function, called the surrogate function, that is then searched efficiently with
an acquisition function before candidate samples are chosen for evaluation on the real objective
function.
Bayesian Optimization is often used in applied machine learning to tune the hyperparameters of a
given well-performing model on a validation dataset.
Bayesian Belief Networks
Probabilistic models can define relationships between variables and be used to calculate
probabilities.
Fully conditional models may require an enormous amount of data to cover all possible cases, and
probabilities may be intractable to calculate in practice. Simplifying assumptions such as the
conditional independence of all random variables can be effective, such as in the case of Naive
Bayes, although it is a drastically simplifying step.
An alternative is to develop a model that preserves known conditional dependence between random
variables and conditional independence in all other cases. Bayesian networks are a probabilistic
graphical model that explicitly capture the known conditional dependence with directed edges in a
graph model. All missing connections define the conditional independencies in the model.
As such Bayesian Networks provide a useful tool to visualize the probabilistic model for a domain,
review all of the relationships between the random variables, and reason about causal probabilities
for scenarios given available evidence.
The networks are not exactly Bayesian by definition, although given that both the probability
distributions for the random variables (nodes) and the relationships between the random variables
(edges) are specified subjectively, the model can be thought to capture the “belief” about a complex
domain.