首页 > 解决方案 > 在数据框中使用 IsolationForest 查找异常值

问题描述

我想在我的数据框中找到异常值。我写了一个代码,它会告诉我我的输入值是否是异常值,但我找不到检查我的数据是否包含异常值的方法。另外,我认为我的代码效果不好,因为它说这些值[1,4,64]不是异常值,我认为它们是。

   first  second  third  result
0      1       2      7    3.00
1     28      85     74    0.04
2      5       2      3    3.00
3      6       4      8    4.00
4      3       6      2    3.00
5      5       8      4    5.00
6      4       3      7    6.00
7      2       5      1    6.00
8      7       7    533    0.80
9      5       3      6    9.00

例如,您可以清楚地看到第 1 行和第 8 行中的值是异常值。这是我拥有的代码:

import pandas as pd
from sklearn.ensemble import IsolationForest  

df = pd.DataFrame({'first': [1,28,5,6,3,5,4,2,7,5],
                   'second': [2,85,2,4,6,8,3,5,7,3],
                   'third': [7,74,3,8,2,4,7,1,533,6],
                   'result': [3,0.04,3,4,3,5,6,6,0.8,9]})

print(df)

x = df.iloc[:,:-1]
print(x)

isolation_forest = IsolationForest(n_estimators=100, behaviour="new",
                                   contamination='auto')
model = isolation_forest.fit(x)

list_of_val = [[1,35,3], [3,4,5], [1,4,64]]

for val in list_of_val:

    outlier = isolation_forest.predict([val])
    print(outlier)

    if outlier[0] == -1:
        print('Values', val, 'are outliers')

    else:
        print('Values', val, 'are not outliers')

如果你告诉我为什么我的代码没有将值检测[1,4,64]为异常值,我将非常感激,如果你告诉我如何才能进入outlier column我的数据框中,该数据框将具有值outliernot outlier旁边的值。

标签: pythonpandasscikit-learn

解决方案


找到了方法

isolation_forest = IsolationForest(n_estimators=100, behaviour="new",
                                   contamination='auto')
model = isolation_forest.fit(x)
df['outliers'] = model.predict(x)
print(df)

推荐阅读