0% found this document useful (0 votes)
211 views81 pages

Classification

The document provides an introduction to classification, describing classification as predicting categorical labels using a model constructed from a training set, in contrast to prediction which models continuous values; it then outlines key concepts in classification including supervised vs unsupervised learning, the two-step classification process of model construction and usage, and various classification algorithms such as decision trees, Bayesian classification, and support vector machines.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
211 views81 pages

Classification

The document provides an introduction to classification, describing classification as predicting categorical labels using a model constructed from a training set, in contrast to prediction which models continuous values; it then outlines key concepts in classification including supervised vs unsupervised learning, the two-step classification process of model construction and usage, and various classification algorithms such as decision trees, Bayesian classification, and support vector machines.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
You are on page 1/ 81

Introduction to

Classification
Contents
• Classification vs. Prediction
• Classification—A Two-Step Process
• Supervised vs. Unsupervised Learning
• Decision Tree Induction
• Attribute Selection Measures
• Bayesian Classification
• Rule Based Classification
• Classification by Back Propagation
• Support Vector Machines
• Associative Classification
• Lazy Learners – k-Nearest Neighbor Classifiers
• Prediction
• Accuracy and Error Measures
Classification vs. 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
• Prediction
– models continuous-valued functions, i.e., predicts
unknown or missing values
• Typical applications
– Credit approval
– Target marketing
– Medical diagnosis
Classfication vs. Prediction
• Classification predicts categorical (discrete,
unordered) labels.
– Ex : categorize bank loans as safe or risky.
– Data analysis task is classification where a model or
classifier is constructed to predict categorical labels
such as “safe” , “risky”, ”yes”, ”no” “treatment A” etc.
• Prediction models continuous-valued functions
– Ex : predict the expenditures in dollars of potential
customers on computer equipment given their income
and occupation.
– The model is a “predictor”
– Regression Analysis is typically used for prediction
Classification—A Two-Step
Process
• Model construction(Learning Step) : 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 (Classification) : for classifying future or unknown objects
– Estimate accuracy of the model
• The known label of test sample is compared with the classified
result from the model
• Accuracy rate is the percentage of test set samples that are
correctly classified by the model
• Test set is independent of training set, otherwise over-fitting will
occur
– If the accuracy is acceptable, use the model to classify data tuples
whose class labels are not known
Training Set
• Training Set :

- A tuple X is represented by an n-dimensional attribute vector X =


(x1,x2,…xn) depicting n measurements made on the tuple from n database
attributes A1, A2, ….An .

- Each tuple X in the training set , is assumed to belong to a predefined


class as determined by another database attribute called the class label
attribute.

- Since the class label of each training tuple is provided this step is also
known as supervised learning.
( Unsupervised Learning is Clustering)

- Attributes can be numerical attributes


- Attributes can be categorical
- Attribute can be distinguishing attribute called class label
Process (1): Model
Construction
Classification
Algorithms
Training
Data

NAME RANK YEARS TENURED Classifier


Mike Assistant Prof 3 no (Model)
Mary Assistant Prof 7 yes
Bill Professor 2 yes
Jim Associate Prof 7 yes IF rank = ‘professor’
Dave Assistant Prof 6 no OR years > 6
Anne Associate Prof 3 no
THEN tenured = ‘yes’
Process (2): Using the Model in
Prediction

Classifier

Testing
Data Unseen Data

(Jeff, Professor, 4)
NAME RANK YEARS TENURED
T om A ssistant P rof 2 no Tenured?
M erlisa A ssociate P rof 7 no
G eorge P rofessor 5 yes
Joseph A ssistant P rof 7 yes
Supervised vs. Unsupervised
Learning
• Supervised learning (classification)
– Supervision: The training data (observations,
measurements, etc.) are accompanied by labels
indicating 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
Preparing the data for
Classification or Prediction
• Data Cleaning – remove noisy data or missing
values
• Attribute relevance analysis - using Correlation
Analysis or Attribute subset selection to find the
reduced set of attributes
• Data transformation and reduction – using
normalization or methods involving distance
measurements , concept hierarchies or
generalization into higher concepts.
Decision Tree Induction
• In 70s and early 80s Ross Quinlan , a researcher in machine learning
developed ID3 ( Iterative Dichotomiser)
– uses entropy as measure of how informative the node is.
• C4.5 which is a benchmark to which new supervised learning algorithms are
often compared.
– Extension of ID3. accounts for unavailable values, continuous attributes
, pruning of decision trees and rule derivation
– Does not generate a binary tree
• Classification and Regression Trees (CART)
– uses gini index for determining best split
– Build binary decision tree
– Adopt a greedy ie. Non back tracking approach in which decision trees
are constructed in a top down recursive divide and conquer manner.
• Training set s recursively partitioned into smaller sub sets as the tree is
being built.
Classification by Decision Tree
Induction
• A decision tree is a flow-chart like structure
- each internal node denotes a test on an
attribute
- each branch represents an outcome of the test
- leaf node holds a class label

