CSE-41XX
CS-4125 ML

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 (x1x_1) and vibration intensity (x2x_2).
  • Dataset: This yields a dataset of unlabeled features {x(1),x(2),,x(m)}\{x^{(1)}, x^{(2)}, \dots, x^{(m)}\} representing mm tested engines.

Aircraft engine feature plot: heat vs vibration

When a new engine (xtestx_{\text{test}}) is produced on the next day, an anomaly detection algorithm is applied to determine if it is anomalous compared to previously manufactured engines.

  • If xtestx_{\text{test}} falls within the dense region of previous data, it is classified as normal (OK).

Normal new engine data point near main cluster

  • If xtestx_{\text{test}} falls far outside the main cluster, it is flagged as anomalous.

Anomalous new engine data point far from cluster

Formal Model Formulation

Given a dataset of normal examples {x(1),x(2),,x(m)}\{x^{(1)}, x^{(2)}, \dots, x^{(m)}\} (in practice, it is acceptable if a tiny fraction of anomalous data is present in the training set):

  1. Density Estimation: Build a probabilistic model p(x)p(x) representing the probability density that a given example xx is normal.
  2. Decision Rule: For a new test example xtestx_{\text{test}}:
    • If p(xtest)<ϵ    Flag as anomalyp(x_{\text{test}}) < \epsilon \implies \text{Flag as anomaly}
    • If p(xtest)ϵ    OK (Normal)p(x_{\text{test}}) \ge \epsilon \implies \text{OK (Normal)}

Here, ϵ\epsilon represents a chosen threshold probability value determining how strict the system is in flagging anomalies.

2D Gaussian probability density contours for anomaly detection


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 p(x)p(x) of normal user behavior.
  • Action: Identify unusual behavior patterns by passing new session data through p(x)p(x). 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 mm computers in a server cluster:
    • x1=x_1 = Memory usage
    • x2=x_2 = Disk accesses per second
    • x3=x_3 = CPU load
  • Engineered Features: Define composite features such as x4=CPU loadnetwork trafficx_4 = \frac{\text{CPU load}}{\text{network traffic}}.
  • 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 xRx \in \mathbb{R}, if xx follows a Gaussian distribution with mean μ\mu and variance σ2\sigma^2 (standard deviation σ\sigma), we write:

xN(μ,σ2)x \sim \mathcal{N}(\mu, \sigma^2)

The probability density function is defined as:

p(x;μ,σ2)=12πσexp((xμ)22σ2)p(x; \mu, \sigma^2) = \frac{1}{\sqrt{2\pi}\sigma} \exp\left( -\frac{(x - \mu)^2}{2\sigma^2} \right)

Gaussian normal distribution bell curve

Gaussian probability density function formula

Impact of Parameters μ\mu and σ2\sigma^2

  • The total area under the probability density curve always equals 11.
  • The mean μ\mu specifies the center peak of the distribution.
  • The standard deviation σ\sigma specifies the spread/width of the curve. Smaller σ\sigma creates a tall, narrow peak, while larger σ\sigma creates a wider, flatter curve.

Effect of mean and variance parameters on Gaussian distributions


Parameter Estimation Problem

Given an unlabeled dataset of mm real-valued scalar examples {x(1),x(2),,x(m)}\{x^{(1)}, x^{(2)}, \dots, x^{(m)}\}:

1D dataset points on x-axis

If we suspect these examples were generated from a Gaussian distribution, we can estimate the parameters μ\mu and σ2\sigma^2:

Gaussian distribution fitted to 1D dataset

Maximum Likelihood Estimation Formulas

μ=1mi=1mx(i)\mu = \frac{1}{m} \sum_{i=1}^{m} x^{(i)} σ2=1mi=1m(x(i)μ)2\sigma^2 = \frac{1}{m} \sum_{i=1}^{m} (x^{(i)} - \mu)^2

Formulas for estimating Gaussian mean mu and variance sigma squared

