Back to DSfBD Index | Previous: (y-06) Outlier Analysis

Mental Model First

  • Classification learns a model that assigns objects to known classes, so it can predict the class of new objects whose label is unknown. In practice you train several methods and variants in parallel and keep the ones with the best validation and test results.
  • Every performance metric comes from the confusion matrix of true and false positives and negatives. Which metric matters depends on the use case: missing a fraud case and flagging an honest customer have different costs. The MCC uses all four cells and suits imbalanced data.
  • A classifier that outputs probabilities needs a decision threshold. Sweeping the threshold from 1 to 0 traces the ROC curve, and the area under it (AUC) summarizes the classifier across all thresholds: 1 is perfect, 0.5 is guessing.
  • The methods trade accuracy against interpretability. k-NN has no training phase, trees are easy to explain but overfit, forests and boosted trees are accurate but opaque, SVMs separate classes with a maximal margin and kernels, logistic regression returns interpretable probabilities and odds, and naive Bayes scales to many attributes such as words in a text.

1. Classification

Han and Kamber's definition of classification and typical business applications.

Han and Kamber (2006, p. 24) define classification as “the process of finding a model (or function) that describes and distinguishes data classes or concepts”, so that the model can predict the class of objects whose class label is unknown.

Business applications include customer classification in marketing, product classification in sales, fraud detection in finance, finding the factors that affect quality in complex production processes, classifying faults and damaged parts in production, classifying process flows in process analysis, identifying image content and determining the emotional content of a text (sad, angry and so on).

Methods

The classification methods of the chapter. Several are usually trained in parallel.

The chapter covers k-nearest neighbors, classification trees and forests, support vector machines, logistic regression and Bayesian classifiers. Artificial neural networks get their own chapter.

The common approach is to apply several methods and method variants in parallel, then keep the ones with the best results during validation and testing, measured by classification quality and computational performance.

2. Performance Metrics

The Confusion Matrix

The confusion matrix of a binary classifier. False positives are type I (alpha) errors, false negatives type II (beta) errors.

For a binary classifier (an object is in the class or not), the confusion matrix crosses actual and predicted classes:

Predicted positivePredicted negative
Actual positiveTPFN (type II or beta error)
Actual negativeFP (type I or alpha error)TN

is the number of actual positives and the number of actual negatives. All metrics below are built from these four cells.

Example: a classifier for high-risk customers with TP = 6, FN = 1, FP = 2 and TN = 4.

The running example is a classifier that identifies high-risk customers. Of 7 actual high-risk customers it finds 6 (TP = 6, FN = 1). Of 6 customers without risk it flags 2 by mistake (FP = 2, TN = 4). Which metric is suitable depends heavily on the use case.

Metrics from the Confusion Matrix

Accuracy, recall, precision, specificity and inverse precision, computed for the high-risk example.

Fallout, miss rate, F-score and the Matthews correlation coefficient for the same example.

MetricFormulaExample
Accuracy10/13 = 0.77
Recall, sensitivity, true positive rate (TPR)6/7 = 0.86
Precision, confidence, true positive accuracy6/8 = 0.75
Specificity, inverse recall, true negative rate4/6 = 0.67
Inverse precision, true negative accuracy4/5 = 0.8
Fallout, false positive rate (FPR)2/6 = 0.33
Miss rate, false negative rate (FNR)1/7 = 0.14

The F-score (F-factor) is the harmonic mean of recall and precision:

The Matthews correlation coefficient (MCC) is the correlation between actual and predicted values:

It ranges from −1 (predictions are the exact opposite of the actual classes) through 0 (no better than random) to 1 (perfect). Because it uses all four cells, the MCC is particularly suitable for imbalanced data, where one class occurs very rarely or almost always.

The ROC Curve

The ROC curve plots TPR against FPR while the decision threshold moves from maximally strict to maximally permissive.

The Receiver Operating Characteristic comes from friend-or-foe detection in World War II. It starts from a classifier that outputs a probability of class membership:

  1. A decision threshold (cut-off point) sets the minimum probability at which a data point is assigned to the class.
  2. The threshold is adjusted step by step, from maximally strict (no data point is assigned to the class) to maximally permissive (all data points are).
  3. For each threshold, compute TPR and FPR and plot the pair. The points form the ROC curve.

Thirteen customers sorted by predicted probability of being high risk. At threshold 0.5, TPR = 0.86 and FPR = 0.33.