• Represents the concept buys_computer.


• Trees produced can be binary trees or non
binary trees
Output: A Decision Tree for
“buys_computer”
age?

<=30 overcast
31..40 >40

student? yes credit rating?

no yes excellent fair

no yes yes
Decision Tree Induction: Training
Dataset
age income student credit_rating buys_computer
<=30 high no fair no
This <=30 high no excellent no
follows an 31…40
>40
high
medium
no
no
fair
fair
yes
yes
example >40 low yes fair yes
of >40
31…40
low
low
yes excellent
yes excellent
no
yes
Quinlan’s <=30 medium no fair no
ID3 <=30
>40
low
medium
yes fair
yes fair
yes
yes
<=30 medium yes excellent yes
31…40 medium no excellent yes
31…40 high yes fair yes
>40 medium no excellent no
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)
– The splitting criterion specifies splitting attribute and split-point.
– A partition is pure if all the tuples belong to the same class
– Splitting variable A can be
• Discrete , then the outcomes of the test are the known values of A
• Continuous-valued, then the outcomes are <= split point and > split_point
• Binary , then yes and no outcomes
• Discrete-valued and binary tree has to be produced
• 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 tuples left , ie. Partition is empty
Generate_Decision_tree
• Input :
– Data partition D which is a set of training
tuples and their associated class label
– attribute list, the set of candidate attributes
– Attribute_selection_method – a procedure to
determine the splitting criterion that best
partitions the data tuples into individual
classes. The criterion consists of a splitting
attribute and the split point or splitting subset
• Output : a decision tree
Generate_Decision_tree : Method
Create a node N;
If tuples in D are all of the same class C then
Return N as leaf node labeled with the class C;
If attribute_list is empty then
return N as a leaf node labeled with the majority class in D;
Apply Attribute_selection_method(D,attribute list) to find the best splitting criterion
Label node N with splitting_criterion;
If splitting_attribute is discrete_valued and multiway splits are allowed then
attribute_list <- attribute_list – splitting_attribute
For each outcome j of the splitting criterion
let Dj be the set of data tuples in D satisfying outcome j;
if Dj is empty then
attach a leaf labeled with the majority class in D to node N;
else
attach the node returned by Generate_decision_tree(Dj, attribute_list ) to node N;
End For
Return N;
Pros and Cons of Decision Tree
Classification
• Advantages
– Construction of Decision tree does not require any domain
knowledge or parameter setting and so is appropriate for
exploratory knowledge discovery
– Can handle high dimensional data
– are able to generate understandable rules
– able to handle both numerical and categorical attributes
– indicate which fields are important for prediction or classification

• Disadvantages
– Error prone where training class is small
– Can be computationally expensive.
Attribute Selection Measure
• Is a heuristic for selecting the splitting criterion
that best seperates a given data partition D
• Ideally each partition has to be pure.
• Information Gain
– Attribute with highest information gain is chosen as
splitting attribute for node N
– Attribute minimizes the information required to
classify the tuples in the resulting partition
– A log function to the base 2 is used because
information is encoded in bits
Attribute Selection Measure:
Information Gain (ID3/C4.5)
 Select the attribute with the highest information gain
 Let pi be the probability that an arbitrary tuple in D
belongs to class Ci, estimated by |Ci, D|/|D|
 Expected information (entropy) needed to classify a tuple
in D: m
Info( D)   pi log 2 ( pi )
i 1

 Information needed (after using A to split D into v


partitions) to classify D: v |D |
InfoA ( D)    Info( D j )
j

j 1 | D |

 Information gained by branching on attribute A

Gain(A)  Info(D)  InfoA(D)


Attribute Selection: Information Gain
 Class P: buys_computer
= “yes” Infoage ( D) 
5
I (2,3) 
4
I (4,0)
14 14
 Class N: buys_computer 5
= “no” 
14
I (3,2)  0.694
9 9 5 5
Info( D)  I (9,5)   log 2 ( )  log 2 ( ) 0.940
14 14 14 14
5
age pi ni I(pi, ni) I (2,3) means “age <=30”
14
<=30 2 3 0.971 has 5 out of 14 samples,
31…40 4 0 0
>40 3 2 0.971 with 2 yes’es and 3 no’s.
age income student credit_rating buys_computer
<=30
<=30
high
high
no
no
fair
excellent
no
no
Hence
31…40
>40
high
medium
no
no
fair
fair
yes
yes
Gain(age)  Info( D)  Infoage ( D)  0.246
>40 low yes fair yes
>40 low yes excellent no
31…40 low yes excellent yes Similarly,
Gain(income)  0.029
<=30 medium no fair no
<=30 low yes fair yes
>40 medium yes fair yes
<=30
31…40
medium
medium
yes excellent
no excellent
yes
yes
Gain( student )  0.151
31…40
>40
high
medium
yes fair
no excellent
yes
no Gain(credit _ rating )  0.048
Computing Information-Gain for
Continuous-Value Attributes
• Let attribute A be a continuous-valued attribute

