什么是异常与离群点?

Python 中的异常检测

Bekhruz (Bex) Tuychiev

Kaggle Master, Data Science Content Creator

内点 vs. 离群点

  • 异常检测:识别异常数据点
  • 内点(Inliers)
    • "正常"的数据点
    • 代表多数
  • 离群点(Outliers)
    • 极少出现
    • 统计上显著不同

两个离群点示例:一朵红色郁金香处于绿色田野中;以及一根与一组白色木棍分离的黑色木棍

Python 中的异常检测

将地球视为异常

所有行星都是内点

从远处拍摄的银河系图像。

只有地球是离群点

地球的奇特图像,通过大气层如同镜头反映出生命的存在。

Python 中的异常检测

统计定义

  • 异常地不同
  • 具有显著不同的特征
  • 是否为离群点由观察者判定
Python 中的异常检测

异常检测的应用

"security"文本的图像,鼠标指针悬停其上。

Python 中的异常检测

异常检测的应用

一只戴蓝色手套的手拿着装有蓝色液体的小化学容器。

Python 中的异常检测

异常检测的应用

一名男子将Visa卡递给拿着收银终端的女子。

Python 中的异常检测

示例数据

import pandas as pd

numbers = pd.Series([24, 46, 30, 28, 1289, 25, 21, 31, 48, 47])
Python 中的异常检测

均值与方差的影响

去除离群点的数据

numbers_a = pd.Series([24, 46, ...])
numbers_a.mean()
33.33
numbers_a.var()
114.5

含离群点的数据

numbers_b = pd.Series([1289, 24, ...])
numbers_b.mean()
158.9
numbers_b.var()
157771.65
Python 中的异常检测

训练数据中的异常

  • 异常会引入噪声
  • 可能被误认为新子群
  • 会分散对真实模式的关注
Python 中的异常检测

离群点检测 vs. 新奇点检测

离群点检测

  • 离群点只存在于训练数据

新奇点检测

  • 新奇点只存在于新数据
Python 中的异常检测

五数概括

import pandas as pd

big_mart = pd.read_csv("big_mart.csv")
sales = big_mart['sales']
sales.describe()
count     8523.000000
mean      2181.288914
std       1706.499616
min         33.290000
25%        834.247400
50%       1794.331000
75%       3101.296400
max      13086.964800
Python 中的异常检测

绘制直方图

import numpy as np
import matplotlib.pyplot as plt

# Find the square root of the length of sales
n_bins = np.sqrt(len(sales))
# Cast to an integer
n_bins = int(n_bins)


# Plot plt.figure(figsize=(8, 4)) plt.hist(sales, bins=n_bins, color='red')
Python 中的异常检测

直方图结果

产品销量的直方图,红色条形,右侧长尾。

Python 中的异常检测

绘制散点图

integers = range(len(sales))

plt.figure(figsize=(16, 8))
plt.scatter(integers, sales, c='red', alpha=0.5)
Python 中的异常检测

散点图结果

散点图:下半部分点云密集,向上逐渐稀疏。

Python 中的异常检测

Vamos praticar!

Python 中的异常检测

Preparing Video For Download...