离群点、异常点检测及Python实现(正态分布3∂,Z-score 异常值检测,基于MAD的Z-score 异常值检测,杠杆值点、DFFITS值、SR学生化残差、cook距离和covratio值)

有一些准则可以检测离群点,如:正态分布3∂,Z-score 异常值检测,基于MAD的Z-score 异常值检测

以上部分详情与代码请参考:https://blog.csdn.net/weixin_35757704/article/details/89280715

下面是其他的准则:高杠杆值点(帽子矩阵)、DFFITS值、SR学生化残差、cook距离和covratio值,先创建个例子:

import numpy as np
import statsmodels.api as sm
import pandas as pd
from sklearn.metrics import mean_squared_error

x = pd.DataFrame(
    np.random.randint(0, 100, size=(100, 4)), columns=['col1', 'col2', 'col3', 'col4']
)
y = np.random.randint(0, 100, size=(100, 1))
fit = sm.OLS(y, x).fit()

print(fit.summary())

pred = fit.predict()
print("RMSE : ", np.sqrt(mean_squared_error(y, pred)))  # 计算 RMSE

# 离群点检验
out_points = fit.get_influence()

高杠杆值点

# 高杠杆值点(帽子矩阵)
leverage = out_points.hat_matrix_diag
# 高杠杆值点大于 2(p+1)/n时 被认为是异常点;其中p为维度,n为样本数量
leverage_out = x[leverage > 2 * (x.shape[1]) / x.shape[0]]

DFFITS值

# DFFITS值
dffits = out_points.dffits[0]

# DFFITS统计值大于 2sqrt((p+1)/n) 时被认为是异常点,其中p为维度,n为样本数量
diffts_out = x[dffits > 2 * np.sqrt((x.shape[1] + 1) / x.shape[0])]

SR学生化残差

# 学生化残差
studentized_residual = out_points.resid_studentized_external

# studentized_residual 的绝对值不大于2
studentized_residual_out = x[np.abs(studentized_residual) > 2]

cook距离

# cook距离

cook = out_points.cooks_distance[0]
# 值的绝对值越大越有高概率是异常点

covratio值

# covratio值

covratio = out_points.cov_ratio
# covratio值离 1 越远,越有可能是离群点

全部代码

import numpy as np
import statsmodels.api as sm
import pandas as pd
from sklearn.metrics import mean_squared_error

x = pd.DataFrame(
    np.random.randint(0, 100, size=(100, 4)), columns=['col1', 'col2', 'col3', 'col4']
)
y = np.random.randint(0, 100, size=(100, 1))
fit = sm.OLS(y, x).fit()

print(fit.summary())

pred = fit.predict()
print("RMSE : ", np.sqrt(mean_squared_error(y, pred)))  # 计算 RMSE

# 离群点检验
out_points = fit.get_influence()

# 高杠杆值点(帽子矩阵)
leverage = out_points.hat_matrix_diag
# 高杠杆值点大于 2(p+1)/n时 被认为是异常点;其中p为维度,n为样本数量
leverage_out = x[leverage > 2 * (x.shape[1]) / x.shape[0]]

# DFFITS值
dffits = out_points.dffits[0]
# DFFITS统计值大于 2sqrt((p+1)/n) 时被认为是异常点,其中p为维度,n为样本数量
diffts_out = x[dffits > 2 * np.sqrt((x.shape[1] + 1) / x.shape[0])]

# 学生化残差
studentized_residual = out_points.resid_studentized_external
# studentized_residual 的绝对值不大于2
studentized_residual_out = x[np.abs(studentized_residual) > 2]

# cook距离

cook = out_points.cooks_distance[0]
# 值的绝对值越大越有高概率是异常点

# covratio值

covratio = out_points.cov_ratio
# covratio值离 1 越远,越有可能是离群点


# 将上面的几种异常值检验统计量与原始数据集合并
contat1 = pd.concat([
    pd.Series(leverage, name='leverage'),
    pd.Series(dffits, name='dffits'),
    pd.Series(studentized_residual, name='rs'),
    pd.Series(cook, name='cook'),
    pd.Series(covratio, name='covratio'),
], axis=1)
  • 4
    点赞
  • 25
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论
Python中有多种方法可以进行离群点检测,下面介绍其中的几种常用方法: 1. 基于统计模型的方法 基于统计模型的方法主要是通过对数据的分布进行建模来检测离群。常用的统计模型包括正态分布、t分布、Chisquare分布等。比如,我们可以使用均和标准差来检测数据是否偏离正态分布。具体代码如下: ```python import numpy as np from scipy.stats import norm # 生成一组数据 data = np.random.randn(1000) # 计算均和标准差 mu, std = norm.fit(data) # 指定阈进行离群点检测 threshold = 3 outliers = data[np.abs(data - mu) > threshold * std] print(outliers) ``` 2. 基于距离的方法 基于距离的方法主要是通过计算数据之间的距离检测离群。常用的距离度量包括欧式距离、马哈拉诺比斯距离等。比如,我们可以使用k近邻算法来检测离群。具体代码如下: ```python from sklearn.neighbors import LocalOutlierFactor # 生成一组数据 data = np.random.randn(1000, 2) # 使用k近邻算法进行离群点检测 clf = LocalOutlierFactor(n_neighbors=20, contamination=0.1) y_pred = clf.fit_predict(data) # 获取离群的索引 outliers = np.where(y_pred == -1)[0] print(outliers) ``` 3. 基于聚类的方法 基于聚类的方法主要是通过将数据分为多个簇来检测离群。常用的聚类算法包括K-means、DBSCAN等。比如,我们可以使用DBSCAN算法来检测离群。具体代码如下: ```python from sklearn.cluster import DBSCAN # 生成一组数据 data = np.random.randn(1000, 2) # 使用DBSCAN算法进行离群点检测 clf = DBSCAN(eps=0.5, min_samples=5) y_pred = clf.fit_predict(data) # 获取离群的索引 outliers = np.where(y_pred == -1)[0] print(outliers) ``` 以上三种方法都有其优缺,具体使用哪种方法需要根据具体情况进行选择。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

呆萌的代Ma

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值