CustomerP(high risk)High risk?At threshold 0.5
Darth0.98yesTP
Kermit0.95yesTP
Lola6660.95yesTP
Asdfasdf0.90yesTP
Tom0.80noFP
Sahra550.70yesTP
Mobi120.60noFP
KevinStrong0.50yesTP
Rupert0.40noTN
Jonas19670.40yesFN
Floh0.30noTN
Hans0.20noTN
BieneMaja0.10noTN

At threshold 0.5 the table reproduces the confusion matrix from the example: TPR = 6/7 = 0.86 and FPR = 2/6 = 0.33. Lowering the threshold from 1 to 0 moves the cut line down the table one customer at a time.

The resulting ROC curve, with the point for threshold 0.5 at FPR 0.33 and TPR 0.86.

Area under the ROC curve: the ideal curve is a rectangle through (0,1), random prediction is the diagonal.

  • The maximally strict threshold classifies every point as negative, which gives the point (0, 0): no positives found and no negatives falsely assigned.
  • The maximally permissive threshold classifies every point as positive, which gives (1, 1): all positives found, but all negatives falsely flagged.
  • An ideal classifier runs through (0, 0), (0, 1) and (1, 1). The worst case is the diagonal from (0, 0) to (1, 1), which is random prediction.

The larger the area under the curve, the better. The area under the ROC curve (AUC or AROC) is therefore a performance metric between 0.5 (random) and 1 (perfect).

Predicting defects in 3D printing (Lutz, Sultanic and Thai 2017): random forest 99.96%, SVM 94.18%, neural network 87.84% AUC.

In a study on predicting defects in 3D printing processes (Lutz, Sultanic and Thai 2017), a random forest reached an AUC of 99.96%, a support vector machine 94.18% and a neural network 87.84%.

3. k-Nearest Neighbors

k-NN compares a data point with its k nearest neighbors and adopts their most frequent class.

k-NN compares a new data point with its k nearest neighbors in the training data and assigns their most frequent class. The method is very simple and efficient. It builds no model during training, so it is not machine learning in the strict sense and is called a lazy classifier.

5-NN on visit frequency and forum posts: which of four new customers are potential premium customers?

The example classifies four new customers as potential premium customers based on visit frequency per week and number of forum posts, using the 5 nearest neighbors:

New customer (visits / posts)Neighbors: premium / notClassified as
(20 / 18)5 / 0premium
(31 / 3)3 / 2premium
(3 / 5)2 / 2not premium
(0 / 15)0 / 5not premium

The slide counts only four neighbors for (3 / 5). With five neighbors and two classes a vote cannot tie, so the fifth neighbor would decide; the slide’s answer implies it is not a premium customer.

4. Classification Trees and Forests

Classification trees: chained if-then rules from the root to a leaf, with variants for regression and outlier detection.

A classification tree arranges classification rules in a tree:

  • Attributes are ordered hierarchically by their relevance for the class assignment.
  • Each path from the root to a leaf is a decision rule made of chained if-then statements, and each leaf is a classification decision.
  • Regression trees predict values (for example a mean) or value ranges instead of a class. A model tree puts regression models in the leaves.
  • Isolation trees and isolation forests use trees for outlier detection: isolated data points have short paths from the root (see L06).
  • Humans can define trees by hand, but they are usually learned from data.

A tree predicting which motif customers of an online shop for nerd products choose. The bars show class proportions in each leaf.

The example predicts the motif a customer of an online shop for nerd products will choose (science fiction, games, fantasy, maths, physics or superheroes) from attributes such as age, how urban the customer’s area is, sex and preferred fit. The bars in each leaf show the class proportions among the training data in that leaf.

The confusion matrix of the motif tree. Reality can rarely be captured perfectly, and a model that does is often overfitted.

Reality can rarely be captured perfectly in a model, and a model that seems to do so is often overfitted.

Learning a Tree

A tree is grown by repeatedly choosing the split that leaves the most homogeneous parts.

  1. Find the attribute (and value) that splits the training data into the most homogeneous parts. An impurity criterion such as the Gini index or information gain measures homogeneity: choose the partition whose summed impurity, weighted by the size of each subtree, is minimal.
  2. Repeat the split for each subtree.
  3. This tends to overfit (overlearning): the model follows the training data too closely and does not generalize. The remedy is pruning.

Two splits on the motif data. Split 2 on urbanization leaves one group that is mostly science fiction.

