异常值
数据预处理第一步,通常是对异常值的处理。首先,要得到数据的上四分位数和下四分位数,利用np.percentile()
,用法如下。
import numpy as np
x = np.array([[1,2,3],[7,8,9]])
Q1 = np.percentile(x,25) # 1st quartile
Q3 = np.percentile(x,75) # 3st quartile
假设数据集是x = [1, 2, 3, ..., 98, 99, 10000]
,显然最后一个数10000是一个超限点。它的Q1 = 25, Q3 = 75,四分位距IQR(the interquartile range)=Q1 - Q3。若上下界分别扩大0.5倍,令k = 1.5
为high = Q3 + k * (Q3 - Q1)
,下界为low = Q1 - k * (Q3 - Q1)
,即上界为-50下界为150,显然10000超限。如果想调整上界下界的范围,调整系数即可。
对于一个矩阵df
,按列循环找到每列数据的异常值,如果某个样本含有n个以上的超限特征,返回行号。
注意:在进行这一步之前,先要处理好缺失值和标签量。
# outlier detection
def detect_outliers(df,n,feature_name):
'''
df: the feature dataframe;
n: if outlier feature more than n
features: the name of columns detected
return the index
'''
outlier_indices=[]
for col in feature_name:
Q1 = np.percentile(df[col],25)
Q3 = np.percentile(df[col],75)
# interquartile range(IQR)
IQR = Q3 - Q1
outlier_step = 1.5 * IQR
# Determine a list of indeices of ouliers for feature col
outlier_list_col = df[(df[col] < Q1 - outlier_step) | (df[col] > Q3 + outlier_step)].index.tolist()
# append the found oulier indices for col to the list of outlier indices
outlier_indices.extend(outlier_list_col)
# select observations containing more than 2 outliers
outlier_indices = Counter(outlier_indices)
multiple_outliers = list(k for k, v in outlier_indices.items() if v > n)
return multiple_outliers
经过检查后,假设特征矩阵有10(列)个特征,规定包含大于4列超过了范围,返回行号。
ouliter_result = detect_outliers(feature, 4, feature.columns.tolist())