过滤异常值-如何使基于中位数的Hampel函数更快?

EHB*_*EHB 6 python function filter pandas

我需要对数据使用Hampel过滤器,以去除异常值。

我无法在Python中找到现有的;仅在Matlab和R中。

[Matlab功能说明] [1]

[关于Matlab Hampel函数的统计交流的讨论] [2]

[R pracma包装小插图;包含hampel功能] [3]

我已经编写了以下函数,并根据R pracma包中的函数对其进行了建模。但是,它远比Matlab版本慢。这不理想;将不胜感激有关如何加快速度的投入。

该功能如下所示-

def hampel(x,k, t0=3):
    '''adapted from hampel function in R package pracma
    x= 1-d numpy array of numbers to be filtered
    k= number of items in window/2 (# forward and backward wanted to capture in median filter)
    t0= number of standard deviations to use; 3 is default
    '''
    n = len(x)
    y = x #y is the corrected series
    L = 1.4826
    for i in range((k + 1),(n - k)):
        if np.isnan(x[(i - k):(i + k+1)]).all():
            continue
        x0 = np.nanmedian(x[(i - k):(i + k+1)])
        S0 = L * np.nanmedian(np.abs(x[(i - k):(i + k+1)] - x0))
        if (np.abs(x[i] - x0) > t0 * S0):
            y[i] = x0
    return(y)
Run Code Online (Sandbox Code Playgroud)

我正在使用“ pracma”包中的R实现作为模型:

function (x, k, t0 = 3) 
{
    n <- length(x)
    y <- x
    ind <- c()
    L <- 1.4826
    for (i in (k + 1):(n - k)) {
        x0 <- median(x[(i - k):(i + k)])
        S0 <- L * median(abs(x[(i - k):(i + k)] - x0))
        if (abs(x[i] - x0) > t0 * S0) {
            y[i] <- x0
            ind <- c(ind, i)
        }
    }
    list(y = y, ind = ind)
}
Run Code Online (Sandbox Code Playgroud)

任何使函数更高效的帮助,或指向现有Python模块中现有实现的指针,将不胜感激。下面的示例数据;Jupyter中的%% timeit细胞魔术表明当前运行需要15秒:

vals=np.random.randn(250000)
vals[3000]=100
vals[200]=-9000
vals[-300]=8922273
%%timeit
hampel(vals, k=6)
Run Code Online (Sandbox Code Playgroud)

[1]:https//www.mathworks.com/help/signal/ref/hampel.html [2]:https//dsp.stackexchange.com/questions/26552/what-is-a-hampel-filter -and-how-does-it-work [3]:https//cran.r-project.org/web/packages/pracma/pracma.pdf

小智 9

上面@EHB 的解决方案很有帮助,但它是不正确的。具体来说,在median_abs_deviation中计算的滚动中位数有差异,它本身就是每个数据点与rolling_median中计算的滚动中位数的差异,但应该是滚动窗口中的数据与窗口上的中位数差异的中位数. 我把上面的代码修改了一下:

def hampel(vals_orig, k=7, t0=3):
    '''
    vals: pandas series of values from which to remove outliers
    k: size of window (including the sample; 7 is equal to 3 on either side of value)
    '''
    
    #Make copy so original not edited
    vals = vals_orig.copy()
    
    #Hampel Filter
    L = 1.4826
    rolling_median = vals.rolling(window=k, center=True).median()
    MAD = lambda x: np.median(np.abs(x - np.median(x)))
    rolling_MAD = vals.rolling(window=k, center=True).apply(MAD)
    threshold = t0 * L * rolling_MAD
    difference = np.abs(vals - rolling_median)
    
    '''
    Perhaps a condition should be added here in the case that the threshold value
    is 0.0; maybe do not mark as outlier. MAD may be 0.0 without the original values
    being equal. See differences between MAD vs SDV.
    '''
    
    outlier_idx = difference > threshold
    vals[outlier_idx] = rolling_median[outlier_idx] 
    return(vals)
Run Code Online (Sandbox Code Playgroud)


EHB*_*EHB 5

熊猫解决方案的速度要快几个数量级:

def hampel(vals_orig, k=7, t0=3):
    '''
    vals: pandas series of values from which to remove outliers
    k: size of window (including the sample; 7 is equal to 3 on either side of value)
    '''
    #Make copy so original not edited
    vals=vals_orig.copy()    
    #Hampel Filter
    L= 1.4826
    rolling_median=vals.rolling(k).median()
    difference=np.abs(rolling_median-vals)
    median_abs_deviation=difference.rolling(k).median()
    threshold= t0 *L * median_abs_deviation
    outlier_idx=difference>threshold
    vals[outlier_idx]=np.nan
    return(vals)
Run Code Online (Sandbox Code Playgroud)

定时时间为11毫秒vs 15秒;巨大的进步。

我在这篇文章中找到了类似过滤器的解决方案