0% found this document useful (0 votes)
4 views60 pages

Classification

The document outlines a course on classification in data science, focusing on techniques such as k-nearest neighbors and decision trees to classify iris species based on physical measurements. It explains the concepts of supervised learning, dataset splitting for training and testing, and the importance of model evaluation. Additionally, it discusses potential issues like overfitting and the visualization of decision trees for better understanding of classification models.

Uploaded by

Raju Kumar
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views60 pages

Classification

The document outlines a course on classification in data science, focusing on techniques such as k-nearest neighbors and decision trees to classify iris species based on physical measurements. It explains the concepts of supervised learning, dataset splitting for training and testing, and the importance of model evaluation. Additionally, it discusses potential issues like overfitting and the visualization of decision trees for better understanding of classification models.

Uploaded by

Raju Kumar
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Classification

Data Science
COMP5122M
Lecturer: Duygu Sarikaya
What will you learn?
• Define what classification is
• Classify Iris Species using k-nearest neighbors
• Classify Iris Species using Decision Trees
• Building Decision Trees
• Entropy and Defining a Best Feature
Recap

Supervised Learning Unsupervised Learning


Quantitative Categorical
Response Response

Regression Classification Dimensionality Reduction Clustering

Nearest Neighbors Principal Component KMeans Clustering


Logistic Regression Analysis Agglomerative Clustering

Slide Ref: Principles and Techniques of Data Science, UC Berkeley


Recap
In “Unsupervised Learning”:
● Goal is to identify patterns in Unsupervised Learning
unlabeled data.
○ We do not have input/output pairs.

○ Note: Sometimes we may have Dimensionality Reduction Clustering


labels, but we’re just choosing to
ignore them (e.g. PCA on labeled
data).

Dimensionality Reduction.
● PCA.

Clustering.

Slide Ref: Principles and Techniques of Data Science, UC Berkeley


Recap
In “Supervised Learning”:
● Goal is to create a function that maps
inputs to outputs.
Supervised Learning ● Model is learned from example
input/output pairs. Each pair consists of:
Quantitative Categorical
Response Response ○ Input vector.

Regression Classification ○ Output value (label).


● Regression: Output value is quantitative.

● Classification: Output value is


categorical.

Slide Ref: Principles and Techniques of Data Science, UC Berkeley


A First Application: Classifying Iris Species

• A botanist is interested in distinguishing the species of some iris flowers that she
has found. She has collected some measurements associated with each iris: the
length and width of the petals and the length and width of the sepals, all measured
in centimeters

• Our goal is to build a machine learning model that can learn from the
measurements of these irises whose species is known, so that we can predict the
species for a new iris.
A First Application: Classifying Iris Species

• Because we have measurements for which we know the correct species of iris, this
is a supervised learning problem.

• We want to predict one of several options (the species of iris). This is an example of
a classification problem.

• The possible outputs (different species of irises) are called classes.

• Every iris in the dataset belongs to one of three classes, so this problem is a three-
class classification problem.

• The desired output for a single data point (an iris) is the species of this flower. For a
• particular data point, the species it belongs to is called its label.
A First Application: Classifying Iris Species

• Iris Plants Database


• ====================
• Notes
• ----
• Data Set Characteristics:
• :Number of Instances: 150 (50 in each of three classes)
• :Number of Attributes: 4 numeric, predictive attributes
• ...
• ----
A First Application: Classifying Iris Species
We want to build a machine learning model from this data that can predict the species
of iris for a new set of measurements.

How to measure success? Training and Testing Data

To assess the model’s performance, we show it new data (data that it hasn’t seen before)
for which we have labels.

This is usually done by splitting the labeled data we have collected (here, our 150 flower
measurements) into two parts.

One part of the data is used to build our machine learning model, and is called the training
data or training set.

The rest of the data will be used to assess how well the model works; this is called the test
data, test set, or hold-out set.
A First Application: Classifying Iris Species
Shuffling the dataset:
Using a test set containing only one of the three classes would not tell us much about how well our
model generalizes, so we shuffle our data to make sure the test data contains data from all classes.

Splitting the dataset


We can use 75% of the rows in the data as the training set, together with the corresponding labels for
this data. The remaining 25% of the data, together with the remaining labels, is declared as the test
set.

