Lecture 15: Anomaly Detection
Learn about anomaly detection algorithms, Gaussian distribution modeling, evaluation metrics, feature engineering, and multivariate Gaussian distributions for detecting outliers.
Anomaly Detection - Problem Motivation
Anomaly detection is a widely used application of machine learning. Although it can be viewed primarily as a solution to an unsupervised learning problem, it also incorporates key aspects of supervised learning.
What is Anomaly Detection?
To understand anomaly detection, consider an aircraft engine manufacturer performing quality assurance (QA) as engines roll off the assembly line:
- Feature Measurement: For each engine, measure specific features such as heat generated () and vibration intensity ().
- Dataset: This yields a dataset of unlabeled features representing tested engines.

When a new engine () is produced on the next day, an anomaly detection algorithm is applied to determine if it is anomalous compared to previously manufactured engines.
- If falls within the dense region of previous data, it is classified as normal (OK).

- If falls far outside the main cluster, it is flagged as anomalous.

Formal Model Formulation
Given a dataset of normal examples (in practice, it is acceptable if a tiny fraction of anomalous data is present in the training set):
- Density Estimation: Build a probabilistic model representing the probability density that a given example is normal.
- Decision Rule: For a new test example :
- If
- If
Here, represents a chosen threshold probability value determining how strict the system is in flagging anomalies.

Applications of Anomaly Detection
Fraud Detection
- Features: User behavior parameters such as online session duration, login location, transaction frequency, and spending patterns.
- Method: Build a model of normal user behavior.
- Action: Identify unusual behavior patterns by passing new session data through . Flag suspicious accounts or automatically block fraudulent card transactions.
Manufacturing
- Quality assurance checks for manufactured components (e.g., aircraft engines, semiconductor microchips).
Data Center Computer Monitoring
- System Features: Monitor computers in a server cluster:
- Memory usage
- Disk accesses per second
- CPU load
- Engineered Features: Define composite features such as .
- Action: Detect anomalous machines that may be failing or behaving erratically before a catastrophic cluster failure occurs.
Gaussian (Normal) Distribution
Anomaly detection heavily relies on the Gaussian (Normal) distribution.
Properties of 1D Gaussian
For a real-valued random variable , if follows a Gaussian distribution with mean and variance (standard deviation ), we write:
The probability density function is defined as:


Impact of Parameters and
- The total area under the probability density curve always equals .
- The mean specifies the center peak of the distribution.
- The standard deviation specifies the spread/width of the curve. Smaller creates a tall, narrow peak, while larger creates a wider, flatter curve.

Parameter Estimation Problem
Given an unlabeled dataset of real-valued scalar examples :

If we suspect these examples were generated from a Gaussian distribution, we can estimate the parameters and :

Maximum Likelihood Estimation Formulas

Note: In statistics, using instead of yields an unbiased estimate of variance. However, in machine learning, is standard; for large , the numerical difference is negligible.
Anomaly Detection Algorithm
Model Formulation
Given an unlabeled training set of examples where each example is an -dimensional feature vector.
Assuming each feature is independently distributed according to a Gaussian distribution , the joint probability is modeled as the product of individual Gaussian densities:

Algorithm Steps

- Feature Selection: Choose features indicative of general properties of the system.
- Fit Parameters: Calculate and for each feature :
- Evaluate Test Point: For a new test example , compute :
- Flag Anomaly: If , flag the example as an anomaly.
2D Example Walkthrough
Consider a 2D dataset with features and :
- : Mean , standard deviation
- : Mean , standard deviation

Plotting the individual feature distributions:

Multiplying the probabilities yields a 3D surface plot of :

For new test examples:
- (normal region):
- (outlier region):
Developing and Evaluating an Anomaly Detection System
Having a real-number evaluation metric is critical for rapidly making decisions about feature engineering, parameter choices, and model selection.
Dataset Split with Labeled Data
Even though anomaly detection is an unsupervised learning problem, having a small amount of labeled data ( for normal, for anomalous) allows for model evaluation.
Suppose we have 10,000 normal engines () and 20 anomalous engines (). A recommended split is:
- Training set: 6,000 normal engines (). Used to fit . (A few minor anomalies in the training set do not significantly degrade performance).
- Cross-Validation (CV) set: 2,000 normal engines (), 10 anomalous engines ().
- Test set: 2,000 normal engines (), 10 anomalous engines ().
Note: Avoid putting the same anomalous examples in both the CV and Test sets.
Evaluation Metrics
Because is overwhelmingly predominant (highly skewed dataset), standard classification accuracy is a poor metric. Instead, use:
- True Positive, False Positive, False Negative, True Negative counts
- Precision and Recall
- -score:
Use the cross-validation set to tune the threshold parameter by selecting the value that maximizes the -score. Afterwards, evaluate the finalized model on the test set.
Anomaly Detection vs. Supervised Learning
When labeled data is available, choosing between anomaly detection and supervised learning depends on the dataset characteristics:
| Feature / Property | Anomaly Detection | Supervised Learning |
|---|---|---|
| Positive Examples () | Very small number (0–20 positive examples). | Large number of positive examples. |
| Negative Examples () | Very large number of negative examples. | Large number of negative examples. |
| Nature of Anomalies | Many different "types" of anomalies. Hard for an algorithm to learn what anomalies look like from a few examples; future anomalies may look completely different from past ones ("unknown unknowns"). | Enough positive examples for the algorithm to learn patterns of positive instances. Future positive examples are expected to resemble training positive examples. |
| Typical Applications | • Fraud detection • Aircraft engine manufacturing QA • Data center machine monitoring | • Email spam classification • Weather prediction • Cancer classification |
Choosing What Features to Use
Feature engineering significantly impacts anomaly detection performance.
Non-Gaussian Features
Plot a histogram of each feature (hist command in MATLAB/Octave) to verify whether it follows a Gaussian distribution.

