Unit 7 of 8 · about 3 hours · explain, measure

Outlier and novelty detection, thresholds and representation

Anomaly scores spend budgets: each alert costs review time. A threshold without a policy and a score without a representation note cannot be operated.

You'll be able to

  • Separate outlier detection on dirty training data from novelty detection on clean training data with new points.
  • Set thresholds from contamination policy or score percentiles and report the implied alert rate.
  • Show that every anomaly score depends on representation: scaling, PCA width and kernel change the ranking.

Covers

Outlier versus novelty detection and threshold policyRepresentation dependence of anomaly scores
1

Read

In this order, only the parts listed

0 of 2 done

  1. Density thresholds and representation-dependent anomaliesHands-On Machine Learning with Scikit-Learn and PyTorch - dimensionality reduction and unsupervised learning

    Book Chapter 8: Using Gaussian Mixtures for Anomaly Detection (printed pp. 274-275) and Exercises 12 and 13 (p. 281). Notebook 08 cells: Anomaly Detection Using Gaussian Mixtures: the 2 percent density rule via percentile on score_samples; Exercises 12 and 13: GMM on PCA-reduced Olivetti faces with sampling and rotated, flipped and darkened anomaly checks, plus the PCA reconstruction-error detector

  2. Novelty versus outlier contract and detectorsscikit-learn - decomposition, clustering and outlier detection

    2.7 Novelty and Outlier Detection: outlier versus novelty definitions, contamination, offset_, decision_function sign and predict labels; 2.7.2 novelty prediction on new data; 2.7.3 EllipticEnvelope robust covariance, IsolationForest path lengths and LOF local density with its fit_predict-only default; 2.7.4 novelty detection with LOF (novelty=True)

2

Focus on

  • Outlier methods fit on polluted data; novelty methods fit on clean data and judge new points. LOF with novelty=False has no predict for new data; refit with novelty=True.
  • contamination sets the score cutoff as a percentile through offset_. It declares the alert rate; it does not discover it.
  • IsolationForest isolates with random feature splits; anomalies need fewer splits. In the paper's score, near 1 means anomaly, well below 0.5 means normal, and all scores near 0.5 mean no distinct anomaly; scikit-learn's score_samples returns the negative. Trees stop at depth for samples per tree.
  • Rescale or re-encode and the ranking changes: LOF neighborhoods, elliptic envelopes and GMM densities all live in the given coordinates.
Common mistakes · 3
  • Tuning contamination until the known incident appears, then reporting the hit as detection. The threshold was fit to the answer; hold it fixed or cross-check on other windows.
  • Calling LOF fit_predict on a deployment batch. With novelty=False the batch is judged against itself, not against clean history, and predict does not exist. Fit on clean data with novelty=True, then call predict on new points.
  • Comparing raw score_samples across models or scalings. Scores are model-and-coordinate specific; compare ranks or calibrated alert rates.
3

Try it yourself

Closed-book, before checking anything

Closed-book, fit IsolationForest with contamination=0.25 and random_state=42 on : predict gives [1,1,1,-1] with only the last decision_function negative. State the implied alert rate and why the cutoff is a policy.
4

Quiz yourself

Answer first, then mark it. Missed ones go to Review.

0 got · 0 missed

  1. 1.Training data is clean and the task judges next week points. Outlier or novelty setup?Answer

    Novelty: fit on clean history and predict new points. An outlier setup would fit the polluted batch including the points under test.

  2. 2.contamination=0.25 on 100 training points. How many train alerts, and what does offset_ do?Answer

    About 25: offset_ is the score percentile implementing that rate. It does not estimate the true anomaly fraction.

  3. 3.Standardizing a skewed sensor channel shuffles LOF rankings. Is that a bug?Answer

    No. LOF compares local densities in the given units; rescaling rewrites every neighborhood. Record scaling as part of the detector.

  4. 4.A GMM 2 percent rule flags a new batch at 9 percent. What do you report?Answer

    The flag rate rose from 2 to 9 percent, 4.5 times, under a fixed threshold. Report the shift with counts and slices before touching the threshold.

5

Practice

  • Deep-ML 367: Implement Isolation Forest for Anomaly Detection

    Problem 367: implement isolation_forest(X, n_trees, sample_size, random_state) with random feature and uniform-split trees, depth cap ceil(log2(sample_size)) and BST-normalized scores

    The tests check rounded score vectors on a 5-point set with one outlier at random_state=42 and a tight cluster at random_state=123. They match only the learn section's recipe taken literally: np.random.seed, legacy np.random calls, and for every leaf size above 1, so is about 0.154. The paper and scikit-learn set , which fails these vectors; note that difference rather than treating it as a bug.

You're done when

You match both Deep-ML score vectors, reproduce the [1,1,1,-1] contamination demo, and can flip a detector between outlier and novelty setups with the right predict calls.

Only when you can do this without notes.

Leads to

Notes

Resources · 2 for this unit, 6 more in the section

Also in this section

  • ISLP - Unsupervised LearningJames, Witten, Hastie, Tibshirani and Taylor · required

    Use Chapter 12 and its Python lab for the PCA derivations (12.2, including the low-rank approximation view and proportion of variance explained) and k-means (12.4.1), plus stability and interpretation limits, beside the notebook route.

  • Deep-ML - unsupervised problemsDeep-ML · support

    Use 17 K-Means Clustering, 19 PCA, 341 Gaussian Mixture Model with EM, 259 DBSCAN and 367 Isolation Forest as unit checks after the local implementation passes. Their tests were read in review; each card states what they pin, including the 367 path-length convention.

  • scikit-learn - preprocessing datascikit-learn · reference

    Read 8.3.1 standardization with the sparse with_mean=False rule, 8.3.1.3 scaling data with outliers, and 8.3.4 categorical encoding with handle_unknown, infrequent and sparse_output behavior. Apply after the HOML notebook build works.

  • scikit-learn - pipelines and composite estimatorsscikit-learn · reference

    Read 8.1.1 Pipeline chaining with the no-leakage rule and transformer caching, and 8.1.4 ColumnTransformer for heterogeneous columns with remainder and fitted-state behavior. Use it to assemble and serialize the feature-selection pipeline.

  • scikit-learn - imputation of missing valuesscikit-learn · reference

    Read 8.4.2 univariate median and most_frequent strategies, 8.4.6 Marking imputed values with MissingIndicator or add_indicator=True for missingness flags, and 8.4.7 estimators that accept NaN directly. Decide impute-only versus impute-plus-indicator per column.

  • UMAP - basic usage and parametersMcInnes, Healy and the UMAP contributors · reference

    Work the Penguin scaling and fit_transform section and the Digits fit and transform section, then read the parameters page for the n_neighbors local-global tradeoff and min_dist packing. Stay in 2D exploratory views with fixed seeds.