如何检测和修复图表上的异常值?

3
我尝试使用 library(AnomalyDetection) 中的 AnomalyDetectionTs() 函数,来自 https://github.com/twitter/AnomalyDetectionhttps://www.r-bloggers.com/anomaly-detection-in-r/,对我的数据进行检测。在我的示例数据中,有些波动值没有像预期那样下降曲线(或以缓慢的方式下降),这个函数对我来说不起作用。该函数检测到的所有异常点都是正确的和正常的值。
以下是该函数的结果:enter image description here 我的示例数据:https://raw.githubusercontent.com/ieatbaozi/R-Practicing/master/example.csv
df <- read.csv(url("https://raw.githubusercontent.com/ieatbaozi/R-Practicing/master/example.csv"),header = TRUE,stringsAsFactors = FALSE)
df$DateTime <- as.POSIXct(df$DateTime)

library(AnomalyDetection)
ADtest <- AnomalyDetectionTs(df, max_anoms=0.1, direction='both', plot=TRUE)
ADtest$plot

这是我的预期结果: enter image description here 如何检测这些异常数据?
如何通过填充最合适的值来修复这些值?使它们平滑地绘制在它们周围的模式附近,并且在修复这些值后所有数据的总值仍然相同。
我的额外问题是:您有任何想法可以找到它的模式吗?我可以给您更多信息。非常感谢您的帮助。
1个回答

2
这里是一种可能的解决方案。
  1. 计算每个点周围小窗口的平均值(滚动平均)
  2. 计算实际值与局部平均值之间的差异。
  3. 计算步骤2中所有差异的标准偏差。
  4. 将距离局部平均值超过X个标准偏差的点标记为异常值。
使用这种方法,我得到了您要查找的点,以及其他一些点 - 这些点处于非常低值到非常高值的转换中。您可以尝试过滤掉它们。 代码
library(zoo)        ## For rolling mean function

WindowSize = 5
HalfWidth = (WindowSize-1)/2

SD = sqrt(mean((rollmean(df$Val, WindowSize ) - 
    df$Val[-c(1:HalfWidth, (nrow(df)+1-(1:HalfWidth)))])^2))
Out = which(abs(rollmean(df$Val, WindowSize ) - 
    df$Val[-c(1:HalfWidth, (nrow(df)+1-(1:HalfWidth)))]) > 2.95*SD) + 2

plot(df, type="l")
points(df[Out,], pch=16, col="red")

Time series plot


1
也许可以使用以下代码来进一步筛选 Out: Out[sapply(Out, function(i) { v <- df$Val[i + (-2):2]; min(v) == v[3] || max(v) == v[3] })] - G. Grothendieck

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接