Pruning the title split: three leaves that fit 9,105 rows become one science fiction leaf.

In the pruning example, a split on academic title below “female” produces three leaves for 9,105 training rows: Dr (science fiction, correct for 14 of 16 rows), Prof (physics, correct for 2 of 2) and no title (science fiction, correct for 8,087 of 9,087). Pruning replaces the subtree with a single science fiction leaf that is correct for 8,101 of 9,105 rows. Pruning costs two correctly classified training rows and removes rules that only covered 18 rows.

Tree methods differ in scales, prediction type, impurity measure, pruning, backtracking, missing values and tree shape.

Tree methods come in many variants. They differ mainly in:

  • the attribute scales they accept (only nominal, or metric as well),
  • the type of prediction (classification only, or also regression, isolation or model trees),
  • the impurity measure,
  • whether and how they prune,
  • backtracking (adjusting earlier splits),
  • how they handle missing values,
  • the shape of the trees (only binary trees with exactly two subtrees per node, or several branches per node).

Forests

Forests grow many trees and combine their results. Bagging and boosting are general strategies, not limited to trees.

Forests grow a large number of trees and combine their results, which makes them more robust and less prone to overlearning.

  • Random forests draw many samples from the training data (bagging) and pick a random subset of attributes to consider at each split. The forest’s result is the majority vote of its trees.
  • Boosted trees and gradient boosted trees grow many very simple trees (stumps) as base classifiers. Step by step they add the next best subtree, with previously misclassified training data weighted higher.

Bagging and boosting work for other base models as well. The downside of forests: they are more complex and less intuitive than a single decision tree.

Bagging: statistical sampling, one model per sample, and a majority vote over their results (payer or non-payer).

A random forest with 8 trees for the motif example. Not quite as intuitive as a single tree.

Trees and forests: advantages and disadvantages.

AdvantagesDisadvantages
Established methodSingle trees tend to overfit and follow the training data
Basic principle is clear and easy to communicateForests, especially boosted trees, cost much more computation
Good results, very good with random forests and boostingForests are no longer intuitive

5. Support Vector Machines

SVMs separate classes with the hyperplane that has the widest margin, allow some errors, and use kernels when no linear separation exists.

An SVM separates data points geometrically. It looks for the decision line (plane, or hyperplane in higher dimensions) that maximizes the distance, the margin, to the data points of the two classes. The wider the margin, the more reliable the separation. The data points closest to the hyperplane are the support vectors.

Real data is not always cleanly separable:

  • The C value allows some misclassified data points. It adjusts how sensitive the SVM is to points near the decision boundary and how the two margins are weighted.
  • If the data is fundamentally not linearly separable, a kernel function maps it into a higher-dimensional space where a linear separation exists.

An SVM for fake news, using machine-detected spelling mistakes and the number of shares within 10 minutes. A soft margin tolerates some errors.

The fake news example separates messages by two criteria: the number of machine-detected spelling mistakes and the number of people the message was shared with within 10 minutes. The SVM tolerates a few modeling errors to keep the margin wide (soft margin).

Without linear separability: a radial kernel separates a compact cluster from the points around it.

The marathon example in scikit-learn with a radial kernel: buyers and non-buyers by age and marathon time.

The marathon example, computed with scikit-learn, uses a radial kernel to separate buyers from non-buyers by age and marathon performance in minutes. The plot marks training data, correctly classified test data and misclassified test points.

Kernel selection in RapidMiner: dot, radial, polynomial, neural, anova, Epanechnikov and others.

Which kernel works best is found by trying them out. RapidMiner, for example, offers dot, radial, polynomial, neural, anova, Epanechnikov, Gaussian combination and multiquadric kernels.

SVMs: advantages and disadvantages.

AdvantagesDisadvantages
Well established in many use casesComputationally intensive
Very robust, even with noiseHard to interpret with many dimensions
Not prone to overlearning

6. Logistic Regression

Logistic regression predicts the probability of class membership with the sigmoid function.

Logistic regression uses a regression method for classification. Linear regression does not fit class labels (0 or 1): several of its mathematical assumptions are violated, and its predictions can become arbitrarily large or small. Logistic regression predicts the probability of class membership instead, using the logistic (sigmoid) function

where is a linear combination of the independent attributes. Depending on the parameters, the function rises from 0 to 1 more or less abruptly. The parameters are estimated with a regression procedure such as maximum likelihood.

