Classification, Attribute Selection, Classifiers- Decision Tree, ID3,C4.5,Navie Bayes, Linear Regression KNN

438 views 56 slides Apr 25, 2024
Slide 1
Slide 1 of 56
Slide 1
1
Slide 2
2
Slide 3
3
Slide 4
4
Slide 5
5
Slide 6
6
Slide 7
7
Slide 8
8
Slide 9
9
Slide 10
10
Slide 11
11
Slide 12
12
Slide 13
13
Slide 14
14
Slide 15
15
Slide 16
16
Slide 17
17
Slide 18
18
Slide 19
19
Slide 20
20
Slide 21
21
Slide 22
22
Slide 23
23
Slide 24
24
Slide 25
25
Slide 26
26
Slide 27
27
Slide 28
28
Slide 29
29
Slide 30
30
Slide 31
31
Slide 32
32
Slide 33
33
Slide 34
34
Slide 35
35
Slide 36
36
Slide 37
37
Slide 38
38
Slide 39
39
Slide 40
40
Slide 41
41
Slide 42
42
Slide 43
43
Slide 44
44
Slide 45
45
Slide 46
46
Slide 47
47
Slide 48
48
Slide 49
49
Slide 50
50
Slide 51
51
Slide 52
52
Slide 53
53
Slide 54
54
Slide 55
55
Slide 56
56

About This Presentation

Classification


Slide Content

Sanjivani Rural Education Society’s
Sanjivani College of Engineering, Kopargaon-423 603
(An Autonomous Institute, Affiliated to Savitribai Phule Pune University, Pune)
NACC ‘A’ Grade Accredited, ISO 9001:2015 Certified
Department of Computer Engineering
(NBA Accredited)
Prof. S. A. Shivarkar
Assistant Professor
Contact No.8275032712
[email protected]
Subject-Data Mining and Warehousing (CO314)
Unit –VI:Classification

Content
Introduction, classification requirements, methods of supervised learning
Decision trees-attribute selection measures (info gain, Gini ratio, Gini
index), scalable decision tree techniques, rule extraction from decision tree,
Naïve bayesianClassification, Rule based classification
Associative Classification, Lazy Learners-k-Nearest-Multiclass Classification,
Metrics for Evaluating Classifier Evaluating the Accuracy of a Classifier
Regression, Introduction to Ensemble Methods.

Supervised vs. Unsupervised Learning
Supervised learning (classification)
Supervision: The training data (observations, measurements, etc.) are
accompanied by labelsindicating the class of the observations
New data is classified based on the training set
Unsupervised learning(clustering)
The class labels of training data is unknown
Given a set of measurements, observations, etc. with the aim of
establishing the existence of classes or clusters in the data

Prediction Problems: Classification vs. Numeric Prediction
Classification
predicts categorical class labels (discrete or nominal)
classifies data (constructs a model) based on the training set and the
values (class labels) in a classifying attribute and uses it in classifying new
data
Numeric Prediction
models continuous-valued functions, i.e., predicts unknown or missing
values
Typical applications
Credit/loan approval:
Medical diagnosis: if a tumor is cancerous or benign
Fraud detection: if a transaction is fraudulent
Web page categorization: which category it is

Classification—A Two-Step Process
Model construction: describing a set of predetermined classes
Each tuple/sample is assumed to belong to a predefined class, as determined by the class
label attribute
The set of tuples used for model construction is training set
The model is represented as classification rules, decision trees, or mathematical formulae
Model usage: for classifying future or unknown objects
Estimate accuracyof the model
The known label of test sample is compared with the classified result from the model
Accuracyrate is the percentage of test set samples that are correctly classified by the
model
Test setis independent of training set (otherwise overfitting)
If the accuracy is acceptable, use the model to classify new data
Note: If the test set is used to select models, it is called validation (test) set

Step 1: Model Construction

Step 2: Model Usage

Issues: Data Preparation
Data cleaning
Preprocess data in order to reduce noise and handle
missing values
Relevance analysis (feature selection)
Remove the irrelevant or redundant attributes
Data transformation
Generalize and/or normalize data

Issues: Evaluating Classification Methods
Accuracy
classifier accuracy: predicting class label
predictor accuracy: guessing value of predicted attributes
Speed
time to construct the model (training time)
time to use the model (classification/prediction time)
Robustness: handling noise and missing values
Scalability: efficiency in disk-resident databases
Interpretability
understanding and insight provided by the model
Other measures, e.g., goodness of rules, such as decision tree size or compactness of classification rules

