利用图基Tukey method检测数据集中的异常值
生活随笔
收集整理的這篇文章主要介紹了
利用图基Tukey method检测数据集中的异常值
小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
在數(shù)據(jù)集中如果某一個(gè)觀察值不尋常地大于或者小于該數(shù)據(jù)集中的其他數(shù)據(jù),我們則稱之為疑似異常值。疑似異常值的存在,會(huì)對(duì)隨后的計(jì)算結(jié)果產(chǎn)生不適當(dāng)?shù)挠绊?#xff0c;檢測(cè)疑似異常值并加以適當(dāng)?shù)奶幚硎鞘直匾摹?/p>
一種經(jīng)典的計(jì)算數(shù)據(jù)集中疑似異常值的方法是Tukey method。該方法先計(jì)算出數(shù)據(jù)集的四分之一分位數(shù)(Q1)和四分之三分位數(shù)(Q3),從而計(jì)算出四分位數(shù)間距(IQR),然后將小于Q1 - 1.5IQR或者大于Q3 + 1.5IQR的數(shù)據(jù)點(diǎn)當(dāng)做是疑似異常值。我們可以借助這種方法在DataFrame中檢測(cè)異常值。代碼如下:
import numpy as np import pandas as pd from collections import Counter import matplotlib as plt# Outlier detection def detect_outliers(df, n, features):"""Takes a dataframe df of features and returns a list of the indicescorresponding to the observations containing more than n outliers accordingto the Tukey method."""outlier_indices = []# iterate over features(columns)for col in features:# 1st quartile (25%)Q1 = np.percentile(df[col], 25)# 3rd quartile (75%)Q3 = np.percentile(df[col], 75)# quartile spacing (IQR)IQR = Q3 - Q1# outlier stepoutlier_step = 1.5 * IQR# Determine a list of indices of outliers for feature coloutlier_list_col = df[(df[col] < Q1 - outlier_step) | (df[col] > Q3 + outlier_step)].index# append the found outlier indices for col to the list of outlier indicesoutlier_indices.extend(outlier_list_col)# select observations containing more than n outliersoutlier_indices = Counter(outlier_indices)multiple_outliers = list(k for k, v in outlier_indices.items() if v > n)return multiple_outliersiris = pd.read_csv('./iris.csv', usecols=[0, 1, 2, 3])print(detect_outliers(iris, 1, iris.columns))利用iris.csv數(shù)據(jù)集,手動(dòng)添加異常點(diǎn):
40,44,45,46,setosa 77,55,33,44,setosa 99,88,82,123,setosa運(yùn)行上面的程序,可以將異常值找出來(lái)。
總結(jié)
以上是生活随笔為你收集整理的利用图基Tukey method检测数据集中的异常值的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: wifi连接到了上不到网路由器怎么设置我
- 下一篇: 矩阵的秩到底描述了什么?