Python 中调整的箱线图

问题描述 投票:0回答:2

对于我的论文,我试图识别数据集中的异常值。该数据集由来自真实过程环境的一个变量的 160000 次构建。然而,在这种环境中,测量结果可能不是来自过程本身的实际数据,而只是垃圾数据。我想在文献的帮助下过滤掉它们,而不仅仅是“专家意见”。

现在我已经了解了 IQR 方法,用于查看在处理正态分布等对称分布时是否存在可能的异常值。然而,我的数据集是右偏的,并且通过分布拟合、逆伽玛和对数正态最适合。

因此,在寻找非对称分布的方法期间,我在交叉验证上发现了这个主题,其中 user603 的答案特别有趣:Is there a boxplotvariant for Poisson distribution data?

在 user603 的回答中,他指出调整后的箱线图有助于识别数据集中可能的异常值,并且 R 和 Matlab 具有这方面的功能

(有一个 𝚁R 实现 (𝚛𝚘𝚋𝚞𝚜𝚝𝚋𝚊𝚜𝚎::𝚊𝚍𝚓𝚋𝚘𝚡()robustbase::adjbox()) 以及 一个 matlab 的(在一个名为 𝚕𝚒𝚋𝚛𝚊libra 的库中)

我想知道Python中是否有这样的函数。或者有没有办法用Python计算医学对(参见user603的答案中的论文)?

我真的很想看看我的数据调整后的箱线图会出现什么结果..

python boxplot outliers
2个回答
3
投票

在 statsmodels.stats.stattools 模块中,有一个函数 med Couple(),它是调整后箱线图中使用的偏度的度量。

在此输入链接描述

使用此变量,您可以计算定义异常值的间隔。


1
投票

这是一种可能的解决方案,遵循 Christophe 的回答 并解决 @banderlog013 的评论。

  1. 查找识别异常值和绘制箱线图所需的参数:
import statsmodels.api as sm
import datetime
import seaborn as sns
def adjusted_boxplot_params(data:pd.Series):
    ''' 
    Returns:
    @outlier_range_lower: lower bound of normal expected values. Everything below are outlier candidates.
    @outlier_range_upper: upper bound of normal expected values. Above are outlier candidates.
    @whis: (lowWhis,highWhis) whis parameter for the boxplot method, in a form (low_percentage, high_percentage), as expected by pyplot.boxplot().
    '''

    q1 = data.quantile(0.25)
    q3 = data.quantile(0.75)

    # Calculate the interquartile range
    iqr = q3 - q1
    #calculate medcouple
    y = np.asarray(data, dtype=np.double) 
    MC = sm.stats.stattools.medcouple(y) 

    # Define the outlier range 
    if (MC>0):
        outlier_range_lower = q1 - 1.5 * np.exp(-4*MC) * iqr
        outlier_range_upper = q3 + 1.5 * np.exp(3*MC)  * iqr
    else:
        outlier_range_lower = q1 - 1.5 * np.exp(-3*MC) * iqr
        outlier_range_upper = q3 + 1.5 * np.exp(4*MC)  * iqr

    whis = np.interp([outlier_range_lower, outlier_range_upper], np.sort(data), np.linspace(0, 1, data.size)) * 100 #Ref: https://stackoverflow.com/a/65390045/7745170

    return outlier_range_lower, outlier_range_upper, whis 
  1. 从数据框列中选择离群值,并可选择绘制调整后的箱线图:
def select_outliers_adjusted_boxplot(df, col_name:str,show_plot=False): 
    ''' selects rows in the dataframe df which coll_name falls out of bounds [min,max]
    @df: dataframe 
    @col_name: column to analyze 
    Returns:
    @otuliers: df with selected rows from input df.
    '''

    outlier_range_lower, outlier_range_upper, whis = adjusted_boxplot_params(df[col_name])
    # Select the rows where the duration is outside the outlier range
    outliers = df[(df[col_name] < outlier_range_lower) |
                  (df[col_name] > outlier_range_upper)]

    if show_plot==True:
        plot = sns.boxplot(x=df[col_name,whis=whis)
        plt.show(plot2)

    # Return the DataFrame containing the outliers
    return outliers
© www.soinside.com 2019 - 2024. All rights reserved.