Note: In statistics, using 1m1\frac{1}{m-1} instead of 1m\frac{1}{m} yields an unbiased estimate of variance. However, in machine learning, 1m\frac{1}{m} is standard; for large mm, the numerical difference is negligible.


Anomaly Detection Algorithm

Model Formulation

Given an unlabeled training set of mm examples {x(1),x(2),,x(m)}\{x^{(1)}, x^{(2)}, \dots, x^{(m)}\} where each example xRnx \in \mathbb{R}^n is an nn-dimensional feature vector.

Assuming each feature xjx_j is independently distributed according to a Gaussian distribution xjN(μj,σj2)x_j \sim \mathcal{N}(\mu_j, \sigma_j^2), the joint probability p(x)p(x) is modeled as the product of individual Gaussian densities:

p(x)=p(x1;μ1,σ12)p(x2;μ2,σ22)p(xn;μn,σn2)=j=1np(xj;μj,σj2)p(x) = p(x_1; \mu_1, \sigma_1^2) \cdot p(x_2; \mu_2, \sigma_2^2) \cdot \dots \cdot p(x_n; \mu_n, \sigma_n^2) = \prod_{j=1}^{n} p(x_j; \mu_j, \sigma_j^2)

Product notation for combined feature Gaussian probability model

Algorithm Steps

Anomaly detection algorithm steps summary

  1. Feature Selection: Choose features xjx_j indicative of general properties of the system.
  2. Fit Parameters: Calculate μj\mu_j and σj2\sigma_j^2 for each feature j=1,,nj = 1, \dots, n: μj=1mi=1mxj(i)\mu_j = \frac{1}{m} \sum_{i=1}^{m} x_j^{(i)} σj2=1mi=1m(xj(i)μj)2\sigma_j^2 = \frac{1}{m} \sum_{i=1}^{m} (x_j^{(i)} - \mu_j)^2
  3. Evaluate Test Point: For a new test example xtestx_{\text{test}}, compute p(xtest)p(x_{\text{test}}): p(xtest)=j=1np(xj,test;μj,σj2)p(x_{\text{test}}) = \prod_{j=1}^{n} p(x_{j,\text{test}}; \mu_j, \sigma_j^2)
  4. Flag Anomaly: If p(xtest)<ϵp(x_{\text{test}}) < \epsilon, flag the example as an anomaly.

2D Example Walkthrough

Consider a 2D dataset with features x1x_1 and x2x_2:

  • x1x_1: Mean μ15\mu_1 \approx 5, standard deviation σ12\sigma_1 \approx 2
  • x2x_2: Mean μ23\mu_2 \approx 3, standard deviation σ21\sigma_2 \approx 1

2D dataset feature values and parameter estimations

Plotting the individual feature distributions:

Individual Gaussian distributions for feature 1 and feature 2

Multiplying the probabilities yields a 3D surface plot of p(x)p(x):

3D surface plot of combined 2D Gaussian probability density p(x)

For new test examples:

  • xtest(1)x_{\text{test}}^{(1)} (normal region): p(xtest(1))=0.436ϵ    Normalp(x_{\text{test}}^{(1)}) = 0.436 \ge \epsilon \implies \text{Normal}
  • xtest(2)x_{\text{test}}^{(2)} (outlier region): p(xtest(2))=0.0021<ϵ    Anomalousp(x_{\text{test}}^{(2)}) = 0.0021 < \epsilon \implies \text{Anomalous}

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 (y=0y = 0 for normal, y=1y = 1 for anomalous) allows for model evaluation.

Suppose we have 10,000 normal engines (y=0y = 0) and 20 anomalous engines (y=1y = 1). A recommended split is:

  • Training set: 6,000 normal engines (y=0y = 0). Used to fit p(x)p(x). (A few minor anomalies in the training set do not significantly degrade performance).
  • Cross-Validation (CV) set: 2,000 normal engines (y=0y = 0), 10 anomalous engines (y=1y = 1).
  • Test set: 2,000 normal engines (y=0y = 0), 10 anomalous engines (y=1y = 1).