%75, %25
%80, %20
%70, %30
A First Application: Classifying Iris Species
The output of the train_test_split function (scikit-learn) is X_train, X_test, y_train, and y_test, which
are all NumPy arrays. X_train contains 75% of the rows of the dataset, and X_test contains the
remaining 25%:

print("X_train shape: {}".format(X_train.shape))


print("y_train shape: {}".format(y_train.shape))

X_train shape: (112, 4)


y_train shape: (112,)

print("X_test shape: {}".format(X_test.shape))


print("y_test shape: {}".format(y_test.shape))

X_test shape: (38, 4)


y_test shape: (38,)
Three classes seem
to be relatively well
separated using the
sepal and petal
measurements.
A First Application: Classifying Iris Species
Building Your First Model: k-Nearest Neighbors:

There are many classification algorithms in scikit-learn that we could use.


Here we will use a k-nearest neighbors classifier.

• Stores the training set.

• To make a prediction for a new data point, the algorithm finds the point in the training set that is
closest to the new point.

• Then it assigns the label of this training point to the new data point.

The k in k-nearest neighbors signifies that instead of using only the closest neighbor to the new data
point, we can consider any fixed number k of neighbors in the training (for example, the closest three
or five neighbors).

Then, we can make a prediction using the majority class among these neighbors.
A First Application: Classifying Iris Species

Ref: [Link]
A First Application: Classifying Iris Species
In K-NN, K is the number of nearest neighbors. The number of neighbors is the core
deciding factor. K is generally an odd number if the number of classes is 2. When K=1, then
the algorithm is known as the nearest neighbor algorithm. This is the simplest case.

In the below figure, suppose yellow colored “?” let's say P is the point, for which label needs
to predict. First, you find the one closest point to P and then the label of the nearest point
assigned to P.

[Link]
A First Application: Classifying Iris Species
Second, you find the k closest point to
P and then classify points by majority
vote of its K neighbors. Each object
votes for their class and the class with
the most votes is taken as the
prediction. For finding closest similar
points, we find the distance between
points using distance measures such
as Euclidean distance, Hamming
distance, Manhattan distance, and
Minkowski distance. The algorithm has
the following basic steps:

[Link] distance
[Link] closest neighbors
[Link] for labels

[Link]
A First Application: Classifying Iris Species
We formulated the task of predicting which species of iris a particular flower belongs to by using
physical measurements of the flower.

We used a dataset of measurements that was annotated by an expert with the correct species to
build our model, making this a supervised learning task.

There were three possible species, setosa, versicolor, or virginica, which made the task a three-class
classification problem.

The possible species are called classes in the classification problem, and the species of a single iris is
called its label.

We split our dataset into a training set, to build our model, and a test set, to evaluate how well our
model will generalize to new, previously unseen data.
Decision Trees
A Decision Tree is a very simple way to classify data. It is simply a tree of
questions that must be answered in sequence to yield a predicted classification.

How many
legs?
4
2 0

Can it talk? Snake Does it purr?

no yes yes no
Does it understand
Kangaroo Cat Dog
what it’s saying?
yes no

Human Parrot

Slide Ref: Principles and Techniques of Data Science, UC Berkeley


Classifying Iris Species : Using Petal Data Only
The plot below shows the width and length of the petals of each flower, with
the species annotated in the form of color.

We can build a decision tree manually just by looking at this picture.

Slide Ref: Principles and Techniques of Data Science, UC Berkeley


Example: Using Petal Data Only

Slide Ref: Principles and Techniques of Data Science, UC Berkeley


Example: Using Petal Data Only
Is petal_width < 0.75 and
petal_length < 2?
no yes

Slide Ref: Principles and Techniques of Data Science, UC Berkeley


Example: Using Petal Data Only
Is petal_width < 0.75 and
petal_length < 2?
no yes
setosa

Slide Ref: Principles and Techniques of Data Science, UC Berkeley


Example: Using Petal Data Only
Is petal_width < 0.75 and
petal_length < 2?
no yes
setosa
Is petal_width >= 1.75

Slide Ref: Principles and Techniques of Data Science, UC Berkeley


Example: Using Petal Data Only
Is petal_width < 0.75 and
petal_length < 2?
no yes
setosa
Is petal_width >= 1.75

yes

virginica

Slide Ref: Principles and Techniques of Data Science, UC Berkeley


Example: Using Petal Data Only
Is petal_width < 0.75 and
petal_length < 2?
no yes
setosa
Is petal_width >= 1.75

yes no

