Guide to AI and Data Courses · Lecture Notes
Chapter 8: Pattern Recognition
On a production line the length of each screw is measured, and a machine must sort every screw as "good" or "defective". Defective screws are slightly longer on average, but some good screws also come out long: the measurement alone does not settle the decision. Pattern recognition is the course about this situation: extracting features from measurements, building a decision rule that takes into account how the classes are distributed and how costly each kind of mistake is, and measuring how often the rule errs. This note introduces the course and shows its three core ideas with small examples that can be worked by hand.
Learning outcomes
- A recognition system
- Break a problem into sensing, preprocessing, feature extraction, classification and evaluation; explain the feature vector and feature space with an example.
- Bayes decision
- Decide an object's class from the prior, likelihood and posterior probability; compute how the decision boundary shifts when error costs change.
- Nearest neighbor
- Make a k-nearest-neighbor decision by hand on a small dataset with Euclidean distance; show how the scale of the features changes the decision.
- Dimensionality reduction
- Find the principal components from a 2×2 covariance matrix and explain why the direction of largest variance need not be the most discriminative one.
- Place of the course
- State what separates pattern recognition from machine learning, computer vision, image processing and biometrics.
8.1What question does the course ask?
How do we decide from measurements which class an object belongs to?
Pattern recognition studies how to decide which class an object belongs to by looking at a feature vector extracted from measurements. The course treats the chain from sensor to decision as a whole: preprocessing, feature selection, classifier design and error analysis.
Two objects with the same measurement can belong to different classes: a screw 53.5 mm long may be good or defective. So pattern recognition is not a problem of finding a rule, but of deciding under uncertainty. The question is: given only the measurements, and knowing the chance of being wrong and the cost of being wrong, which class should we choose?
The course treats this question as a chain. A sensor takes a measurement; preprocessing removes noise; feature extraction reduces the measurement to a few discriminative numbers, the feature vector; a classifier looks at this vector and picks a class; evaluation counts the errors. Every link affects the result. If the features do not separate the classes, even the best classifier can do nothing; if the classes truly overlap, even the best decision errs at a certain rate.
8.1.1Feature space
d features span a d-dimensional space, and each example becomes a point in it. The classifier's job is to cut this space into class regions; the surface between the regions is the decision boundary. With two features it is a line or a curve, with three a surface, and beyond that we cannot see it but the same idea holds. The three core ideas of the course answer three questions: how to make the decision with the fewest errors (Bayes), how to classify a new point by looking at its neighbors (nearest neighbor), and what to do when the feature space is very large (dimensionality reduction).
8.1.2At a glance
| Criterion | Pattern Recognition |
|---|---|
| Approach | statistical decision theory |
| Input | measurement or feature vector |
| Output | class label |
| Success measure | classification error |
| Math load | medium-high: probability, linear algebra |
| Data needs | labeled examples |
8.2A short history
| Year | Milestone |
|---|---|
| 1936 | Fisher publishes linear discriminant analysis; the Iris data from that paper is still the first example. |
| 1962 | Hu introduces moment features invariant to translation, scale and rotation. |
| 1967 | Cover and Hart show that the nearest neighbor rule's error is at most twice the Bayes error. |
| 1973 | Duda and Hart publish the field's core textbook, "Pattern Classification and Scene Analysis". |
| 1991 | Turk and Pentland build face recognition on PCA with eigenfaces. |
| 1998 | LeCun et al. publish LeNet-5 and the MNIST handwritten digit dataset. |
8.3Core concepts
The rest of the course is built on the concepts below. The following sections work through the most important ones with examples.
| Concept | Meaning |
|---|---|
| Feature vector | Measurements that represent an object: length, color, texture. |
| Feature space | Each example is a point; classes are regions in this space. |
| Bayesian decision theory | Choose the class with the largest posterior; minimum error. |
| Decision boundary | The surface that splits feature space into class regions. |
| Density estimation | Parametric (Gaussian) or nonparametric (Parzen). |
| Nearest neighbor | Assign a new example to the class of the nearest labeled ones. |
| Dimensionality reduction | Few but discriminative features with PCA and LDA. |
| Confusion matrix | Shows which class is confused with which. |
8.4Bayesian decision theory: prior, likelihood and cost
Take two classes: good (G) and defective (D) screws. Before any measurement we already know something about the classes: what fraction of the screws on the line is defective? This is the prior probability. After the measurement our knowledge is updated, and Bayes' rule says how.
P(D | x) = P(x | D) · P(D) / P(x). P(D) is the prior, P(x | D) the likelihood (how ordinary the measurement x is in class D), and P(D | x) the posterior. The Bayes decision picks the class with the largest posterior; with two classes P(x) is the same on both sides, so we compare P(x | D)·P(D) with P(x | G)·P(G). Among all possible decision rules this one minimizes the expected error.
Good screws have mean length 50 mm and defective ones 56 mm; assume normal distributions with standard deviation 2 mm in both. 20% of the screws on the line are defective: P(D) = 0.2, P(G) = 0.8 (the values are illustrative). The measured length is x = 53.5 mm.
- Likelihood ratio. The exponent of the normal density is −(x − μ)2 / (2σ2), so for good screws it is 3.52/8 = 1.531 and for defective ones 2.52/8 = 0.781. The ratio is P(x|D)/P(x|G) = e1.531 − 0.781 = e0.75 ≈ 2.12: the measurement is about twice as ordinary for defective screws.
- Multiply by the prior. The posterior ratio is P(D|x)/P(G|x) = 2.12 · (0.2/0.8) ≈ 0.53.
- Posterior probability. P(D|x) = 0.53 / (1 + 0.53) ≈ 0.346, P(G|x) ≈ 0.654.
- Decision. To make as few errors as possible we say "good". With equal priors (0.5/0.5) the ratio would stay 2.12, P(D|x) ≈ 0.68, and we would say "defective".
- Cost. Let missing a defective screw be 5 times as costly as scrapping a good one. The expected loss of saying "good" is 5 · 0.346 ≈ 1.73, and of saying "defective" 1 · 0.654 ≈ 0.65. We pick the smaller loss: the decision is now "defective".
The same measurement led to different decisions when the prior and the cost changed. This is the real lesson of Bayesian theory: the decision depends not only on the measurement but on how common the classes are and what mistakes cost.
Because the two variances are equal here, the decision boundary is a single threshold: x* = (μG + μD)/2 + σ2/(μD − μG) · ln(P(G)/P(D)); if x > x* we say "defective". With equal priors and equal costs the threshold is the midpoint of the two means, 53 mm. With priors 0.8/0.2 it moves to 53 + (4/6) · ln 4 ≈ 53.92 mm, and adding the cost ratio of 5 moves it to 53 + (4/6) · ln(0.8) ≈ 52.85 mm. Because missing a defective screw is expensive the threshold goes down: shorter screws are suspected too.
Assuming the decision boundary is always the midpoint of the two class means. The midpoint is correct only when the classes are equally frequent and the errors equally costly. Above, the threshold came out at 53.92 mm, not 53 mm; the 53.5 mm screw was above the midpoint yet was classified "good". When the classes are imbalanced the threshold moves away from the common class and toward the rare one.
8.5The nearest-neighbor rule and distance
The Bayes decision needs the class distributions. In real problems we do not have distributions but labeled examples. The nearest-neighbor rule skips the estimation and looks straight at the examples: a new point is assigned to the class of the closest labeled example in feature space. In the k-nearest-neighbor (k-NN) rule we look at the closest k examples and pick the class that occurs most often among them. There is no training; all examples are stored and the distances are computed at decision time.
For two feature vectors a and b, d(a, b) = √( Σ (aj − bj)2 ). Other distances exist (Manhattan, Mahalanobis), but the decision always depends on what "close" measures.
Six labeled examples with two features: class A has (1, 1), (2, 1), (1, 3); class B has (4, 2), (5, 4), (4, 5). The point to classify is q = (3, 2).
- Distances. B(4,2): √(1 + 0) = 1; A(2,1): √(1 + 1) ≈ 1.41; A(1,1): √(4 + 1) ≈ 2.24; A(1,3): √(4 + 1) ≈ 2.24; B(5,4): √(4 + 4) ≈ 2.83; B(4,5): √(1 + 9) ≈ 3.16.
- k = 1. The nearest example is B(4,2); the decision is B.
- k = 3. The nearest three are B(4,2), A(2,1) and one of the A examples at distance 2.24; both are A. Two A, one B: the decision is A.
- k = 5. Three A (up to 2.24) and two B (at 1 and 2.83): the decision is again A.
The same point was classified differently depending on k. With k = 1 the decision hangs on a single neighbor, possibly a noisy one; as k grows the decision gets smoother. By the 1967 result of Cover and Hart, as the number of examples goes to infinity the error of the 1-NN rule is at most twice the Bayes error; so this simple rule gives a reasonable result even with no assumption about the distributions.
Choosing k is model selection: a very small k leads to overfitting, a very large k to oversmoothing. It is usually odd (to avoid ties) and chosen with a validation set or cross-validation, which are covered in the Machine Learning course.
Using features directly when their scales differ. Describe a person by age and income: the query is q = (30 years, 50,000); two examples are p1 = (60, 50,500) and p2 = (31, 56,000). Raw distances: d(q, p1) = √(302 + 5002) ≈ 501 and d(q, p2) = √(1 + 60002) ≈ 6000. The nearest is p1; the 30-year age gap is ignored only because the income numbers are large. If we divide each feature by its range (assume an age range of 50 and an income range of 80,000) the distances become √(0.62 + 0.006252) ≈ 0.60 and √(0.022 + 0.0752) ≈ 0.078, and now p2 is the nearest. In distance-based methods the features are scaled first.
8.6Feature space and dimensionality reduction: PCA
As the number of measurements grows, the feature space expands while the number of examples stays the same; examples become sparse and neighbors are no longer really close. This is the curse of dimensionality. The remedy is to reduce the number of features: either select the most useful ones, or extract a smaller number of new features as combinations of the old ones. The best-known method of the second kind is principal component analysis (PCA).
Rotates the data to the directions of largest variance. First the mean is subtracted; then the eigenvectors of the covariance matrix are found. An eigenvalue is the variance along its direction. The eigenvector with the largest eigenvalue is the first principal component. Projecting the data onto only the first few components reduces the dimension.
Five examples: (1,2), (2,3), (3,5), (4,4), (5,6).
- Mean. (3, 4). After subtracting it the deviations are (−2,−2), (−1,−1), (0,1), (1,0), (2,2).
- Covariance (dividing by n − 1 = 4): sxx = (4+1+0+1+4)/4 = 2.5; syy = (4+1+1+0+4)/4 = 2.5; sxy = (4+1+0+0+4)/4 = 2.25. The matrix is [[2.5, 2.25], [2.25, 2.5]].
- Eigenvalues. Since the diagonal entries are equal, λ = 2.5 ± 2.25: λ1 = 4.75, λ2 = 0.25. The eigenvectors are (1, 1)/√2 and (1, −1)/√2.
- Explained variance. 4.75 / (4.75 + 0.25) = 95%. Replacing the two features with one component keeps 95% of the variance.
- Projection. The values on the first component are (dx + dy)/√2: −2.83, −1.41, 0.71, 0.71, 2.83. The two-dimensional data became one number.
PCA does not look at labels. It finds the direction in which the data spreads, not the direction that separates the classes. A method that aims at separation is Fisher linear discriminant analysis (LDA), which looks for the direction that pushes the class means apart while shrinking the spread inside each class. The concepts of matrix, eigenvalue and eigenvector are treated in detail in the Linear Algebra course.
Believing that the direction of largest variance is the most discriminative one. Six points: class A (1,2), (3,4), (5,6), class B (2,1), (4,3), (6,5). The covariance matrix is [[3.5, 2.9], [2.9, 3.5]], the eigenvalues are 6.4 and 0.6, and the first component carries 91% of the variance. But along this direction (1,1)/√2 the two classes project to the same values (3, 7, 11 over √2 for both); the classes are completely mixed. The direction that separates them is (1,−1)/√2: always −1/√2 for A and +1/√2 for B. The component PCA throws away as "low variance" carries all the discriminative information here.
8.7How is the course taught?
8.7.1A typical workflow
A mail sorting machine scans the postcode on an envelope, binarizes the image and splits it into digits, extracts shape features from each digit, decides which digit it is with nearest neighbor or an SVM, and sends misread envelopes to manual sorting.
8.7.2Topics over the semester
- Recognition systems: sensing, features, decision
- Bayesian decision theory, risk and loss
- The normal distribution and discriminant functions
- Parameter estimation: maximum likelihood, Bayesian
- Nonparametric density estimation: Parzen windows
- Nearest-neighbor rule and distance measures
- Linear discriminants and the perceptron
- Support vector machines
- Feature extraction, selection, curse of dimensionality
- PCA and Fisher linear discriminant analysis (LDA)
- Evaluating and comparing classifiers
- Clustering and Gaussian mixture models
This is a typical semester; the order and coverage vary between universities.
8.7.3Skills you will gain
- designing features from measurements
- building a Bayes classifier
- k-NN and SVM with scikit-learn
- extracting image features with OpenCV
- error analysis with a confusion matrix
8.7.4Try it yourself
The Try It: Reject the Defective Part slide in the presentation lets you solve a typical problem of this course yourself: Every screw on the line is measured; defective ones are longer on average, but the distributions overlap. Change the defect rate and error cost to move the Bayes boundary; click the chart to measure a part.
8.8Are you ready for this course?
8.8.1Prerequisites
| Course | Why it is needed |
|---|---|
| Probability and Statistics | Bayesian decision theory, density estimation |
| Programming | arrays, loops and functions in Python or Java |
| Linear Algebra | vectors, distances, eigenvalues: the language of PCA and LDA |
8.8.2Ask yourself
For every "no", the right-hand column shows where to start. If you can say "yes" to most of them, you are ready.
| Question | If not, start with |
|---|---|
| Can you explain the normal distribution, mean and covariance? | Probability and Statistics |
| Can you explain Euclidean distance, eigenvalues and eigenvectors? | Linear Algebra |
| Can you find the minimum of a function by taking its derivative? | Derivatives and extrema from calculus |
| Can you load and process a dataset with NumPy arrays in Python? | An intro programming course, then a short NumPy tutorial |
8.9Neighboring courses
8.9.1Where it overlaps
| Relation | Course | Shared ground |
|---|---|---|
| builds on | This course builds on Probability and Statistics | Bayesian decision theory, density estimation |
| application | Biometric Systems applies the methods of this course | matching, verification and identification |
| shares methods | Shares methods with Machine Learning | classifiers, decision boundaries |
| shares methods | Shares methods with Image Processing | feature extraction, template matching |
| shares methods | Shares methods with Computer Vision | object classification |
8.9.2Where it differs
- Machine Learning: ML studies learning algorithms in general; this course focuses on the design from measurement to class decision and on the Bayes error.
- Computer Vision: Computer vision tries to understand the scene in an image; this course treats class decisions from any kind of measurement.
- Image Processing: Image processing enhances and transforms images, and the result is still an image; this course outputs a class label.
- Biometric Systems: Biometrics is an application of pattern recognition; this course teaches general decision methods, not person-specific ones.
8.10In practice
8.10.1Applications
| Area | What is done |
|---|---|
| Handwriting recognition | Reading postcodes, bank checks and forms. |
| Optical character recognition | Turning a scanned document into editable text. |
| Face and fingerprint | Identity verification and identification. |
| Industrial inspection | Rejecting defective products on the line. |
| Medical diagnosis | Classifying ECGs, blood tests or tissue samples. |
| Speaker recognition | Finding out who is speaking from the voice. |
8.10.2Risks and ethics
| Risk | Explanation |
|---|---|
| Face recognition without consent | Face recognition enables covert tracking; Clearview AI was fined in several European countries for faces scraped from the internet. |
| Error gaps between groups | In the Gender Shades study, commercial gender classifiers erred far more often on darker-skinned women than on lighter-skinned men. |
| Treating all errors alike | If a missed cancer weighs the same as a false alarm, total error looks low while outcomes are dangerous; choose the loss matrix with care. |
| Leakage in feature selection | Selecting features on the full dataset and then cross-validating makes the error look far lower than it really is. |
These issues are discussed in depth in Explainable AI and AI Ethics.
8.10.3Tools and datasets
Tools: scikit-learn, NumPy, OpenCV, MATLAB Statistics and ML Toolbox, Weka, PRTools.
Well-known datasets: Iris, MNIST, Optical Recognition of Handwritten Digits (UCI), Wisconsin Breast Cancer, AT&T (ORL) face dataset, EMNIST.
8.11Common misconceptions
Pattern recognition is the old name for machine learning.
The two overlap heavily; pattern recognition is an engineering view that also covers sensing and feature design.
Choosing the classifier is the key step.
In most problems feature selection decides success; a good classifier cannot rescue bad features.
With the right features the error drops to zero.
If classes overlap, even the best decision errs as much as the Bayes error.
The more features, the better.
As dimension grows, examples become sparse (the curse of dimensionality); useless features hurt performance.
8.12Summary
- Pattern recognition extracts a feature vector from a measurement and decides a class; the chain is sensing, preprocessing, feature extraction, classification and evaluation.
- The Bayes decision picks the class with the largest posterior; the posterior is proportional to likelihood times prior, and error costs shift the decision boundary.
- If the classes overlap even the best decision errs; this lower bound is the Bayes error.
- The nearest-neighbor rule looks straight at labeled examples without knowing the distributions; the result depends on k and on the distance, hence on the scale of the features.
- As the number of features grows, examples become sparse (the curse of dimensionality); PCA reduces to the directions that keep variance, but it does not guarantee the direction that separates the classes.
8.13Test Yourself
10% of the screws on the line are defective. A test flags a defective screw as "defective" with probability 90% and a good screw as "defective" with probability 20%. A screw is flagged "defective"; what is the probability that it really is defective?
Answer
Bayes' rule: P(D|+) = 0.9 · 0.1 / (0.9 · 0.1 + 0.2 · 0.9) = 0.09 / 0.27 = 1/3. Although the test looks good, defective screws are rare, so only a third of the flagged screws are really defective.
Let the class means be 10 (good) and 14 (defective), both with standard deviation 2. The priors are 0.9 (good) and 0.1 (defective). Find the Bayes decision threshold. What would it be with equal priors?
Answer
With equal priors the threshold is the midpoint of the means: 12. With priors 0.9/0.1, x* = 12 + (4/4) · ln(0.9/0.1) = 12 + ln 9 ≈ 14.20. The threshold is even above the defective mean (14): good screws are so numerous that a measurement of 14 is still decided "good".
For the six-point data of the second section, classify q = (3, 2) with k = 1 and k = 5.
Answer
Distance order: B(4,2) 1; A(2,1) 1.41; A(1,1) and A(1,3) 2.24; B(5,4) 2.83; B(4,5) 3.16. k = 1: B. k = 5: three A, two B; the decision is A. The choice of k changed the decision.
Find the eigenvalues and the variance fraction explained by the first component for data with covariance matrix [[3, 1], [1, 3]].
Answer
The diagonal entries are equal, so λ = 3 ± 1: 4 and 2 (eigenvectors (1,1)/√2 and (1,−1)/√2). The fraction is 4 / (4 + 2) = 2/3 ≈ 66.7%. With one component a third of the variance is lost.
The features of both classes come from the same distribution, and the priors are 0.7 and 0.3. What is the lower bound on the expected error for any classifier?
Answer
The measurement says nothing about the class, so the best decision is always to pick the common class; the error is 0.3. This is the Bayes error: when classes overlap completely, no method can do better.
A student first looks at all the data, picks the 20 features most correlated with the class out of 1000, and then runs cross-validation with these 20 features and reports the error. Why is this misleading?
Answer
Feature selection used the labels and also saw the test folds; in every fold of the cross-validation the test data had leaked into the selection, so the error comes out lower than it really is. Selection must be done inside each fold, on the training part only.
8.14After this course
Pattern recognition is the shared core of computer vision, speech recognition and biometrics. After this course you can move to a sensing area (vision, audio, biometrics) or go on to deep learning, which also learns the features from data.
Courses that build on or extend this one: Biometric Systems.
Related careers: Image and signal processing engineer, Machine learning engineer, Biometrics specialist, Quality inspection systems engineer.
8.15Further reading
- R. O. Duda, P. E. Hart and D. G. Stork, Pattern Classification (2nd ed., 2001): covers the topics of this note at textbook level, from Bayesian decision theory to nearest neighbor and PCA.
- C. M. Bishop, Pattern Recognition and Machine Learning (2006): builds the probabilistic view more broadly; a good next step for Bayesian methods and mixture models.
- S. Theodoridis and K. Koutroumbas, Pattern Recognition (4th ed., 2009): treats classifiers, feature selection and clustering from an engineering viewpoint.
8.16References
- Duda, Hart and Stork, Pattern Classification, 2nd ed., Wiley, 2001.
- Bishop, Pattern Recognition and Machine Learning, Springer, 2006.
- Theodoridis and Koutroumbas, Pattern Recognition, 4th ed., Academic Press, 2009.
- Fukunaga, Introduction to Statistical Pattern Recognition, 2nd ed., Academic Press, 1990.
Related pages: Slides · Slides (PDF) · Course page