Download presentation
Presentation is loading. Please wait.
1
Machine Learning” Notes 2
Dr. Alper Özpınar
2
Training, Validating and Testing Data
To make a model, we first need data that has an underlying relationship. For this example, we will create our own simple dataset with x-values (features) and y-values (labels). An important part of our data generation is adding random noise to the labels. In any real-world process, whether natural or man-made, the data does not exactly fit to a trend. There is always noise or other variables in the relationship we cannot measure. November 21, 2018
3
Training, Validating and Testing Data
November 21, 2018
4
November 21, 2018
5
Overfitting in Machine Learning
Overfitting refers to a model that models the training data too well. Overfitting happens when a model learns the detail and noise in the training data to the extent that it negatively impacts the performance of the model on new data. This means that the noise or random fluctuations in the training data is picked up and learned as concepts by the model. The problem is that these concepts do not apply to new data and negatively impact the models ability to generalize. Overfitting is more likely with nonparametric and nonlinear models that have more flexibility when learning a target function. As such, many nonparametric machine learning algorithms also include parameters or techniques to limit and constrain how much detail the model learns. For example, decision trees are a nonparametric machine learning algorithm that is very flexible and is subject to overfitting training data. This problem can be addressed by pruning a tree after it has learned in order to remove some of the detail it has picked up. November 21, 2018
6
Underfitting in Machine Learning
Underfitting refers to a model that can neither model the training data nor generalize to new data. An underfit machine learning model is not a suitable model and will be obvious as it will have poor performance on the training data. Underfitting is often not discussed as it is easy to detect given a good performance metric. The remedy is to move on and try alternate machine learning algorithms. Nevertheless, it does provide a good contrast to the problem of overfitting. November 21, 2018
7
November 21, 2018
8
A programming task
9
Illustrating Classification Task
10
Classification Using Distance
Place items in class to which they are “closest”. Must determine distance between an item and a class. Classes represented by Centroid: Central value. Medoid: Representative point. Individual points Algorithm: KNN
11
K Nearest Neighbor (KNN):
Training set includes classes. Examine K items near item to be classified. New item placed in class with the most number of close items. O(q) for each tuple to be classified. (Here q is the size of the training set.)
12
KNN
13
Nearest Neighbor Classifiers
Basic idea: If it walks like a duck, quacks like a duck, then it’s probably a duck Training Records Test Record Compute Distance Choose k of the “nearest” records 11/21/2018 Data Mining: Concepts and Techniques
14
Nearest neighbor method
Majority vote within the k nearest neighbors new K= 1: brown K= 3: green 11/21/2018 Data Mining: Concepts and Techniques
15
Nearest-Neighbor Classifiers
Requires three things The set of stored records Distance Metric to compute distance between records The value of k, the number of nearest neighbors to retrieve To classify an unknown record: Compute distance to other training records Identify k nearest neighbors Use class labels of nearest neighbors to determine the class label of unknown record (e.g., by taking majority vote) 11/21/2018 Data Mining: Concepts and Techniques
16
Definition of Nearest Neighbor
K-nearest neighbors of a record x are data points that have the k smallest distance to x 11/21/2018 Data Mining: Concepts and Techniques
17
Data Mining: Concepts and Techniques
1 nearest-neighbor Voronoi Diagram 11/21/2018 Data Mining: Concepts and Techniques
18
Nearest Neighbor Classification
Compute distance between two points: Euclidean distance Determine the class from nearest neighbor list take the majority vote of class labels among the k-nearest neighbors Weigh the vote according to distance weight factor, w = 1/d2 11/21/2018 Data Mining: Concepts and Techniques
19
Nearest Neighbor Classification…
Choosing the value of k: If k is too small, sensitive to noise points If k is too large, neighborhood may include points from other classes 11/21/2018 Data Mining: Concepts and Techniques
20
Nearest Neighbor Classification…
Scaling issues Attributes may have to be scaled to prevent distance measures from being dominated by one of the attributes Example: height of a person may vary from 1.5m to 1.8m weight of a person may vary from 90lb to 300lb income of a person may vary from $10K to $1M 11/21/2018 Data Mining: Concepts and Techniques
21
Nearest Neighbor Classification…
Problem with Euclidean measure: High dimensional data curse of dimensionality Can produce counter-intuitive results vs d = d = Solution: Normalize the vectors to unit length 11/21/2018 Data Mining: Concepts and Techniques
22
Nearest neighbor Classification…
k-NN classifiers are lazy learners It does not build models explicitly Unlike eager learners such as decision tree induction and rule-based systems Classifying unknown records are relatively expensive 11/21/2018 Data Mining: Concepts and Techniques
23
Discussion on the k-NN Algorithm
The k-NN algorithm for continuous-valued target functions Calculate 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 point xq giving greater weight to closer neighbors Similarly, for real-valued target functions 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. 11/21/2018 Data Mining: Concepts and Techniques
24
Decision Trees Training Data Model: Decision Tree Splitting Attributes
categorical continuous class Splitting Attributes Refund Yes No NO MarSt Single, Divorced Married TaxInc NO < 80K > 80K NO YES Training Data Model: Decision Tree
25
Another Example of Decision Tree
categorical categorical continuous class MarSt Single, Divorced Married NO Refund No Yes NO TaxInc < 80K > 80K NO YES There could be more than one tree that fits the same data!
26
Decision Tree Classification Task
27
Apply Model to Test Data
Start from the root of tree. Refund MarSt TaxInc YES NO Yes No Married Single, Divorced < 80K > 80K
28
Apply Model to Test Data
Refund MarSt TaxInc YES NO Yes No Married Single, Divorced < 80K > 80K
29
Apply Model to Test Data
Refund Yes No NO MarSt Single, Divorced Married TaxInc NO < 80K > 80K NO YES
30
Apply Model to Test Data
Refund Yes No NO MarSt Single, Divorced Married TaxInc NO < 80K > 80K NO YES
31
Apply Model to Test Data
Refund Yes No NO MarSt Single, Divorced Married TaxInc NO < 80K > 80K NO YES
32
Apply Model to Test Data
Refund Yes No NO MarSt Married Assign Cheat to “No” Single, Divorced TaxInc NO < 80K > 80K NO YES
33
Decision Tree Classification Task
34
Decision Tree Induction
Many Algorithms: Hunt’s Algorithm (one of the earliest) CART ID3, C4.5 SLIQ,SPRINT
35
General Structure of Hunt’s Algorithm
Let Dt be the set of training records that reach a node t General Procedure: If Dt contains records that belong the same class yt, then t is a leaf node labeled as yt If Dt is an empty set, then t is a leaf node labeled by the default class, yd If Dt contains records that belong to more than one class, use an attribute test to split the data into smaller subsets. Recursively apply the procedure to each subset. Dt ?
36
Hunt’s Algorithm Refund Refund Refund Marital Marital Status Status
Don’t Cheat Yes No Don’t Cheat Refund Don’t Cheat Yes No Marital Status Single, Divorced Married Refund Don’t Cheat Yes No Marital Status Single, Divorced Married Taxable Income < 80K >= 80K
37
Tree Induction Greedy strategy. Issues
Split the records based on an attribute test that optimizes certain criterion. Issues Determine how to split the records How to specify the attribute test condition? How to determine the best split? Determine when to stop splitting
38
Tree Induction Greedy strategy. Issues
Split the records based on an attribute test that optimizes certain criterion. Issues Determine how to split the records How to specify the attribute test condition? How to determine the best split? Determine when to stop splitting
39
How to Specify Test Condition?
Depends on attribute types Nominal Ordinal Continuous Depends on number of ways to split 2-way split Multi-way split
40
Splitting Based on Nominal Attributes
Multi-way split: Use as many partitions as distinct values. Binary split: Divides values into two subsets Need to find optimal partitioning. CarType Family Sports Luxury CarType {Sports, Luxury} {Family} OR CarType {Family, Luxury} {Sports}
41
Splitting Based on Ordinal Attributes
Multi-way split: Use as many partitions as distinct values. Binary split: Divides values into two subsets Need to find optimal partitioning. What about this split? Size Small Medium Large Size {Small, Medium} {Large} Size {Medium, Large} {Small} OR Size {Small, Large} {Medium}
42
Splitting Based on Continuous Attributes
Different ways of handling Discretization to form an ordinal categorical attribute Static – discretize once at the beginning Dynamic – ranges can be found by equal interval bucketing, equal frequency bucketing (percentiles), or clustering. Binary Decision: (A < v) or (A v) consider all possible splits and finds the best cut can be more compute intensive
43
Splitting Based on Continuous Attributes
44
Tree Induction Greedy strategy. Issues
Split the records based on an attribute test that optimizes certain criterion. Issues Determine how to split the records How to specify the attribute test condition? How to determine the best split? Determine when to stop splitting
45
How to determine the Best Split
Before Splitting: 10 records of class 0, 10 records of class 1 Which test condition is the best?
46
How to determine the Best Split
Greedy approach: Nodes with homogeneous class distribution are preferred Need a measure of node impurity: Non-homogeneous, High degree of impurity Homogeneous, Low degree of impurity
47
Measures of Node Impurity
Gini Index Entropy Misclassification error
48
How to Find the Best Split
Before Splitting: M0 A? B? Yes No Yes No Node N1 Node N2 Node N3 Node N4 M1 M2 M3 M4 M12 M34 Gain = M0 – M12 vs M0 – M34
49
Measure of Impurity: GINI
Gini Index for a given node t : (NOTE: p( j | t) is the relative frequency of class j at node t). Maximum (1 - 1/nc) when records are equally distributed among all classes, implying least interesting information Minimum (0.0) when all records belong to one class, implying most interesting information
50
Examples for computing GINI
P(C1) = 0/6 = P(C2) = 6/6 = 1 Gini = 1 – P(C1)2 – P(C2)2 = 1 – 0 – 1 = 0 P(C1) = 1/ P(C2) = 5/6 Gini = 1 – (1/6)2 – (5/6)2 = 0.278 P(C1) = 2/ P(C2) = 4/6 Gini = 1 – (2/6)2 – (4/6)2 = 0.444
51
Splitting Based on GINI
Used in CART, SLIQ, SPRINT. When a node p is split into k partitions (children), the quality of split is computed as, where, ni = number of records at child i, n = number of records at node p.
52
Binary Attributes: Computing GINI Index
Splits into two partitions Effect of Weighing partitions: Larger and Purer Partitions are sought for. B? Yes No Node N1 Node N2 Gini(N1) = 1 – (5/6)2 – (2/6)2 = 0.194 Gini(N2) = 1 – (1/6)2 – (4/6)2 = 0.528 Gini(Children) = 7/12 * /12 * = 0.333
53
Categorical Attributes: Computing Gini Index
For each distinct value, gather counts for each class in the dataset Use the count matrix to make decisions Multi-way split Two-way split (find best partition of values)
54
Continuous Attributes: Computing Gini Index
Use Binary Decisions based on one value Several Choices for the splitting value Number of possible splitting values = Number of distinct values Each splitting value has a count matrix associated with it Class counts in each of the partitions, A < v and A v Simple method to choose best v For each v, scan the database to gather count matrix and compute its Gini index Computationally Inefficient! Repetition of work.
55
Continuous Attributes: Computing Gini Index...
For efficient computation: for each attribute, Sort the attribute on values Linearly scan these values, each time updating the count matrix and computing gini index Choose the split position that has the least gini index Split Positions Sorted Values
56
Alternative Splitting Criteria based on INFO
Entropy at a given node t: (NOTE: p( j | t) is the relative frequency of class j at node t). Measures homogeneity of a node. Maximum (log nc) when records are equally distributed among all classes implying least information Minimum (0.0) when all records belong to one class, implying most information Entropy based computations are similar to the GINI index computations
57
Examples for computing Entropy
P(C1) = 0/6 = P(C2) = 6/6 = 1 Entropy = – 0 log 0 – 1 log 1 = – 0 – 0 = 0 P(C1) = 1/ P(C2) = 5/6 Entropy = – (1/6) log2 (1/6) – (5/6) log2 (1/6) = 0.65 P(C1) = 2/ P(C2) = 4/6 Entropy = – (2/6) log2 (2/6) – (4/6) log2 (4/6) = 0.92
58
Splitting Based on INFO...
Information Gain: Parent Node, p is split into k partitions; ni is number of records in partition i Measures Reduction in Entropy achieved because of the split. Choose the split that achieves most reduction (maximizes GAIN) Used in ID3 and C4.5 Disadvantage: Tends to prefer splits that result in large number of partitions, each being small but pure.
59
Splitting Based on INFO...
Gain Ratio: Parent Node, p is split into k partitions ni is the number of records in partition i Adjusts Information Gain by the entropy of the partitioning (SplitINFO). Higher entropy partitioning (large number of small partitions) is penalized! Used in C4.5 Designed to overcome the disadvantage of Information Gain
60
Splitting Criteria based on Classification Error
Classification error at a node t : Measures misclassification error made by a node. Maximum (1 - 1/nc) when records are equally distributed among all classes, implying least interesting information Minimum (0.0) when all records belong to one class, implying most interesting information
61
Examples for Computing Error
P(C1) = 0/6 = P(C2) = 6/6 = 1 Error = 1 – max (0, 1) = 1 – 1 = 0 P(C1) = 1/ P(C2) = 5/6 Error = 1 – max (1/6, 5/6) = 1 – 5/6 = 1/6 P(C1) = 2/ P(C2) = 4/6 Error = 1 – max (2/6, 4/6) = 1 – 4/6 = 1/3
62
Comparison among Splitting Criteria
For a 2-class problem:
63
Misclassification Error vs Gini
Yes No Node N1 Node N2 Gini(N1) = 1 – (3/3)2 – (0/3)2 = 0 Gini(N2) = 1 – (4/7)2 – (3/7)2 = 0.489 Gini(Children) = 3/10 * /10 * = 0.342
64
Tree Induction Greedy strategy. Issues
Split the records based on an attribute test that optimizes certain criterion. Issues Determine how to split the records How to specify the attribute test condition? How to determine the best split? Determine when to stop splitting
65
Stopping Criteria for Tree Induction
Stop expanding a node when all the records belong to the same class Stop expanding a node when all the records have similar attribute values Early termination (to be discussed later)
66
Decision Tree Based Classification
Advantages: Inexpensive to construct Extremely fast at classifying unknown records Easy to interpret for small-sized trees Accuracy is comparable to other classification techniques for many simple data sets
67
Practical Issues of Classification
Underfitting and Overfitting Missing Values Costs of Classification
68
Underfitting and Overfitting (Example)
500 circular and 500 triangular data points. Circular points: 0.5 sqrt(x12+x22) 1 Triangular points: sqrt(x12+x22) > 0.5 or sqrt(x12+x22) < 1
69
Underfitting and Overfitting
Underfitting: when model is too simple, both training and test errors are large
70
Overfitting due to Noise
Decision boundary is distorted by noise point
71
Overfitting due to Insufficient Examples
Lack of data points in the lower half of the diagram makes it difficult to predict correctly the class labels of that region - Insufficient number of training records in the region causes the decision tree to predict the test examples using other training records that are irrelevant to the classification task
72
Notes on Overfitting Overfitting results in decision trees that are more complex than necessary Training error no longer provides a good estimate of how well the tree will perform on previously unseen records Need new ways for estimating errors
73
Minimum Description Length (MDL)
Cost(Model,Data) = Cost(Data|Model) + Cost(Model) Cost is the number of bits needed for encoding. Search for the least costly model. Cost(Data|Model) encodes the misclassification errors. Cost(Model) uses node encoding (number of children) plus splitting condition encoding.
74
How to Address Overfitting
Pre-Pruning (Early Stopping Rule) Stop the algorithm before it becomes a fully-grown tree Typical stopping conditions for a node: Stop if all instances belong to the same class Stop if all the attribute values are the same More restrictive conditions: Stop if number of instances is less than some user-specified threshold Stop if class distribution of instances are independent of the available features (e.g., using 2 test) Stop if expanding the current node does not improve impurity measures (e.g., Gini or information gain).
75
How to Address Overfitting…
Post-pruning Grow decision tree to its entirety Trim the nodes of the decision tree in a bottom-up fashion If generalization error improves after trimming, replace sub-tree by a leaf node. Class label of leaf node is determined from majority class of instances in the sub-tree Can use MDL for post-pruning
76
Example of Post-Pruning
Training Error (Before splitting) = 10/30 Pessimistic error = ( )/30 = 10.5/30 Training Error (After splitting) = 9/30 Pessimistic error (After splitting) = (9 + 4 0.5)/30 = 11/30 PRUNE! Class = Yes 20 Class = No 10 Error = 10/30 Class = Yes 8 Class = No 4 Class = Yes 3 Class = No 4 Class = Yes 4 Class = No 1 Class = Yes 5 Class = No 1
77
Examples of Post-pruning
Case 1: C0: 11 C1: 3 C0: 2 C1: 4 Optimistic error? Pessimistic error? Reduced error pruning? Don’t prune for both cases Don’t prune case 1, prune case 2 Case 2: C0: 14 C1: 3 C0: 2 C1: 2 Depends on validation set
78
Handling Missing Attribute Values
Missing values affect decision tree construction in three different ways: Affects how impurity measures are computed Affects how to distribute instance with missing value to child nodes Affects how a test instance with missing value is classified
79
Computing Impurity Measure
Before Splitting: Entropy(Parent) = -0.3 log(0.3)-(0.7)log(0.7) = Split on Refund: Entropy(Refund=Yes) = 0 Entropy(Refund=No) = -(2/6)log(2/6) – (4/6)log(4/6) = Entropy(Children) = 0.3 (0) (0.9183) = 0.551 Gain = 0.9 ( – 0.551) = Missing value
80
Distribute Instances Probability that Refund=Yes is 3/9
No Probability that Refund=Yes is 3/9 Probability that Refund=No is 6/9 Assign record to the left child with weight = 3/9 and to the right child with weight = 6/9 Refund Yes No
81
Classify Instances New record:
Married Single Divorced Total Class=No 3 1 4 Class=Yes 6/9 2.67 3.67 2 6.67 Refund Yes No NO MarSt Single, Divorced Married Probability that Marital Status = Married is 3.67/6.67 Probability that Marital Status ={Single,Divorced} is 3/6.67 TaxInc NO < 80K > 80K NO YES
82
K-means Algorithm e.g., Euclidean distance
Partitioning Clustering Approach a typical clustering analysis approach via iteratively partitioning training data set to learn a partition of the given data space learning a partition on a data set to produce several non-empty clusters (usually, the number of clusters given in advance) in principle, optimal partition achieved via minimising the sum of squared distance to its “representative object” in each cluster e.g., Euclidean distance
83
Introduction Given a K, find a partition of K clusters to optimise the chosen partitioning criterion (cost function) global optimum: exhaustively search all partitions The K-means algorithm: a heuristic method K-means algorithm (MacQueen’67): each cluster is represented by the centre of the cluster and the algorithm converges to stable centriods of clusters. K-means algorithm is the simplest partitioning method for clustering analysis and widely used in data mining applications.
84
K-means Algorithm Given the cluster number K, the K-means algorithm is carried out in three steps after initialisation: Initialisation: set seed points (randomly) Assign each object to the cluster of the nearest seed point measured with a specific distance metric Compute new seed points as the centroids of the clusters of the current partition (the centroid is the centre, i.e., mean point, of the cluster) Go back to Step 1), stop when no more new assignment (i.e., membership in each cluster no longer changes)
85
Example Problem Medicine Weight pH-Index A 1 B 2 C 4 3 D 5
Suppose we have 4 types of medicines and each has two attributes (pH and weight index). Our goal is to group these objects into K=2 group of medicine. A B C D Medicine Weight pH-Index A 1 B 2 C 4 3 D 5
86
Example Step 1: Use initial seed points for partitioning
Assign each object to the cluster with the nearest seed point D Euclidean distance C A B
87
Example Step 2: Compute new centroids of the current partition
Knowing the members of each cluster, now we compute the new centroid of each group based on these new memberships.
88
Example Step 2: Renew membership based on new centroids
Compute the distance of all objects to the new centroids Assign the membership to objects
89
Example Step 3: Repeat the first two steps until its convergence
Knowing the members of each cluster, now we compute the new centroid of each group based on these new memberships.
90
Example Step 3: Repeat the first two steps until its convergence
Compute the distance of all objects to the new centroids Stop due to no new assignment Membership in each cluster no longer change
91
Exercise For the medicine data set, use K-means with the Manhattan distance metric for clustering analysis by setting K=2 and initialising seeds as C1 = A and C2 = C. Answer three questions as follows: How many steps are required for convergence? What are memberships of two clusters after convergence? What are centroids of two clusters after convergence? Medicine Weight pH-Index A 1 B 2 C 4 3 D 5 A B C D
92
K-Means vs KNN November 21, 2018 K-Means KNN
It is an Unsupervised learning technique It is a Supervised learning technique It is used for Clustering It is used mostly for Classification, and sometimes even for Regression ‘K’ in K-Means is the number of clusters the algorithm is trying to identify/learn from the data. The clusters are often unknown since this is used with Unsupervised learning. ‘K’ in KNN is the number of nearest neighbours used to classify or (predict in case of continuous variable/regression) a test sample It is typically used for scenarios like understanding the population demomgraphics, market segmentation, social media trends, anomaly detection, etc. where the clusters are unknown to begin with. It is used for classification and regression of known data where usually the target attribute/variable is known before hand. In training phase of K-Means, K observations are arbitrarily selected (known as centroids). Each point in the vector space is assigned to a cluster represented by nearest (euclidean distance) centroid. Once the clusters are formed, for each cluster the centroid is updated to the mean of all cluster members. And the cluster formation restarts with new centroids. This repeats until the centroids themselves become mean of clusters, i.e., when updating centroids to mean doesn’t change them. The prediction of a test observation is done based on nearest centroid. K-NN doesn’t have a training phase as such. But the prediction of a test observation is done based on the K-Nearest (often euclidean distance) Neighbours (observations) based on weighted averages/votes. November 21, 2018
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.