话不多说,上马
public List<double> DetectOutliersIQR(List<double> data)
{
List<double> outliers = new List<double>();
double q1 = GetQuantile(data, 0.25);
double q3 = GetQuantile(data, 0.75);
double iqr = q3 - q1;
double lowerBound = q1 - 1.5 * iqr;
double upperBound = q3 + 1.5 * iqr;
foreach (double value in data)
{
if (value < lowerBound || value > upperBound)
{
outliers.Add(value);
}
}
return outliers;
}
// 计算指定百分位数的值
private double GetQuantile(List<double> data, double percentile)
{
data.Sort();
int count = data.Count;
double index = percentile * (count - 1);
int floor = (int)Math.Floor(index);
int ceil = (int)Math.Ceiling(index);
if (floor == ceil)
{
return data[floor];
}
else
{
double lowerValue = data[floor] * (ceil - index);
double upperValue = data[ceil] * (index - floor);
return lowerValue + upperValue;
}
}
使用
List<double> datas = new List<double>() {1,3,0,2,4,1,6,8,22,5,6,7,33,5,1,99,55,5,9,8,7 };
List<double> temps = DetectOutliersIQR(datas);
异常检测结果