隔离森林入门

Python 中的异常检测

Bekhruz (Bex) Tuychiev

Kaggle Master, Data Science Content Creator

调查数据

  • 一个受访者:
    • 12岁
    • 身高160厘米
    • 体重190磅

一名戴帽子的12岁卡通男孩形象

Python 中的异常检测

多变量异常

多变量异常:

  • 具有两个或以上属性
  • 属性本身不一定异常
  • 仅在综合考虑所有属性时才异常
Python 中的异常检测

决策树

一个决策树的根节点和一个终止节点,用于判断5是否为质数

Python 中的异常检测

决策树

一个三层的完整决策树,用于判断5是否为质数

Python 中的异常检测

隔离树

iTrees:

  • 隔离树的简称
  • 决策树的随机化版本
  • 随机进行划分(分支)
  • 更可能在内点/离群点间隙处划分
Python 中的异常检测

二维数据示例

一个包含9个数据点的二维数据集,其中两个为离群点

Python 中的异常检测

拟合隔离树

二维数据集被一条绿色线在平面上划分为两部分

拟合到二维数据集的隔离树根节点

Python 中的异常检测

拟合隔离树

二维数据集被两条垂直线划分为四部分

隔离树的两个节点,检测到2个离群点

Python 中的异常检测

拟合隔离树

二维数据集被6条不同颜色的线划分为多部分

隔离树在该二维数据集上继续生长的其余部分

Python 中的异常检测

点如何被分类

判为离群点当:

  • 接近根节点
  • 或需要的划分更少

隔离树在该二维数据集上继续生长的其余部分

Python 中的异常检测

美国 Airbnb 数据

import pandas as pd

airbnb_df = pd.read_csv("airbnb.csv")
Python 中的异常检测

美国 Airbnb 数据

airbnb_df.info()
<class 'pandas.core.frame.DataFrame'>
RangeIndex: 10000 entries, 0 to 9999
Data columns (total 6 columns):
 #   Column                          Non-Null Count  Dtype  
 0   minimum_nights                  10000 non-null  int64  
 1   number_of_reviews               10000 non-null  int64  
 2   reviews_per_month               10000 non-null  float64
 3   calculated_host_listings_count  10000 non-null  int64  
 4   availability_365                10000 non-null  int64  
 5   price                           10000 non-null  int64  
dtypes: float64(1), int64(5)
Python 中的异常检测

fit_predict

from pyod.models.iforest import IForest

iforest = IForest() labels = iforest.fit_predict(airbnb_df) print(labels)
array([0, 0, 0, ..., 1, 0, 0])

Python 中的异常检测

筛选离群点

outliers = airbnb_df[labels == 1]

print(outliers.shape)
(1000, 6)
Python 中的异常检测

¡Vamos a practicar!

Python 中的异常检测

Preparing Video For Download...