Maintenance need against machine hours, with the fitted logistic curve and a threshold at p = 0.5.

The example predicts whether a machine needs maintenance from its runtime in hours:

A threshold such as turns the probability into a class.

Logistic regression with two attributes is a surface. From three attributes on it becomes hard to visualize.

The method works with more than one attribute as well. With two attributes the result is a surface; with three or more it becomes hard to visualize.

Interpreting the parameters through log-odds: each machine hour multiplies the odds by e

The logistic function is the inverse of the logit, the natural logarithm of the odds (the probability divided by its complementary probability). In the example:

  • The parameter 0.003 is positive, so the probability of belonging to the failure class rises with machine runtime.
  • : the odds grow by a factor of 1.003 for each additional machine hour.
  • For each additional 500 machine hours, the odds grow by a factor of .

Logistic regression: advantages and disadvantages.

AdvantagesDisadvantages
Commonly usedNeeds extensive preprocessing: cleaning outliers, adjusting for dependencies between attributes
Good interpretability of the result (a probability)
The approach reappears in standard building blocks of neural networks

7. Bayes Classifiers

Bayes classifiers compute the probability of class membership from prior knowledge with Bayes' theorem.

Bayes classifiers also determine the probability of class membership. They use prior knowledge of relative probabilities, which can be estimated from the class distribution of the training data, and compute the result with Bayes’ theorem. Naive Bayes classifiers are the most common variant: they assume that each explanatory attribute influences the class independently. That makes them suitable for problems with very many attributes, such as text analysis.

Typical applications are classifying help-desk tickets, complaints, damage reports or customer feedback, spam detection, and identifying hate speech or misinformation on social networks.

Bayes' theorem: posterior, likelihood, prior and evidence.

TermMeaningName
Probability of class given that feature is observeda posteriori probability
Probability of observing feature given class likelihood
Probability of class prior
Probability of feature evidence

Spam example: 8% of all mails are spam, 20% of spam and 0.43% of non-spam mentions weight loss.

From P(weight loss | spam) to P(spam | weight loss): a new mail with "weight loss" in the subject is spam with probability 80%.

The spam example starts from what is known:

  • 8% of all mails are spam: , so .
  • 20% of spam mails have “weight loss” in the subject: .
  • 0.43% of non-spam mails do: .

Bayes’ theorem gives the probability that a new mail with “weight loss” in the subject is spam:

So , and the new mail is four times more likely to be spam than not.

Naive Bayes scales well and often works surprisingly well, but fails with strong dependencies between features.

  • Naive Bayes scales very well and often works surprisingly well, even when the independence assumption only roughly holds.
  • It fails when features really are strongly dependent.
  • It does not understand semantics. Large language models do, but at much higher computational cost.
  • It is therefore unsuitable for strong processual dependencies: it can analyze process outcomes, but not process structures.

Summary

Classification predicts known class labels for new objects. Evaluate classifiers through the confusion matrix and pick the metric the use case needs: recall when misses are expensive, precision when false alarms are, MCC for imbalanced classes, and ROC and AUC when you want to compare classifiers across all thresholds. k-NN needs no training, trees are transparent but overfit until pruned, forests and boosting are accurate but opaque, SVMs maximize the margin and use kernels for non-linear boundaries, logistic regression gives probabilities with interpretable odds, and naive Bayes scales to many independent features such as words.

Self-Check

  1. For TP = 6, FN = 1, FP = 2 and TN = 4, compute accuracy, recall, precision and specificity.
  1. Compute the F-score and the MCC for the same matrix.
  1. Only 1% of transactions are fraud. A model always predicts “no fraud”. What are its accuracy, recall and MCC, and what does this show?
  1. Which points does every ROC curve pass through, and what AUC does random guessing give?
  1. Why is k-NN called a lazy classifier?
  1. How is a classification tree grown, and why does it need pruning?
  1. In the pruning example, how many training rows were classified correctly before and after pruning?
  1. What is the difference between bagging and boosting?
  1. What are support vectors, and what do the C value and a kernel do?
  1. In the maintenance model , at what runtime is the probability 0.5, and by how much do the odds change per 500 hours?
  1. With , and , how likely is a mail with “weight loss” in the subject to be spam?
  1. Why is naive Bayes good for text classification but unsuitable for analyzing process structures?

Back to DSfBD Index | Previous: (y-06) Outlier Analysis