virginica Is pedal_width <= 1.55 and


pedal_length <= 4.95

Slide Ref: Principles and Techniques of Data Science, UC Berkeley


Example: Using Petal Data Only
Is petal_width < 0.75 and
petal_length < 2?
no yes
setosa
Is petal_width >= 1.75

yes no

virginica Is pedal_width <= 1.55 and


pedal_length <= 4.95
yes
versicolor

Slide Ref: Principles and Techniques of Data Science, UC Berkeley


Example: Using Petal Data Only
Is petal_width < 0.75 and
petal_length < 2?
no yes
setosa
Is petal_width >= 1.75

yes no

virginica Is pedal_width <= 1.55 and


pedal_length <= 4.95
no yes
Is petal_width <= 1.65 or versicolor
petal_length >= 4.95

Slide Ref: Principles and Techniques of Data Science, UC Berkeley


Example: Using Petal Data Only
Is petal_width < 0.75 and
petal_length < 2?
no yes
setosa
Is petal_width >= 1.75

yes no

virginica Is pedal_width <= 1.55 and


pedal_length <= 4.95
no yes
Is petal_width <= 1.65 or versicolor
petal_length >= 4.95
yes
virginica

Slide Ref: Principles and Techniques of Data Science, UC Berkeley


Example: Using Petal Data Only
Is petal_width < 0.75 and
petal_length < 2?
no yes
setosa
Is petal_width >= 1.75

yes no

virginica Is pedal_width <= 1.55 and


pedal_length <= 4.95
no yes
Is petal_width <= 1.65 or versicolor
petal_length >= 4.95
no yes
Is petal_length <= virginica
5.55

Slide Ref: Principles and Techniques of Data Science, UC Berkeley


Example: Using Petal Data Only
Is petal_width < 0.75 and
petal_length < 2?
no yes
setosa
Is petal_width >= 1.75

yes no

virginica Is pedal_width <= 1.55 and


pedal_length <= 4.95
no yes
Is petal_width <= 1.65 or versicolor
petal_length >= 4.95
no yes
Is petal_length <= virginica
5.55
no yes
virginica versicolor Slide Ref: Principles and Techniques of Data Science, UC Berkeley
Example: Using Petal Data Only
How accurate is our decision tree model on the training data?

Is this good or bad?

Slide Ref: Principles and Techniques of Data Science, UC Berkeley


Example: Using Petal Data Only
How accurate is our decision tree model on the training data?
● It seems like it gets every point correct.

Is this good or bad?


● I’d argue bad.
● Seems likely to result in overfitting!
● Will discuss overfitting more later.

First, let’s see how we can build decision trees for classification using scikit-learn.

Slide Ref: Principles and Techniques of Data Science, UC Berkeley


Visualizing Decision Tree Models

In each box, we see:


• The rule.
• The gini impurity (chance that a sample
would be misclassified if randomly assigned
at this point).
• The number of samples still unclassified.
• The number of samples in each class still
unclassified.
• The most likely class.
Slide Ref: Principles and Techniques of Data Science, UC Berkeley
Understanding Our Decision Tree

There is one terminal decision point where


there is more than one possible right answer.

The model was unable to come up with a


decision rule to resolve these last 3 samples.

Let’s see why using the query method of the


dataframe class.

Slide Ref: Principles and Techniques of Data Science, UC Berkeley


Understanding Our Decision Tree

There is one terminal decision point where


there is more than one possible right answer.
• In the original data set, there was a
versicolor iris with the same petal
measurements as two virginicas.

Slide Ref: Principles and Techniques of Data Science, UC Berkeley


Visualizing Decision Tree Models
Plotting the decision boundaries for our model:
● Decision tree has nonlinear boundary

Slide Ref: Principles and Techniques of Data Science, UC Berkeley


Measuring the Performance of Our Model
Running the code below, we see that we only get 99.3% accuracy.

To understand why, let’s look back at our decision tree model.

Slide Ref: Principles and Techniques of Data Science, UC Berkeley


Overfitting and Decision Trees
scikit-learn makes it easy to generate decision trees.

Perfect accuracy on the training data, EXCEPT when there are samples from
different categories with the exact same features.
● That is, if the versicolor above had a petal_length of 4.800001, we’d have
100% training accuracy.

