基于一列中给定值的行异常值/异常检测(数组格式)

2024-04-19 16:00:04 发布

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

我一直在尝试通过Python或R找到一种方法,在我的csv文件中,脚本应该遍历每一行,并尝试根据其中一列中的数组值检测异常值或异常

根据我的说法,这个问题相当复杂,我已经尝试了很多方法来检测异常或异常值

我应该研究机器学习来解决这个问题吗

类似的事情有already a question posted,但没有得到正确的回答(我觉得),给出的数据图像可以用来描述任何可能的答案

谢谢

I would like to find the outliers in the Values column, for example, in the first row 142 would be an outlier when compared to other values in the cell, i want something which would go ID wise (row by row) and write the outliers to a new file with all these columns in place


Tags: 文件csvtheto方法in脚本机器
2条回答

下面是一些让你开始的东西。假设我们将离群值定义为与平均值相差2个标准差以上的值,我们可以执行以下操作。在继续阅读之前,请记住,在有限的数据点上执行类似操作是有风险的,因为您没有观察到足够的数据来知道它是异常值

import numpy as np
import pandas as pd
df = pd.DataFrame({'id':np.arange(1,6),
                   'lat':np.array([43,44,45,47,48]),
                   'lon':np.array([16,5,12,13,17]),
                   'values':[[171,172,142,169,178,180],[27,150,151,162,159,165],
                             [151,153,152,37],[171.222,127,180,172.56],[np.nan]]
                  })

我们可以看看df:

    id  lat     lon     values
0   1   43  16  [171, 172, 142, 169, 178, 180]
1   2   44  5   [27, 150, 151, 162, 159, 165]
2   3   45  12  [151, 153, 152, 37]
3   4   47  13  [171.222, 127, 180, 172.56]
4   5   48  17  [nan]

我们定义了一个函数,该函数将数据点返回到平均值2 sd以外的值:

def func(x):
    x = np.array(x)
    x_mean = np.mean(x)
    x_sd = np.std(x)
    return(x[abs(x - x_mean)>2*x_sd])

现在我们制作一个新的数据帧:

newdf =df.copy()
newdf['outlier_values'] = newdf['values'].apply(func)
newdf

结果如下:

id  lat     lon     values  outlier_values
0   1   43  16  [171, 172, 142, 169, 178, 180]  [142]
1   2   44  5   [27, 150, 151, 162, 159, 165]   [27]
2   3   45  12  [151, 153, 152, 37]     []
3   4   47  13  [171.222, 127, 180, 172.56]     []
4   5   48  17  [nan]   []

也许基于熵的方法可以在这里工作:http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.380.4114&rep=rep1&type=pdf

简言之,熵是无序的度量。因此,您可以通过计算行熵来“测量”行的无序度。这是一个相对的衡量标准,所以你必须尝试并确定你的情况下什么是精确的(这不是一个精确的科学)

以下是一个例子:

from scipy.stats import entropy


def my_entropy(labels, base = None):
    value,counts = np.unique(labels, return_counts=True)
    return entropy(counts, base=base)  

ls = [ [1,0,1,0,1,0,1,0,1,1,1,1], [1,0,1,0,1,0,1,0,1,1,9,1] , [1,0,1,'A',1,0,1,0,1,1,1,1], [1,0,1,0,5,0,1,0,7,1,0,1] ]

res = []
for labels in ls:
    res.append(my_entropy(labels))

print(res)
#[0.6365141682948128, 0.887694275799104, 0.8239592165010823, 1.14370838942625]

res在此根据无序程度对列表进行排序。在第一种情况下,我们只有0和1,所以熵是最低的。其他3个列表中引入的不同异常值显著增加了熵。所以我们可以用熵来衡量质量

相关问题 更多 >