Issues: Evaluating Classification Methods: Accuracy
Accuracy simply measureshow often the classifier correctly predicts.
We can define accuracy as the ratio of the number of correct predictions and the total number of
predictions.
For binary classification (only two class labels) we use TP and TN.

Accuracy: Confusion Matrix

Decision Tree Induction: Training Dataset

Decision Tree Induction: Training Dataset
age?
overcast
student? credit rating?
<=30
>40
no yes
yes
yes
31..40
fairexcellent
yesno
Training data set: Buys_computer
The data set follows an example of
Quinlan’s ID3 (Playing Tennis)
Resulting tree:

Algorithm for Decision Tree Induction
Basic algorithm (a greedy algorithm)
Tree is constructed in a top-down recursive divide-and-conquer manner
At start, all the training examples are at the root
Attributes are categorical (if continuous-valued, they are discretized in
advance)
Examples are partitioned recursively based on selected attributes
Test attributes are selected on the basis of a heuristic or statistical measure
(e.g., information gain)
Conditions for stopping partitioning
All samples for a given node belong to the same class
There are no remaining attributes for further partitioning –majority voting
is employed for classifying the leaf
There are no samples left

Brief Review of Entropy

m = 2

Brief Review of Entropy

m = 2

Attribute Selection Measure: Information Gain (ID3)
Select the attribute with the highest information gain
Let p
ibe the probability that an arbitrary tuple in D belongs to class C
i, estimated
by |C
i, D|/|D|
Expected information(entropy) needed to classify a tuple in D:
Informationneeded (after using A to split D into v partitions) to classify D:
Information gainedby branching on attribute A)(log)(
2
1
i
m
i
i ppDInfo

 )(
||
||
)(
1
j
v
j
j
A DInfo
D
D
DInfo 
 (D)InfoInfo(D)Gain(A)
A

Decision Tree Induction: Training Dataset Example 1

Attribute Selection: Information Gain

Decision Tree Induction: Training Dataset Example 2

Computing Information-Gain for Continuous-Value Attributes
Let attribute A be a continuous-valued attribute
Must determine the best split pointfor A
Sort the value A in increasing order
Typically, the midpoint between each pair of adjacent values is considered as a
possible split point
(a
i+a
i+1)/2 is the midpoint between the values of a
iand a
i+1
The point with the minimum expected information requirementfor A is
selected as the split-point for A
Split:
D1 is the set of tuples in D satisfying A ≤ split-point, and D2 is the set of tuples
in D satisfying A > split-point

Gain Ratio for Attribute Selection (C4.5)
Information gain measure is biased towards attributes with a
large number of values
C4.5 (a successor of ID3) uses gain ratio to overcome the
problem (normalization to information gain)
GainRatio(A) = Gain(A)/SplitInfo(A)
Ex.
gain_ratio(income) = 0.029/1.557 = 0.019
The attribute with the maximum gain ratio is selected as the
splitting attribute)
||
||
(log
||
||
)(
2
1 D
D
D
D
DSplitInfo
j
v
j
j
A 

Attribute Selection (C4.5): Example 1
Department AgeSalary Count Status
sales 31…35 46…50 30 senior
sales 26…30 26…30 40 junior
sales 31…35 31…35 40 junior
systems 21…25 46…50 20 junior
systems 21…31 66…70 5 senior
systems 26…30 46…50 3 junior
systems 41…45 66…70 3 senior
marketing 36…40 46…50 10 senior
marketing 31…35 41…45 4 junior
secretary 46…50 36…40 4 senior
secretary 26…30 26…30 6 junior
Training
data
from an
employee

Gini Index (CART, IBM IntelligentMiner)
If a data set D contains examples from nclasses, giniindex, gini(D) is defined as
where p
jis the relative frequency of class jin D
If a data set Dis split on A into two subsets D
1and D
2, the giniindex gini(D) is
defined as
Reduction in Impurity:
The attribute provides the smallest gini
split(D) (or the largest reduction in impurity)
is chosen to split the node (need to enumerate all the possible splitting points for
each attribute)


n
j
p
j
Dgini
1
2
1)( )(
||
||
)(
||
||
)(
2
2
1
1
Dgini
D
D
Dgini
D
D
Dgini
A
 )()()( DginiDginiAgini
A


Gini Index: Example 1

Computation of Gini Index
Ex. D has 9 tuples in buys_computer= “yes” and 5 in “no”
Suppose the attribute income partitions D into 10 in D
1: {low, medium} and 4 in D
2
Gini
{low,high}is 0.458; Gini
{medium,high}is 0.450. Thus, split on the {low,medium} (and
{high}) since it has the lowest Gini index
All attributes are assumed continuous-valued
May need other tools, e.g., clustering, to get the possible split values
Can be modified for categorical attributes459.0
14
5
14
9
1)(
22












Dgini )(
14
4
)(
14
10
)(
21},{ DGiniDGiniDgini
mediumlowincome 












Comparing Attribute Selection Measures
The three measures, in general, return good results but
Information gain:
biased towards multivalued attributes
Gain ratio:
tends to prefer unbalanced splits in which one partition is much smaller than the
others
Gini index:
biased to multivalued attributes
has difficulty when # of classes is large
tends to favor tests that result in equal-sized partitions and purity in both
partitions

Other Attribute Selection Measures
CHAID: a popular decision tree algorithm, measure based on χ
2
test for independence
C-SEP: performs better than info. gain and giniindex in certain cases
G-statistic: has a close approximation to χ
2
distribution
MDL (Minimal Description Length) principle(i.e., the simplest solution is preferred):
The best tree as the one that requires the fewest # of bits to both (1) encode the tree,
and (2) encode the exceptions to the tree
Multivariate splits (partition based on multiple variable combinations)
CART: finds multivariate splits based on a linear comb. of attrs.
Which attribute selection measure is the best?
Most give good results, none is significantly superior than others

Overfitting: An induced tree may overfitthe training data
Model tries to accommodate all data points.
Too many branches, some may reflect anomalies due to noise or outliers
Poor accuracy for unseen samples
A solution to avoid overfitting is using a linear algorithm if we have linear data or
using the parameters like the maximal depth if we are using decision trees.
Two approaches to avoid overfitting
Prepruning: Halt tree construction early̵do not split a node if this would result in the goodness
measure falling below a threshold
Difficult to choose an appropriate threshold
Postpruning: Remove branchesfrom a “fully grown” tree—get a sequence of progressively
pruned trees
Use a set of data different from the training data to decide which is the “best pruned tree”
Overfitting and Tree Pruning

Underfitting: An induced tree may overfitthe training data
Model tries to accommodate very few data points e.g. 10% dataset for training and 90 % for
testing.
It has very less accuracy.
An underfitmodel’s are inaccurate, especially when applied to new,
unseen examples.
Techniques to Reduce Underfitting
Increase model complexity.
Increase the number of features, performingfeature engineering.
Remove noise from the data.
Increase the number ofepochsor increase the duration of training to get better results.
Overfitting and Tree Pruning

Overfitting and Underfitting
Reasons for Overfitting:
1.High variance and low bias.
2.The model is too complex.
3.The size of the training data.
Reasons forUnderfitting
1.If model not capable to represent the complexities in the data.
2.The size of the training dataset used is not enough.
3.Features are not scaled.

Overfitting and Underfitting

Enhancements to Basic Decision Tree Induction
Allow for continuous-valued attributes
Dynamically define new discrete-valued attributes that
partition the continuous attribute value into a discrete set of
intervals
Handle missing attribute values
Assign the most common value of the attribute
Assign probability to each of the possible values
Attribute construction
Create new attributes based on existing ones that are
sparsely represented
This reduces fragmentation, repetition, and replication

Bayesian Classification: Why?
A statistical classifier: performs probabilistic prediction, i.e.,predicts class
membership probabilities
Foundation:Based on Bayes’ Theorem.
Performance:A simple Bayesian classifier, naïve Bayesian classifier, has comparable
performance with decision tree and selected neural network classifiers
Incremental: Each training example can incrementally increase/decrease the
probability that a hypothesis is correct —prior knowledge can be combined with
observed data
Standard: Even when Bayesian methods are computationally intractable, they can
provide a standard of optimal decision making against which other methods can be
measured

Bayes’ Theorem: Basics
Total probability Theorem:
Bayes’ Theorem:
Let Xbe a data sample (“evidence”): class label is unknown
Let H be a hypothesisthat X belongs to class C
Classification is to determine P(H|X), (i.e., posteriori probability): the probability that the
hypothesis holds given the observed data sample X
P(H) (prior probability): the initial probability
E.g.,Xwill buy computer, regardless of age, income, …
P(X): probability that sample data is observed
P(X|H) (likelihood): the probability of observing the sample X, given that the hypothesis holds
E.g.,Given thatXwill buy computer, the prob. that X is 31..40, medium income)()
1
|()(
i
AP
M
i
i
ABPBP 

 )(/)()|(
)(
)()|(
)|( XX
X
X
X PHPHP
P
HPHP
HP 

Prediction Based on Bayes’ Theorem
Given training dataX, posteriori probability of a hypothesis H,
P(H|X), follows the Bayes’ theorem
Informally, this can be viewed as
posteriori = likelihood x prior/evidence
Predicts Xbelongs to C
iiffthe probability P(C
i|X) is the highest
among all the P(C
k|X) for all the kclasses
Practical difficulty: It requires initial knowledge of many
probabilities, involving significant computational cost)(/)()|(
)(
)()|(
)|( XX
X
X
X PHPHP
P
HPHP
HP 

Classification Is to Derive the Maximum Posteriori
Let D be a training set of tuples and their associated class labels, and each tuple is
represented by an n-D attribute vector X= (x
1, x
2, …, x
n)
Suppose there are mclasses C
1, C
2, …, C
m.
Classification is to derive the maximum posteriori, i.e., the maximal P(C
i|X)
This can be derived from Bayes’ theorem
Since P(X) is constant for all classes, only
needs to be maximized)(
)()|(
)|(
X
X
X
P
i
CP
i
CP
i
CP  )()|()|(
i
CP
i
CP
i
CP XX

Naïve Bayes Classifier
A simplified assumption: attributes are conditionally independent (i.e., no
dependence relation between attributes):
This greatly reduces the computation cost: Only counts the class distribution
If A
kis categorical, P(x
k|C
i) is the # of tuples in C
ihaving value x
kfor A
kdivided by
|C
i, D| (# of tuples of C
iin D)
If A
kis continous-valued, P(x
k|C
i) is usually computed based on Gaussian
distribution with a mean μand standard deviation σ
and P(x
k|C
i) is )|(...)|()|(
1
)|()|(
21
CixPCixPCixP
n
k
CixPCi
P
nk


X 2
2
2
)(
2
1
),,(







x
exg ),,()|(
iiCCkxgCi
P X

Naïve Bayes Classifier
Class:
C1:buys_computer = ‘yes’
C2:buys_computer = ‘no’
Data to be classified:
X = (age <=30,
Income = medium,
Student = yes
Credit_rating= Fair)

Model Evaluation
Evaluation metrics: How can we measure accuracy? Other
metrics to consider?
Use validation test setof class-labeled tuples instead of
training set when assessing accuracy
Methods for estimating a classifier’s accuracy:
Holdout method, random subsampling
Cross-validation
Bootstrap
Comparing classifiers:
Confidence intervals
Cost-benefit analysis and ROC Curves

Model Evaluation Metrics: Confusion Metrics
Actual class\Predicted
class
buy_computer
= yes
buy_computer
= no
Total
buy_computer = yes 6954 46 7000
buy_computer = no 412 2588 3000
Total 7366 2634 10000
Givenmclasses, an entry, CM
i,jin a confusion matrixindicates
# of tuples in class ithat were labeled by the classifier as class j
May have extra rows/columns to provide totals
Confusion Matrix:
Actual class\Predicted class C
1 ¬ C
1
C
1 True Positives (TP)False Negatives (FN)
¬ C
1 False Positives (FP)True Negatives (TN)
Example of Confusion Matrix:

Model Evaluation Metrics: Accuracy, Error Rate, Sensitivity and Specificity
Classifier Accuracy, or
recognition rate: percentage of
test set tuples that are correctly
classified
Accuracy = (TP + TN)/All
Error rate:1 –accuracy, or
Error rate = (FP + FN)/All
Class Imbalance Problem:
One class may be rare, e.g.
fraud, or HIV-positive
Significant majority of the
negative classand minority of
the positive class
Sensitivity: True Positive
recognition rate
Sensitivity = TP/P
Specificity: True Negative
recognition rate
Specificity = TN/N
A\PC¬C
CTPFNP
¬CFPTNN
P’N’All

Model Evaluation Metrics: Precision and Recall, and F-measures
Precision: exactness –what % of tuples that the classifier
labeled as positive are actually positive
Recall: completeness –what % of positive tuples did the
classifier label as positive?
Perfect score is 1.0
Inverse relationship between precision & recall
Fmeasure (F
1orF-score): harmonic mean of precision and
recall,
F
ß: weighted measure of precision and recall
assigns ß times as much weight to recall as to precision

Lazy vs. Eager Learning
Lazy vs. eager learning
Lazy learning(e.g., instance-based learning): Simply
stores training data (or only minor processing) and
waits until it is given a test tuple
Eager learning(the above discussed methods): Given
a set of training tuples, constructs a classification model
before receiving new (e.g., test) data to classify
Lazy: less time in training but more time in predicting
Accuracy
Lazy method effectively uses a richer hypothesis space
since it uses many local linear functions to form an
implicit global approximation to the target function
Eager: must commit to a single hypothesis that covers
the entire instance space

Lazy Learner: Instance-Based Methods
Instance-based learning:
Store training examples and delay the processing (“lazy
evaluation”) until a new instance must be classified
Typical approaches
k-nearest neighbor approach
Instances represented as points in a Euclidean space.
Locally weighted regression
Constructs local approximation
Case-based reasoning
Uses symbolic representations and knowledge-based
inference

The k-Nearest Neighbor Algorithm
All instances correspond to points in the n-D space
The nearest neighbor are defined in terms of Euclidean distance, dist(X
1, X
2)
Target function could be discrete-or real-valued
For discrete-valued, k-NN returns the most common value among the ktraining
examples nearest tox
q
Vonoroidiagram: the decision surface induced by 1-NN for a typical set of
training examples
.
_
_
x
q
+
__
+
_
_
+
.
.
.
. .

Step #1 -Assign a value toK.
Step #2 -Calculate the distance between the new data entry and all
other existing data entries. Arrange them in ascending order.
Step #3 -Find theKnearest neighbors to the new entry based on the
calculated distances.
Step #4 -Assign the new data entry to the majority class in the
nearest neighbors.
The k-Nearest Neighbor Algorithm Steps

Type of Distances used in Machine Learning algorithm
Euclidean distance :√(X₂-X₁)²+(Y₂-Y₁)²
Manhattan Distance
The Manhattan distance as the sum of absolute differences
Lets calculate Distance between { 2, 3 } from { 3, 5 }
|2–3|+|3–5| = |-1| + |-2| = 1+2 = 3
|x1 —x2| + |y1 —y2|

For given data test tuple Brightness=20, saturation=35, Class?
Assume K=5, use Euclidean distance
BRIGHTNESS SATURATION CLASS
40 20 Red
50 50 Blue
60 90 Blue
10 25 Red
70 70 Blue
60 10 Red
25 80 Blue
Euclidean distance :√(X₂-X₁)²+(Y₂-Y₁)²
The k-Nearest Neighbor Algorithm

What Is Prediction?
(Numerical) prediction is similar to classification
construct a model
use model to predict continuous or ordered value for a given input
Prediction is different from classification
Classification refers to predict categorical class label
Prediction models continuous-valued functions
Major method for prediction: regression
model the relationship between one or more independentor
predictorvariables and a dependentor responsevariable
Regression analysis
Linear and multiple regression
Non-linear regression
Other regression methods: generalized linear model, Poisson
regression, log-linear models, regression trees

Linear Regression
Linear regression: involves a response variable y and a single
predictor variable x
y = w
0+ w
1x
where w
0(y-intercept) and w
1(slope) are regression coefficients
Method of least squares: estimates the best-fitting straight line
Multiple linear regression: involves more than one predictor variable
Training data is of the form (X
1, y
1), (X
2, y
2),…, (X
|D|, y
|D|)
Ex. For 2-D data, we may have: y = w
0+ w
1x
1+ w
2x
2
Solvable by extension of least square method or using SAS, S-Plus
Many nonlinear functions can be transformed into the above






||
1
2
||
1
)(
))((
1
D
i
i
D
i
ii
xx
yyxx
w xwyw
10


Linear Regression
Linear regression: Linear regression shows the linear relationship
between two variables.
Y= a + bX
Where Y: Dependent variable
X : Independent variable
b: slope
a and b calculated as:

Linear Regression Example
Y = a + bx
y = 1.5 + 0.95x

Linear Regression Example

Ensemble Methods: Increasing the Accuracy
Ensemble methods
Use a combination of models to increase accuracy
Combine a series of k learned models, M
1, M
2, …,
M
k, with the aim of creating an improved model
M*
Popular ensemble methods
Bagging: averaging the prediction over a collection
of classifiers
Boosting: weighted vote with a collection of
classifiers
Ensemble: combining a set of heterogeneous
classifiers

DEPARTMENT OF COMPUTER ENGINEERING, Sanjivani COE, Kopargaon 56
Reference
Han, Jiawei Kamber, Micheline Pei and Jian, “Data Mining: Concepts and
Techniques”,Elsevier Publishers, ISBN:9780123814791, 9780123814807.
https://onlinecourses.nptel.ac.in/noc24_cs22
https://medium.com/analytics-vidhya/type-of-distances-used-in-machine-
learning-algorithm-c873467140de
https://www.freecodecamp.org/news/k-nearest-neighbors-algorithm-
classifiers-and-model-example/
Tags