Note: Avoid putting the same anomalous examples in both the CV and Test sets.

Evaluation Metrics

Because y=0y = 0 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
  • F1F_1-score: F1=2PrecisionRecallPrecision+RecallF_1 = 2 \cdot \frac{\text{Precision} \cdot \text{Recall}}{\text{Precision} + \text{Recall}}

Use the cross-validation set to tune the threshold parameter ϵ\epsilon by selecting the value that maximizes the F1F_1-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 / PropertyAnomaly DetectionSupervised Learning
Positive Examples (y=1y=1)Very small number (0–20 positive examples).Large number of positive examples.
Negative Examples (y=0y=0)Very large number of negative examples.Large number of negative examples.
Nature of AnomaliesMany 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.

Non-Gaussian right-skewed feature distribution histogram

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

  • x1log(x1)x_1 \to \log(x_1)
  • x1log(x1+c)x_1 \to \log(x_1 + c)
  • x1x1=x11/2x_1 \to \sqrt{x_1} = x_1^{1/2}
  • x1x11/3x_1 \to x_1^{1/3}

Logarithmic transformation resulting in Gaussian-like distribution

Error Analysis for Anomaly Detection

  1. Run the trained algorithm on the cross-validation set.
  2. Identify false negatives (anomalous examples where p(x)ϵp(x) \ge \epsilon).
  3. Analyze why the algorithm assigned a high probability to the anomalous example.
  4. Create a new feature that isolates the anomaly.

Anomalous point hidden in 1D projection

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 x4=CPU loadnetwork trafficx_4 = \frac{\text{CPU load}}{\text{network traffic}} or x5=CPU load2network trafficx_5 = \frac{\text{CPU load}^2}{\text{network traffic}} helps highlight such anomalies.


Multivariate Gaussian Distribution

Motivation

Consider an unlabeled dataset where two features (x1x_1 = CPU load, x2x_2 = memory usage) are positively correlated:

Unlabeled 2D dataset showing positive correlation between features

Suppose an anomalous test point occurs at x1=0.4,x2=1.5x_1 = 0.4, x_2 = 1.5:

Anomalous point with normal individual feature values

Individually, x1=0.4x_1 = 0.4 is within normal range, and x2=1.5x_2 = 1.5 is within normal range. However, their combination is highly unusual.

The original independent Gaussian model evaluates p(x)=p(x1)p(x2)p(x) = p(x_1)p(x_2), which forms axis-aligned concentric circular/elliptical contours:

Concentric circular contours failing to isolate correlated outlier

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 p(x1),p(x2),p(x_1), p(x_2), \dots separately, model p(x)p(x) jointly in one step using parameters:

  • Mean vector μRn\mu \in \mathbb{R}^n
  • Covariance matrix ΣRn×n\Sigma \in \mathbb{R}^{n \times n}

The probability density function is:

p(x;μ,Σ)=1(2π)n/2Σ1/2exp(12(xμ)TΣ1(xμ))p(x; \mu, \Sigma) = \frac{1}{(2\pi)^{n/2} |\Sigma|^{1/2}} \exp\left( -\frac{1}{2} (x - \mu)^T \Sigma^{-1} (x - \mu) \right)

Multivariate Gaussian distribution probability density formula

Where Σ|\Sigma| denotes the determinant of matrix Σ\Sigma (det(sigma) in MATLAB).

Covariance matrix determinant det(Sigma) explanation

