我的设备产生了一些异常数据,如何找到?
对于异常值检测,我们可以使用一种称为"3倍中位数绝对偏差(3 times Median Absolute Deviation,3*MAD)"的方法。
using System; using System.Collections.Generic; using System.Linq; public class Program { public static void Main(string[] args) { List<double> data = new List<double> { 0.1, 0.3, 0.27, 0.29, 18.7, 18.5, 0.3, 0.5, 0.9 }; List<double> outliers = FindOutliers(data); Console.WriteLine("异常数据:"); foreach (double outlier in outliers) { Console.WriteLine(outlier); } } public static List<double> FindOutliers(List<double> data) { List<double> outliers = new List<double>(); double median = CalculateMedian(data); double mad = CalculateMAD(data, median); foreach (double value in data) { if (Math.Abs(value - median) > 3 * mad) // 判断是否为异常值,这里使用3倍MAD作为判断条件 { outliers.Add(value); } } return outliers; } public static double CalculateMedian(List<double> data) { List<double> sortedData = data.OrderBy(x => x).ToList(); int n = sortedData.Count; if (n % 2 == 0) { return (sortedData[(n / 2) - 1] + sortedData[n / 2]) / 2; } else { return sortedData[n / 2]; } } public static double CalculateMAD(List<double> data, double median) { List<double> absoluteDeviations = new List<double>(); foreach (double value in data) { absoluteDeviations.Add(Math.Abs(value - median)); } double mad = CalculateMedian(absoluteDeviations); return mad; } }