• Must determine the best split point for A


– Sort the value A in increasing order
– Typically, the midpoint between each pair of adjacent values is
considered as a possible split point
• (ai+ai+1)/2 is the midpoint between the values of ai and ai+1
– The point with the minimum expected information requirement for 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)
v | Dj | | Dj |
SplitInfo A ( D)    log 2 ( )
j 1 |D| |D|
• GainRatio(A) = Gain(A)/SplitInfo(A)
4 4 6 6 4 4
SplitInfo A ( D)    log 2 ( )   log 2 ( )   log 2 ( )  0.926
14 14 14 14 14 14

• Ex:gain_ratio(income) = 0.029/0.926 = 0.031


• The attribute with the maximum gain ratio is selected
as the splitting attribute
Gini index (CART, IBM IntelligentMiner)
• If a data set D contains examples from n classes, gini
index, gini(D) is defined as n 2
gini( D) 1  p j
j 1

where pj is the relative frequency of class j in D


• If a data set D is split on A into two subsets D1 and D2,
the gini index(D
gini(D)
)
|D1|is defined as|D2 |
gini( )  gini( )
gini A D1 D2
|D| |D|
gini( A)  gini(D)  giniA(D)
• Reduction in Impurity:
• The attribute provides the smallest ginisplit(D) (or the
largest reduction in impurity) is chosen to split the node
(need to enumerate all the possible splitting points for
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
Rule Extraction from a Decision Tree
• Rules are easier to understand than large trees
age?
• One rule is created for each path from the root to
a leaf <=30 31..40 >40

• Each attribute-value pair along a path forms a student?


yes
credit rating?

conjunction: the leaf holds the class prediction no yes excellent fair

yes
• Rules are mutually exclusive and exhaustive no yes

• Example: Rule extraction from our buys_computer decision-tree


IF age = young AND student = no THEN buys_computer = no
IF age = young AND student = yes THEN buys_computer = yes
IF age = mid-age THEN buys_computer = yes
IF age = old AND credit_rating = excellent THEN buys_computer = yes
IF age = young AND credit_rating = fair THEN buys_computer = no
Using IF-THEN Rules for
Classification
• Represent the knowledge in the form of IF-THEN rules
R: IF age = youth AND student = yes THEN buys_computer = yes
– Rule antecedent/precondition vs. rule consequent
• Assessment of a rule: coverage and accuracy
– ncovers = # of tuples covered by R
– ncorrect = # of tuples correctly classified by R
coverage(R) = ncovers /|D| /* D: training data set */
accuracy(R) = ncorrect / ncovers
• If more than one rule is triggered, need conflict resolution
– Size ordering: assign the highest priority to the triggering rules that has the
“toughest” requirement (i.e., with the most attribute test)
– Class-based ordering: decreasing order of prevalence or misclassification
cost per class
– Rule-based ordering (decision list): rules are organized into one long
Overfitting and Tree Pruning
• Overfitting: An induced tree may overfit the training data
– Too many branches, some may reflect anomalies due to noise or
outliers
– Poor accuracy for unseen samples
• 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 branches from 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”
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
Example Training Data Set
Outlook Temp Humidity Windy Class
Sunny 79 90 True No play
Sunny 56 70 False Play
Sunny 79 75 True Play
Sunny 60 90 True No play
Overcast 88 88 False No play
Overcast 63 75 True Play
Overcast 88 95 False Play
Rain 78 60 False Play
Rain 66 70 False No play
Rain 68 60 True No Play
Example Test Data Set
Outlook Temp Humidity Windy Class
Sunny 79 90 True Play
Sunny 56 70 False Play
Sunny 79 75 True No Play
Sunny 60 90 True No play
Overcast 88 88 False No play
Overcast 63 75 True Play
Overcast 88 95 False Play
Rain 78 60 False Play
Rain 66 70 False No play
Rain 68 60 True Play
Classification in Large Databases
• Classification—a classical problem extensively studied by
statisticians and machine learning researchers
• Scalability: Classifying data sets with millions of examples
and hundreds of attributes with reasonable speed
• Why decision tree induction in data mining?
– relatively faster learning speed (than other classification
methods)
– convertible to simple and easy to understand
classification rules
– can use SQL queries for accessing databases
– comparable classification accuracy with other methods
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
Bayesian Theorem: Basics
• Let X be a data sample (“evidence”): class label is unknown
• Let H be a hypothesis that X belongs to class C
• Classification is to determine P(H|X), the probability that the
hypothesis holds given the observed data sample X
• P(H) (prior probability), the initial probability
– E.g., X will buy computer, regardless of age, income, …
• P(X): probability that sample data is observed
• P(X|H) (posteriori probability), the probability of observing the
sample X, given that the hypothesis holds
– E.g., Given that X will buy computer, the prob. that X is
31..40, medium income
Bayesian Theorem
• Given training data X, posteriori probability of a
hypothesis H, P(H|X), follows the Bayes theorem

P(H | X)  P(X | H )P(H )


P(X)
• Informally, this can be written as
posteriori = likelihood x prior/evidence
• Predicts X belongs to Ci iff the probability P(Ci|X) is the
highest among all the P(Ck|X) for all the k classes
• Practical difficulty: require initial knowledge of many
probabilities, significant computational cost
Towards Naïve Bayesian
Classifier
• 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 = (x1, x2, …, xn)
• Suppose there are m classes C1, C2, …, Cm.
• Classification is to derive the maximum posteriori,
i.e., the maximal P(Ci|X)
• This can be derived from Bayes’ theorem
P(X | C )P(C )
P(C | X)  i i P(C | X)  P(X | C )P(C )
i P(X) i i i
• Since P(X) is constant for all classes, only
needs to be maximized
Derivation of Naïve Bayes Classifier
• A simplified assumption: attributes are conditionally
independent (i.e., no dependence relation between attributes):
n
P( X | C i )   P( x | C i )  P( x | C i )  P( x | C i )  ...  P( x | C i )
k 1 2 n
k 1

• This greatly reduces the computation cost: Only counts the class
distribution
• If Ak is categorical, P(xk|Ci) is the # of tuples in Ci having value
xk for Ak divided by |Ci, D| (# of tuples of Ci in D)
• If Ak is continous-valued, P(xk|Ci) is usually computed based on
Gaussian distribution with a mean μ and standard deviation σ
• and P(xk|Ci) is 1 
( x ) 2

g ( x,  ,  )  2 2
e
2 

P(X | C i)  g ( xk , Ci ,  Ci )
Naïve Bayesian Classifier: Training Dataset
age income studentcredit_rating
buys_comput
<=30 high no fair no
<=30 high no excellent no
Class: 31…40 high no fair yes
C1:buys_computer = ‘yes’
>40 medium no fair yes
C2:buys_computer = ‘no’
>40 low yes fair yes
Data sample >40 low yes excellent no
X = (age <=30, 31…40 low yes excellent yes
Income = medium, <=30 medium no fair no
Student = yes <=30 low yes fair yes
Credit_rating = Fair) >40 medium yes fair yes
<=30 medium yes excellent yes
31…40 medium no excellent yes
31…40 high yes fair yes
>40 medium no excellent no
Naïve Bayesian Classifier: An
Example
• P(Ci): P(buys_computer = “yes”) = 9/14 = 0.643
P(buys_computer = “no”) = 5/14= 0.357

• Compute P(X|Ci) for each class


P(age = “<=30” | buys_computer = “yes”) = 2/9 = 0.222
P(age = “<= 30” | buys_computer = “no”) = 3/5 = 0.6
P(income = “medium” | buys_computer = “yes”) = 4/9 = 0.444
P(income = “medium” | buys_computer = “no”) = 2/5 = 0.4
P(student = “yes” | buys_computer = “yes) = 6/9 = 0.667
P(student = “yes” | buys_computer = “no”) = 1/5 = 0.2
P(credit_rating = “fair” | buys_computer = “yes”) = 6/9 = 0.667
P(credit_rating = “fair” | buys_computer = “no”) = 2/5 = 0.4

• X = (age <= 30 , income = medium, student = yes, credit_rating = fair)


P(X|Ci) : P(X|buys_computer = “yes”) = 0.222 x 0.444 x 0.667 x 0.667 = 0.044
P(X|buys_computer = “no”) = 0.6 x 0.4 x 0.2 x 0.4 = 0.019
P(X|Ci)*P(Ci) : P(X|buys_computer = “yes”) * P(buys_computer = “yes”) = 0.028
P(X|buys_computer = “no”) * P(buys_computer = “no”) = 0.007
Therefore, X belongs to class (“buys_computer = yes”)
Avoiding the 0-Probability Problem

• Naïve Bayesian prediction requires each conditional


prob. be non-zero. Otherwise, the predicted prob.
will be zero ) 
n
P( X | P(
Ci | )  xk Ci
k 1

Ex. Suppose a dataset with 1000 tuples, income=low


(0), income= medium (990), and income = high (10),
• Use Laplacian correction (or Laplacian estimator)
– Adding 1 to each case
Prob(income = low) = 1/1003
Prob(income = medium) = 991/1003
Prob(income = high) = 11/1003
– The “corrected” prob. estimates are close to their “uncorrected”
counterparts
Naïve Bayesian Classifier:
Comments
• Advantages
– Easy to implement
– Good results obtained in most of the cases
• Disadvantages
– Assumption: class conditional independence, therefore
loss of accuracy
– Practically, dependencies exist among variables
• E.g., hospitals: patients: Profile: age, family history, etc.
Symptoms: fever, cough etc., Disease: lung cancer, diabetes, etc.
• Dependencies among these cannot be modeled by Naïve
Bayesian Classifier
• How to deal with these dependencies?
– Bayesian Belief Networks
Naïve Bayesian Classifier:
Comments
• Advantages
– Easy to implement
– Good results obtained in most of the cases
• Disadvantages
– Assumption: class conditional independence, therefore
loss of accuracy
– Practically, dependencies exist among variables
• E.g., hospitals: patients: Profile: age, family history, etc.
Symptoms: fever, cough etc., Disease: lung cancer, diabetes, etc.
• Dependencies among these cannot be modeled by Naïve
Bayesian Classifier
• How to deal with these dependencies?
– Bayesian Belief Networks
Data set for Bayesian Classifier
Bayesian Belief Networks
• Bayesian belief network allows a subset of the
variables conditionally independent
• A graphical model of causal relationships
– Represents dependency among the variables
– Gives a specification of joint probability distribution
 Nodes: random variables
 Links: dependency
X Y  X and Y are the parents of Z, and Y is
the parent of P
Z  No dependency between Z and P
P  Has no loops or cycles
Bayesian Belief Network: An
Example
Family The conditional probability table
Smoker
History (CPT) for variable LungCancer:
(FH, S) (FH, ~S) (~FH, S) (~FH, ~S)

LC 0.8 0.5 0.7 0.1


LungCancer Emphysema ~LC 0.2 0.5 0.3 0.9

CPT shows the conditional probability for


each possible combination of its parents

PositiveXRay Dyspnea Derivation of the probability of a


particular combination of values of X,
from CPT:
Bayesian Belief Networks n
P ( x1 ,..., xn )   P ( x i | Parents(Y i ))
i 1
Linear Classification
• Binary Classification
problem
• The data above the red
line belongs to class ‘x’
x
x x • The data below red line
x x
x belongs to class ‘o’
x x o
x • Examples: SVM,
o
x o o Perceptron, Probabilistic
ooo
o o Classifiers
o o o o
Classification by Backpropagation

• Backpropagation: A neural network learning algorithm


• Started by psychologists and neurobiologists to develop
and test computational analogues of neurons
• A neural network: A set of connected input/output units
where each connection has a weight associated with it
• During the learning phase, the network learns by
adjusting the weights so as to be able to predict the
correct class label of the input tuples
• Also referred to as connectionist learning due to the
connections between units
How A Multi-Layer Neural Network Works?
• The inputs to the network correspond to the attributes measured for
each training tuple
• Inputs are fed simultaneously into the units making up the input
layer
• They are then weighted and fed simultaneously to a hidden layer
• The number of hidden layers is arbitrary, although usually only one
• The weighted outputs of the last hidden layer are input to units
making up the output layer, which emits the network's prediction
• The network is feed-forward in that none of the weights cycles back
to an input unit or to an output unit of a previous layer
• From a statistical point of view, networks perform nonlinear
regression: Given enough hidden units and enough training
samples, they can closely approximate any function
Defining a Network Topology
• First decide the network topology: # of units in the input
layer, # of hidden layers (if > 1), # of units in each hidden
layer, and # of units in the output layer
• Normalizing the input values for each attribute measured in
the training tuples to [0.0—1.0]
• One input unit per domain value, each initialized to 0
• Output, if for classification and more than two classes, one
output unit per class is used
• Once a network has been trained and its accuracy is
unacceptable, repeat the training process with a different
network topology or a different set of initial weights
Back propagation
• Iteratively process a set of training tuples & compare the network's
prediction with the actual known target value
• For each training tuple, the weights are modified to minimize the
mean squared error between the network's prediction and the actual
target value
• Modifications are made in the “backwards” direction: from the output
layer, through each hidden layer down to the first hidden layer, hence
“backpropagation”
• Steps
– Initialize weights (to small random #s) and biases in the network
– Propagate the inputs forward (by applying activation function)
– Backpropagate the error (by updating weights and biases)
– Terminating condition (when error is very small, etc.)
A Neuron (= a perceptron)
- k
x0 w0
x1

w1
f
output y
xn wn
For Example
n
Input weight weighted Activation y  sign(  wi xi   k )
vector x vector w sum function i 0

• The n-dimensional input vector x is mapped into


variable y by means of the scalar product and a
nonlinear function mapping
A Multi-Layer Feed-Forward Neural
Network
Output vector

Err j  O j (1  O j ) Errk w jk
Output layer k

 j   j  (l) Err j
wij  wij  (l ) Err j Oi
Hidden layer Err j  O j (1  O j )(T j  O j )
wij 1
Oj  I j
1 e
Input layer
I j   wij Oi   j
i
Input vector: X
Back Propagation Algorithm
Input :
D, a data set consisting of the training tuples and associated target values
l, the learning rate
Network, a multi layer feed-forward network
Output :
A trained neural network
Method :
Initialize all weights and biases in network
While terminating condition is not satisfied {
for each training tuple X in D {
for each input layer unit j {
Oj = Ij; // output of an input unit is its actual input value
for each hidden or output layer unit j {
Ij= Σi wijOi + Øj; // compute the net input of unit j with resp. to prev. layer,i
Oj= 1 / (1 + e –Ij); } // compute the output of each unit j
Back Propagation Algorithm
// Back propagate the errors :
for each unit j in the output layer
Errj= Oj(1-Oj)(Tj-Oj); // Compute the error
for each unit j in the hidden layers from last to first hidden layer
Errj = Oj(1-Oj) Σk Errk wjk; // Compute error with resp. to next
higher layer,k
for each weight wij in network {
Δwij = (l) ErrjOi; // weight increment
wij = wij + Δwij ; } // weight update
For each bias Øj in network {
ΔØj = (l)Errj;
Øj = Øj + ΔØj ;
}}
Important points
• Initialize the weights with small random numbers ranging from -1.0
to 1.0
•  - is bias of the unit – thresholds to vary the activity of the unit.
• The logistic or sigmoid function - squashing function - maps a large
input domain to a smaller range between 0 & 1
• l is the learning rate – typically value between 0.0 and 1.0 - can be
set to 1/t where t is the number of iterations through the training set
so far
• Terminating condition
– When increments in weights are too small
– Number of tuples misclassified in the previous epoch is below some threshold
– A prespecified number of epochs has expired
Neural Network as a Classifier
• Advantages
– High tolerance to noisy data
– Ability to classify untrained patterns
– Well-suited for continuous-valued inputs and outputs
– Successful on a wide array of real-world data
– Algorithms are inherently parallel
– Techniques have recently been developed for the extraction of
rules from trained neural networks
• Disadvantages
– Long training time
– Require a number of parameters typically best determined
empirically, e.g., the network topology or ``structure."
– Poor interpretability: Difficult to interpret the symbolic meaning
behind the learned weights and of ``hidden units" in the network
SVM—History and Applications
• Vapnik and colleagues (1992)—groundwork from Vapnik &
Chervonenkis’ statistical learning theory in 1960s
• Features: training can be slow but accuracy is high owing to their
ability to model complex nonlinear decision boundaries (margin
maximization)
• Used both for classification and prediction
• Applications:
– handwritten digit recognition, object recognition, speaker
identification, benchmarking time-series prediction tests
SVM—General Philosophy

Small Margin Large Margin


Support Vectors
SVM—Margins and Support
Vectors
SVM—Support Vector Machines
• It uses a nonlinear mapping to transform the original training data into a higher
dimension
• With the new dimension, it searches for the linear optimal separating
hyperplane (i.e., “decision boundary”)
– W.X + b = 0 where W is the weight vector and b is scalar value referred to
as bias
– If the training tuples are two dim we can rewrite the seperating hyper plan
as w0 + w1x1 + w2x2 = 0
– The hyperplane with largest margin are selected.
– H1 : w0 + w1x1 + w2x2 >= 1 for class label yi = +1
– H1 : w0 + w1x1 + w2x2 <= -1 for class label yi = -1
• With an appropriate nonlinear mapping to a sufficiently high dimension, data
from two classes can always be separated by a hyperplane
• SVM finds this hyperplane using support vectors (“essential” training tuples)
and margins (defined by the support vectors)
Associative Classification
• Associative classification
– Association rules are generated and analyzed for use in classification
– Search for strong associations between frequent patterns
(conjunctions of attribute-value pairs) and class labels
– Classification: Based on evaluating a set of rules in the form of
P1 ^ p2 … ^ pl  “Aclass = C” (conf, sup)
• Why effective?
– It explores highly confident associations among multiple attributes
and may overcome some constraints introduced by decision-tree
induction, which considers only one attribute at a time
– In many studies, associative classification has been found to be more
accurate than some traditional classification methods, such as C4.5
Typical Associative Classification
Methods
• CBA (Classification By Association: Liu, Hsu & Ma, KDD’98)
– Mine association possible rules in the form of
• Cond-set (a set of attribute-value pairs)  class label
– Build classifier: Organize rules according to decreasing precedence
based on confidence and then support
• CMAR (Classification based on Multiple Association Rules: Li, Han, Pei,
ICDM’01)
– Classification: Statistical analysis on multiple rules
• CPAR (Classification based on Predictive Association Rules: Yin & Han,
SDM’03)
– Generation of predictive rules (FOIL-like analysis)
– High efficiency, accuracy similar to CMAR
Simple non-linear regression
 transform the nonlinear relationship to a linear relationship
using a mathematical transformation
 Situation a: Transformations on the x, y or both x and y
variables such as log or square root.
 Situation b: Transformation on the x variable such as square
root, log or -1/x.
 Situation c: Transformation on the y variable such as square
root, log or -1/y.

63 Introduction to Data Analytics - Rohini R. Rao


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 set, 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 its
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
K-Nearest-Neighbor Classifiers
• First described in the 1950s
• Learning by analogy ie. By comparing a given test tuple with training
tuples that are similar to it.
• Training tuples are described by n attributes.
• Each tuple represents a point in n dim space.
• Classifier searches the pattern space for the k training tuples that
are closest to the unknown tuple.
• Euclidean Distance between two points
• X1 = ( x11,x12,…x1n) and X2 = (x21,x22..x2n) is
• Dist(X1,X2) = √Σ1=1n (x1i – x2i)2
• If attributes have initial large ranges normalize the attributes.
• For k-nearest-neighbor classification , the unknown tuple is assigned
the most common class among its k nearest neighbors.
Distance Measures
• Euclidean Distance
– X1 = ( x11,x12,…x1n) and X2 = (x21,x22..x2n) is
– Dist(X1,X2) = √Σ1=1n (x1i – x2i)2
• Manhattan or City Block Distance
– d(i , j ) = | xi1 – x j1| + | xi2 – xj2| +… | xin – xjn|
• Minkowski Distance
– d(i,j) = (| xi1 – x j1|p + | xi2 – xj2| p+… | xin – xjn|p) 1/p
K-Nearest-Neighbor Classifiers
• When k =1 the unknown tuple is assigned a class of the
training tuple that is closest to it in pattern space
• For categoric data compare the values in both tuples if
they are same and assign 0 else 1. Can also incorporate
grading.
• Selecting a k value is crucial..Chose one that gives the
minimum error rate .
– Starting with k=1 we use a test set to estimate the error rate of
the classifier
– At each step k value is incremented to allow for one more
neighbor.
– K value that gives the minimum error rate is selected.
Discussion on the k-NN Algorithm
• k-NN for real-valued prediction for a given unknown tuple
– Returns the mean values of the k nearest neighbors
• Distance-weighted nearest neighbor algorithm
– Weight the contribution of each of the k neighbors
according to their distance to the query xq w 1
d ( xq , x )2
• Give greater weight to closer neighbors i

• Robust to noisy data by averaging k-nearest neighbors


• Curse of dimensionality: distance between neighbors could
be dominated by irrelevant attributes
– To overcome it, axes stretch or elimination of the least
relevant attributes
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 independent or
predictor variables and a dependent or response variable
• Regression analysis
– Linear (involves single response variable) and multiple linear
regression ( involves two or more response variables)
– 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 = w0 + w1 x
- w0 (y-intercept) and w1 (slope) are regression coefficients
Method of least squares: estimates the best-fitting straight line
| D|

 (x  x )( yi  y )
w  w  y w x
i
i 1

1 | D|

 (x i  x )2
0 1
i 1

• Multiple linear regression: involves more than one predictor


variable
– Training data is of the form (X1, y1), (X2, y2),…, (X|D|, y|D|)
– Ex. For 2-D data, we may have: y = w0 + w1 x1+ w2 x2
– Solvable by extension of least square method or using SAS, S-Plus
– Many nonlinear functions can be transformed into the above
Nonlinear Regression
• Some nonlinear models can be modeled by a polynomial
function
• A polynomial regression model can be transformed into
linear regression model. For example,
y = w0 + w1 x + w2 x2 + w3 x3
convertible to linear with new variables: x2 = x2, x3= x3
y = w0 + w1 x + w2 x2 + w3 x3
• Other functions, such as power function, can also be
transformed to linear model
• Some models are intractable nonlinear (e.g., sum of
exponential terms)
– possible to obtain least square estimates through
extensive calculation on more complex formulae
Simple non-linear regression
 transform the nonlinear relationship to a linear relationship
using a mathematical transformation
 Situation a: Transformations on the x, y or both x and y
variables such as log or square root.
 Situation b: Transformation on the x variable such as square
root, log or -1/x.
 Situation c: Transformation on the y variable such as square
root, log or -1/y.

73 Introduction to Data Analytics - Rohini R. Rao


Other Regression-Based Models
• Generalized linear model:
– Foundation on which linear regression can be applied to modeling
categorical response variables
– Variance of y is a function of the mean value of y, not a constant
– Logistic regression: models the prob. of some event occurring as a
linear function of a set of predictor variables
– Poisson regression: models the data that exhibit a Poisson
distribution
• Log-linear models: (for categorical data)
– Approximate discrete multidimensional prob. distributions
– Also useful for data compression and smoothing
• Regression trees and model trees
– Trees to predict continuous values rather than class labels
Classification Accuracy
• The training set tends to overfit the data
• An independent test set is created randomly
from a general data set.
• The accuracy of the classifier on a given test set
is the percentage of test set tuples that are
correctly classified by the classifier.
• If the accuracy is acceptable then the classifier
is used to classify future data tuples for which
the class label is unknown
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
C1cancer C2~cancer
Classifier Accuracy Measures C1 True positive False negative

C2 False positive True negative

classes buy_computer = yes buy_computer = no total recognition(%)


buy_computer = yes 6954 46 7000 99.34
buy_computer = no 412 2588 3000 86.27
total 7366 2634 10000 95.52
• Accuracy of a classifier M, acc(M): percentage of test set tuples that are correctly
classified by the model M
– Error rate (misclassification rate) of M = 1 – acc(M)
– Given m classes, CMi,j, an entry in a confusion matrix, indicates # of tuples
in class i that are labeled by the classifier as class j
• Alternative accuracy measures (e.g., for cancer diagnosis)
sensitivity = t-pos/pos /* true positive recognition rate */
specificity = t-neg/neg /* true negative recognition rate */
precision = t-pos/(t-pos + f-pos)
accuracy = sensitivity * pos/(pos + neg) + specificity * neg/(pos + neg)
– This model can also be used for cost-benefit analysis
Predictor Error Measures
• Measure predictor accuracy: measure how far off the predicted value is from
the actual known value
• Loss function: measures the error betw. yi and the predicted value yi’
– Absolute error: | yi – yi’|
– Squared error: (yi – yi’)2
• Test error (generalization error): the average loss over the test set
d d
– Mean absolute error:  | yi  yi ' |Mean squared error: ( y  y ')
i i
2
i 1
i 1
d
d
d
Relative squared error: ( yi  yi ' ) 2
d

– Relative absolute error:  | y i 1


i  yi ' |
d i 1
| y y| d

(y
i
i 1
i  y)2
i 1

The mean squared-error exaggerates the presence of outliers


Evaluating the Accuracy of a
Classifier or Predictor (I)
• Holdout method
– Given data is randomly partitioned into two independent sets
• Training set (e.g., 2/3) for model construction
• Test set (e.g., 1/3) for accuracy estimation
– Random sampling: a variation of holdout
• Repeat holdout k times, accuracy = avg. of the accuracies
obtained
• Cross-validation (k-fold, where k = 10 is most popular)
– Randomly partition the data into k mutually exclusive subsets,
each approximately equal size
– At i-th iteration, use Di as test set and others as training set
– Leave-one-out: k folds where k = # of tuples, for small sized data
– Stratified cross-validation: folds are stratified so that class dist. in
each fold is approx. the same as that in the initial data
Evaluating the Accuracy of a
Classifier or Predictor (II)
• Bootstrap
– Works well with small data sets
– Samples the given training tuples uniformly with replacement
• i.e., each time a tuple is selected, it is equally likely to be selected again
and re-added to the training set
• .632 boostrap
– Suppose we are given a data set of d tuples. The data set is sampled d
times, with replacement, resulting in a training set of d samples. The data
tuples that did not make it into the training set end up forming the test set.
About 63.2% of the original data will end up in the bootstrap, and the
remaining 36.8% will form the test set (since (1 – 1/d)d ≈ e-1 = 0.368)
– Repeat the sampling procedure k times, overall accuracy of the model:
k
acc( M )   (0.632  acc( M i ) test _ set 0.368  acc( M i ) train_ set )
i 1
Ensemble Methods: Increasing the
Accuracy

• Ensemble methods
– Use a combination of models to increase accuracy
– Combine a series of k learned models, M1, M2, …, Mk,
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

You might also like