If a feature is heavily skewed, apply logarithmic or power transformations to make it more Gaussian:

Error Analysis for Anomaly Detection
- Run the trained algorithm on the cross-validation set.
- Identify false negatives (anomalous examples where ).
- Analyze why the algorithm assigned a high probability to the anomalous example.
- Create a new feature that isolates the anomaly.

For example, in server monitoring, if a machine experiences unusually high CPU load while disk accesses are low, single-feature Gaussians might view both values as normal independently. Defining a new combined feature or helps highlight such anomalies.
Multivariate Gaussian Distribution
Motivation
Consider an unlabeled dataset where two features ( = CPU load, = memory usage) are positively correlated:

Suppose an anomalous test point occurs at :

Individually, is within normal range, and is within normal range. However, their combination is highly unusual.
The original independent Gaussian model evaluates , which forms axis-aligned concentric circular/elliptical contours:

Because the concentric circles treat the green anomalous point as having the same probability density as normal points on the outer ring, the original model fails to detect the anomaly.
Mathematical Formulation
To capture feature correlations directly, use the Multivariate Gaussian Distribution.
Instead of modeling separately, model jointly in one step using parameters:
- Mean vector
- Covariance matrix
The probability density function is:

Where denotes the determinant of matrix (det(sigma) in MATLAB).
![]()
Visualizing the Effects of and
-
Standard Identity Covariance (): Symmetric bell curve centered at .


-
Shrinking Diagonal Elements (): The distribution becomes narrower and taller while maintaining axis symmetry.


-
Asymmetric Diagonal Elements: Varying individual diagonal entries alters variance along specific feature axes.

-
Off-Diagonal Elements (Correlation): Non-zero off-diagonal elements orient the elliptical contours along diagonal angles, modeling positive or negative feature correlations.

-
Shifting Mean : Modifying translates the peak location across the feature space.
Anomaly Detection Algorithm with Multivariate Gaussian
Parameter Estimation
Given dataset :

-
Mean Vector :

-
Covariance Matrix :

Algorithm Steps
-
Fit parameters and on the training set.
-
For a new test example :

Compute using the multivariate Gaussian density function:

-
Flag an anomaly if .
Applying Multivariate Gaussian fitting creates non-axis-aligned elliptical contours that accurately isolate the correlated anomaly:

Equivalence to Original Model
The original independent Gaussian model is a special case of the multivariate Gaussian model where the covariance matrix is constrained to be diagonal:

Original Model vs. Multivariate Gaussian Model
| Property | Original Gaussian Model | Multivariate Gaussian Model |
|---|---|---|
| Correlation Handling | Must manually create features (e.g., ) to capture anomalies where features take unusual combinations. | Automatically captures feature correlations without manual feature engineering. |
| Computational Cost | Computationally cheap: time complexity. Scales extremely well to huge feature dimensions (e.g., ). | Computationally expensive: Requires computing matrix inverse which is . Inefficient when is very large. |
| Sample Size Requirements | Works well even with small training set sizes (e.g., ). | Requires (number of examples strictly greater than number of features). Otherwise, is singular/non-invertible. |
| Non-Invertibility Issues | Not susceptible to matrix non-invertibility. | is non-invertible if: 1. 2. Redundant (linearly dependent) features exist (e.g., ). Solve by removing redundant features or applying PCA. |
| Usage | Most commonly used in practice due to efficiency and scalability. | Used when feature correlations are critical and . |
Lecture 14: Dimensionality Reduction
A comprehensive guide to dimensionality reduction techniques, focusing on Principal Component Analysis (PCA), data compression, visualization, mathematical formulation, algorithm implementation, reconstruction, and practical guidance.
Lecture 16: Recommender Systems
An introduction to recommender systems, including content-based recommendation methods, collaborative filtering algorithms, low-rank matrix factorization, and mean normalization.