-> This tendency for perfect accuracy should give us concern about overfitting.
(We will go over this later!)
Slide Ref: Principles and Techniques of Data Science, UC Berkeley
Multidimensional Decision Trees
Naturally, we can include even more features. For example, if we want to use
the petal AND sepal measurements, we simply train the decision tree on all four
columns of the data.

The resulting model gets:


● 100% accuracy on the training set (no overlapping data points).
● 95% accuracy on the test set.

Slide Ref: Principles and Techniques of Data Science, UC Berkeley


Model 2D-150 vs. Model 4D-110 Tree Visualization

What is different about these two models?


Slide Ref: Principles and Techniques of Data Science, UC Berkeley
Model 2D-150 vs. Model 4D-110 Tree Visualization
Models are quite similar:
● Model 4D-110 uses only 110 samples.
● The decision rules are nearly identical,
except that Model4D-110 uses the
sepal_width exactly once to resolve
the case that we couldn’t resolve with
petal_length and petal_width.

Model 4D-110 seems marginally better, but


both got only 95% accuracy on test set.
● Need more data to know for sure.

Slide Ref: Principles and Techniques of Data Science, UC Berkeley


Decision Tree Generation
Let’s discuss how decision trees are created from data.

Traditional decision tree generation algorithm:


● All of the data starts in the root node.
● Repeat until every node is either pure or unsplittable:
○ Pick the best feature x and best split value β, e.g. x = petal_length, β = 2.
○ Split data into two nodes, one where x < β, and one where x ≥ β.

Notes: A node that has only one type is called a “pure” node. A node that has
duplicate data that cannot be split is called “unsplittable”.

Slide Ref: Principles and Techniques of Data Science, UC Berkeley


Defining a Best Feature
Question: Which feature and split value is best?
● Equivalently: Which horizontal or vertical line do we want to draw?

????
[50, 50, 50]
No Yes

???? ????
[??, ??, ??] [??, ??, ??]

Slide Ref: Principles and Techniques of Data Science, UC Berkeley


Defining a Best Feature
Question: Which feature and split value is best?
● Equivalently: Which horizontal or vertical line do we want to draw?

width > 1.5


[50, 50, 50]
No Yes

???? ????
[50, 46, 3] [0, 4, 47]

Is this
good?
Slide Ref: Principles and Techniques of Data Science, UC Berkeley
Defining a Best Feature
Question: Which feature and split value is best?
● Equivalently: Which horizontal or vertical line do we want to draw?

width > 1.5


[50, 50, 50]
No Yes

???? ????
[50, 46, 3] [0, 4, 47]

Is this good? It does help,


but we could do better!
Slide Ref: Principles and Techniques of Data Science, UC Berkeley
Defining a Best Feature
Question: Which feature and split value is best?
● Equivalently: Which horizontal or vertical line do we want to draw?

Better than before??


length > 4
[50, 50, 50]
No Yes

???? ????
[50, 9, 0] [0, 41, 50]

Slide Ref: Principles and Techniques of Data Science, UC Berkeley


Defining a Best Feature
Question: Which feature and split value is best?
● Equivalently: Which horizontal or vertical line do we want to draw?

width > 0.5


[50, 50, 50]
No Yes

???? ????
[2, 50, 50] [48, 0, 0]

Even better?

Slide Ref: Principles and Techniques of Data Science, UC Berkeley


Defining a Best Feature
Question: Which feature and split value is best?
● Equivalently: Which horizontal or vertical line do we want to draw?

We need some sort of rigorous definition for a good split.


width > 0.8
[50, 50, 50]
No Yes

???? ????
[50, 0, 0] [0, 50, 50]

Best?

Slide Ref: Principles and Techniques of Data Science, UC Berkeley


Node Entropy
Let 𝑝𝐶 be the proportion of data points in a node with label C.

For example, for the node at the top of the


decision tree, 𝑝0 = 34/110 = 0.31, S=1.58
𝑝1 = 36/110 = 0.33, and 𝑝2 = 40/110 = 0.36.

Define the entropy S of a node as:

For example, S for the top node is:


−0.31 log20.31 − 0.33 log20.33 − 0.36 log20.36 = 0.52 + 0.53 + 0.53 = 1.58
Slide Ref: Principles and Techniques of Data Science, UC Berkeley
Test Your Understanding
What is the entropy of the node on the left with [31, 4, 1] in each class?
● 𝑝0 = 31/36 = 0.86, 𝑝1 = 4/36 = 0.11, and 𝑝2 = 1/36 = 0.028
● S = −0.86 log20.86
− 0.11 log20.11
− 0.028 log20.028 = 0.68
S=1.58

