从三维数据元素中删除异常值

2024-03-29 15:00:45 发布

您现在位置:Python中文网/ 问答频道 /正文

我编写了一个函数,从数据集中删除异常值。例如,它使用z-score,也适用于1d的元素

# usage remove_outliers(data)  
[10 99 12 15 9 2 17 15]---->[10 12 15 9 17 15]

然而,它是错误的三维数据,它拉离我的三维数据,例如

# usage remove_outliers(data, thresh=(30,30,30), axis=(0,1))  
[(0, 10, 3) (99, 255, 255) (100, 10, 9) (45, 34, 9)]---->[  0  10   3  99 255 255 100  10   9  45  34   9]

我期待着这样的结果

[(0, 10, 3) (100, 10, 9) (45, 34, 9)]

我在函数remove_outliers()中做错了什么?如何编辑它来处理3d元素数据?你知道吗

def remove_outliers(data, thresh=2.0, axis=None):
    # If a value is > thresh std_deviations from the mean they are an outlier and remove it
    # Eg, thresh = 3, std_dev = 2, mean=18. If value=7, then 7 is an outlier
    d = np.abs(data - np.median(data, axis))
    mdev = np.median(d, axis)
    s = d/mdev if mdev else 0.0
    return data[s<thresh]

Tags: 数据函数元素dataifisvaluenp
1条回答
网友
1楼 · 发布于 2024-03-29 15:00:45

您需要为每个点组合坐标条件。在下面的代码中,这是由.all(axis=1)完成的

# numpy.median is rather slow, let's build our own instead
def median(x):
    m,n = x.shape
    middle = np.arange((m-1)>>1,(m>>1)+1)
    x = np.partition(x,middle,axis=0)
    return x[middle].mean(axis=0)

# main function
def remove_outliers(data,thresh=2.0):           
    m = median(data)                            
    s = np.abs(data-m)                          
    return data[(s<median(s)*thresh).all(axis=1)]

# small test
remove_outliers(np.array([(0, 10, 3), (99, 255, 255), (100, 10, 9), (45, 34, 9)]))
# array([[100,  10,   9],
#        [ 45,  34,   9]])

相关问题 更多 >