Skip to content

Js 异常点检测算法

Published: at 02:21 PMSuggest Changes

从数据 0,1,2,2,2,3,111,2,333,4,3,2 中找到 111333 这两个异常值

const outlierDetector = (collection) => {
  const size = collection.length;

  let q1, q3;

  if (size < 2) {
    return collection;
  }

  const sortedCollection = collection.slice().sort((a, b) => a - b);

  if (((size - 1) / 4) % 1 === 0 || (size / 4) % 1 === 0) {
    q1 =
      (1 / 2) *
      (sortedCollection[Math.floor(size / 4) - 1] +
        sortedCollection[Math.floor(size / 4)]);
    q3 =
      (1 / 2) *
      (sortedCollection[Math.ceil((size * 3) / 4) - 1] +
        sortedCollection[Math.ceil((size * 3) / 4)]);
  } else {
    q1 = sortedCollection[Math.floor(size / 4)];
    q3 = sortedCollection[Math.floor((size * 3) / 4)];
  }

  const iqr = q3 - q1;
  const maxValue = q3 + iqr * 1.5;

  return sortedCollection.filter((value) => value >= maxValue);
};

let a = [1,2,3,1,2,111,22,2,1,2]
let b = [1,4,7,20,3,5,12,33]
let c = [1,4,7,20,3,5,12,33,50,100]

outlierDetector(a);
outlierDetector(b);
outlierDetector(c);


Previous Post
JavaScript 动态时间规整 (DTW) 算法实现
Next Post
JavaScript 动态寻峰算法