Define the entropy S of a node as: S=0.68

Can think of entropy as how unpredictable a node is. Low entropy means
more predictable. High entropy means more unpredictable.
Slide Ref: Principles and Techniques of Data Science, UC Berkeley
Exploring Entropy
Observations about entropy:
● A node where all data are part of the
same class has zero entropy.
−1 log2 1 = 0 S=1.58
● A node where data are evenly split
between two classes has entropy 1.
−0.5 log2 0.5 − 0.5 log2 0.5= 1 S=0.68
● A node where data are evenly split
between 3 classes has entropy 1.58.
3 × (−0.33 log2 0.33) = 1.58
● A node where data are evenly split into
C classes has entropy log2C.
C × (−1/C log2 1/C) = −log2 1/C = log2 C
Slide Ref: Principles and Techniques of Data Science, UC Berkeley
Weighted Entropy as a Loss Function
We can use Weighted Entropy as a loss function in helping us decide which split
to take.

Suppose a given split results in two nodes X and Y with N1 and N2 total samples
each. The loss of that split is given by:

Slide Ref: Principles and Techniques of Data Science, UC Berkeley


Defining a Best Feature
Split choice #1: width > 1.5. Compute entropy of child nodes:
● entropy([50, 46, 3]) = 1.16
● entropy([4, 47]) = 0.4
● Weighted average: 99/150 × 1.16 + 51/150 × 0.4 = 0.9

S=1.58, Loss=0.9
width > 1.5
[50, 50, 50]
No Yes
Not so good
???? ????
[50, 46, 3] [0, 4, 47]
S=1.16 S=0.4

Slide Ref: Principles and Techniques of Data Science, UC Berkeley


Defining a Best Feature
Split choice #2: length > 4. Compute entropy of child nodes:
● entropy([50, 9]) = 0.62
● entropy([41, 50]) = 0.99
● Weighted Average: 0.84: Better than split choice #1!

S=1.58, Loss=0.84
length > 4
[50, 50, 50]
No Yes

???? ????
[50, 9, 0] [0, 41, 50]
S=0.62 S=0.99
Better?

Slide Ref: Principles and Techniques of Data Science, UC Berkeley


Defining a Best Feature
Split choice #3: width > 0.5. Compute entropy of child nodes:
● entropy([2, 50, 50]) = 1.12
● entropy([48]) = 0
● Weighted average: 0.76: Lower than split choice #2!

S=1.58, Loss = 0.76


width > 0.5
[50, 50, 50]
No Yes

???? ????
[2, 50, 50] [48, 0, 0]
Even better? S=1.12 S=0

Slide Ref: Principles and Techniques of Data Science, UC Berkeley


Defining a Best Feature
Split choice #4: width > 0.9. Compute entropy of child nodes:
● entropy([50, 50]) = 1
● entropy([50]) = 0
● Weighted average: 0.66: Lower than split choice #3!

S=1.58, Loss=0.66
width > 0.8
[50, 50, 50]
No Yes

????
Best? [50, 0, 0] [0, 50, 50]
S=0 S=1

Slide Ref: Principles and Techniques of Data Science, UC Berkeley


Decision Tree Generation
Traditional decision tree generation algorithm:
● All of the data starts in the root node.
● Repeat until every node is either pure or unsplittable:
○ Pick the best feature x and split value β such that the loss of the resulting
split is minimized, e.g. x = petal_width, β = 0.8 has loss 0.66.
○ Split data into two nodes, one where x < β, and one where x ≥ β.

Notes: A node that has only one type is called a “pure” node. A node that has
duplicate data that cannot be split is called “unsplittable”.

Let’s now turn our attention to avoiding overfitting.

Slide Ref: Principles and Techniques of Data Science, UC Berkeley


Summary
• Classification
• k-nearest neighbors Algorithms
• Decision Trees
• Building Decision Trees
• Entropy and Defining a Best Feature
Next
• We will revisit the Decision Tree example to learn more about
• Overfitting
• Random Decision Trees
• Regularization
References
Data Science for Business: What You Need to Know about Data Mining and Data-Analytic Thinking by
Foster Provost and Tom Fawcett

Introduction to Machine Learning with Python, a Guide for Data Scientists by Andreas C. Müller &
Sarah Guido

You might also like