python - 在数据框中使用 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
我的数据框中,该数据框将具有值outlier
和not outlier
旁边的值。
解决方案
找到了方法
isolation_forest = IsolationForest(n_estimators=100, behaviour="new",
contamination='auto')
model = isolation_forest.fit(x)
df['outliers'] = model.predict(x)
print(df)
推荐阅读
- python - 从在线流中记录的损坏的 AAC 文件
- python - Mutagen Python FileNotFoundError 处理
- javascript - 当点击其他地方时,引导下拉菜单不会消失?
- python - 如果数据存在,JSON 会做一些事情,如果不存在,则做其他事情
- reactjs - React Native:Flatlist 问题
- javascript - 在某些网站上使用 jQuery 函数会导致 Uncaught TypeError
- r - 如何使用 highlight.js 突出显示所有 R 函数名称?
- javascript - 在 Firefox 中使用 'deviceorientation' 事件会发出警告
- ember.js - Ember 应用程序使用作为传递依赖安装的插件
- joomla - Joomla Admin 和前面缺少图标