outlier_detection.rs
This file
Path
src/outlier_detection.rs
90 lines · 2.5 KiB · Rust
Last changed by
Merge pull request #963 from sharkdp/codex/measurement-helpersDavid Peterbefore adoptionf16b6b9
History of this fileTake it
1//! A module for statistical outlier detection.2//!3//! References:4//! - Boris Iglewicz and David Hoaglin (1993), "Volume 16: How to Detect and Handle Outliers",5//! The ASQC Basic References in Quality Control: Statistical Techniques, Edward F. Mykytka,6//! Ph.D., Editor.78/// Minimum modified Z-score for a datapoint to be an outlier. Here, 1.4826 is a factor that9/// converts the MAD to an estimator for the standard deviation. The second factor is the number10/// of standard deviations.11pub const OUTLIER_THRESHOLD: f64 = 1.4826 * 10.0;1213/// Return the number of outliers in a given sample. Outliers are defined as data points with a14/// modified Z-score that is larger than `OUTLIER_THRESHOLD`.15#[cfg(test)]16pub fn num_outliers(xs: &[f64]) -> usize {17 use crate::quantity::statistics::modified_zscores_f64;1819 if xs.is_empty() {20 return 0;21 }2223 let scores = modified_zscores_f64(xs);24 scores25 .iter()26 .filter(|&&s| s.abs() > OUTLIER_THRESHOLD)27 .count()28}2930#[test]31fn test_detect_outliers() {32 // Should not detect outliers in small samples33 assert_eq!(0, num_outliers(&[]));34 assert_eq!(0, num_outliers(&[50.0]));35 assert_eq!(0, num_outliers(&[1000.0, 0.0]));3637 // Should not detect outliers in low-variance samples38 let xs = [-0.2, 0.0, 0.2];39 assert_eq!(0, num_outliers(&xs));4041 // Should detect a single outlier42 let xs = [-0.2, 0.0, 0.2, 4.0];43 assert_eq!(1, num_outliers(&xs));4445 // Should detect a single outlier46 let xs = [0.5, 0.30, 0.29, 0.31, 0.30];47 assert_eq!(1, num_outliers(&xs));4849 // Should detect no outliers in sample drawn from normal distribution50 let xs = [51 2.33269488,52 1.42195907,53 -0.57527698,54 -0.31293437,55 2.2948158,56 0.75813273,57 -1.0712388,58 -0.96394741,59 -1.15897446,60 1.10976285,61 ];62 assert_eq!(0, num_outliers(&xs));6364 // Should detect two outliers that were manually added65 let xs = [66 2.33269488,67 1.42195907,68 -0.57527698,69 -0.31293437,70 2.2948158,71 0.75813273,72 -1.0712388,73 -0.96394741,74 -1.15897446,75 1.10976285,76 20.0,77 -500.0,78 ];79 assert_eq!(2, num_outliers(&xs));80}8182#[test]83fn test_detect_outliers_if_mad_becomes_0() {84 // See https://stats.stackexchange.com/q/33993285 let xs = [10.0, 10.0, 10.0, 10.0, 10.0, 10.0, 10.0, 100.0];86 assert_eq!(1, num_outliers(&xs));8788 let xs = [10.0, 10.0, 10.0, 10.0, 10.0, 10.0, 10.0, 100.0, 100.0];89 assert_eq!(2, num_outliers(&xs));90}