Visualizing the Effects of Σ\Sigma and μ\mu

  1. Standard Identity Covariance (Σ=[1001]\Sigma = \begin{bmatrix} 1 & 0 \\ 0 & 1 \end{bmatrix}): Symmetric bell curve centered at μ=[00]\mu = \begin{bmatrix} 0 \\ 0 \end{bmatrix}.

    2D Multivariate Gaussian with identity covariance matrix

    3D surface plot of symmetric 2D Multivariate Gaussian

  2. Shrinking Diagonal Elements (Σ=[0.6000.6]\Sigma = \begin{bmatrix} 0.6 & 0 \\ 0 & 0.6 \end{bmatrix}): The distribution becomes narrower and taller while maintaining axis symmetry.

    Shrinking covariance matrix values along diagonal

    Narrower and taller 3D surface plot from smaller variance

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

    Asymmetric variance changes altering Gaussian contour shape

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

    Varying off-diagonal covariance entries to model positive and negative correlations

  5. Shifting Mean μ\mu: Modifying μ\mu translates the peak location across the feature space.


Anomaly Detection Algorithm with Multivariate Gaussian

Parameter Estimation

Given dataset {x(1),x(2),,x(m)}\{x^{(1)}, x^{(2)}, \dots, x^{(m)}\}:

Multivariate Gaussian model equation for anomaly detection

  1. Mean Vector μ\mu:

    μ=1mi=1mx(i)\mu = \frac{1}{m} \sum_{i=1}^{m} x^{(i)}

    Multivariate Gaussian mean vector parameter estimation formula

  2. Covariance Matrix Σ\Sigma:

    Σ=1mi=1m(x(i)μ)(x(i)μ)T\Sigma = \frac{1}{m} \sum_{i=1}^{m} (x^{(i)} - \mu)(x^{(i)} - \mu)^T

    Multivariate Gaussian covariance matrix parameter estimation formula

Algorithm Steps

  1. Fit parameters μ\mu and Σ\Sigma on the training set.

  2. For a new test example xtestx_{\text{test}}:

    Testing new example xtest in Multivariate Gaussian model

    Compute p(xtest)p(x_{\text{test}}) using the multivariate Gaussian density function:

    Computing probability p(xtest) with Multivariate Gaussian density function

  3. Flag an anomaly if p(xtest)<ϵp(x_{\text{test}}) < \epsilon.

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

Elliptical contour plot of Multivariate Gaussian correctly identifying anomaly

Equivalence to Original Model

The original independent Gaussian model is a special case of the multivariate Gaussian model where the covariance matrix Σ\Sigma is constrained to be diagonal:

Σ=[σ12000σ22000σn2]\Sigma = \begin{bmatrix} \sigma_1^2 & 0 & \dots & 0 \\ 0 & \sigma_2^2 & \dots & 0 \\ \vdots & \vdots & \ddots & \vdots \\ 0 & 0 & \dots & \sigma_n^2 \end{bmatrix}

Diagonal covariance matrix showing equivalence of original model as special case


Original Model vs. Multivariate Gaussian Model

PropertyOriginal Gaussian ModelMultivariate Gaussian Model
Correlation HandlingMust manually create features (e.g., x4=x1x2x_4 = \frac{x_1}{x_2}) to capture anomalies where features take unusual combinations.Automatically captures feature correlations without manual feature engineering.
Computational CostComputationally cheap: O(n)O(n) time complexity. Scales extremely well to huge feature dimensions (e.g., n=100,000n = 100,000).Computationally expensive: Requires computing matrix inverse Σ1\Sigma^{-1} which is O(n3)O(n^3). Inefficient when nn is very large.
Sample Size RequirementsWorks well even with small training set sizes (e.g., m=50,100m = 50, 100).Requires m>nm > n (number of examples strictly greater than number of features). Otherwise, Σ\Sigma is singular/non-invertible.
Non-Invertibility IssuesNot susceptible to matrix non-invertibility.Σ\Sigma is non-invertible if:
1. m<nm < n
2. Redundant (linearly dependent) features exist (e.g., x1=x2x_1 = x_2). Solve by removing redundant features or applying PCA.
UsageMost commonly used in practice due to efficiency and scalability.Used when feature correlations are critical and mnm \gg n.

On this page