python 箱型图算法简介

本文详细介绍了统计学中的四分位数概念,包括第一四分位数(Q1)、第二四分位数(中位数Q2)和第三四分位数(Q3),并解释了四分位距(IQR)的概念。通过四分位数可以有效地界定数据集中的异常值,异常值被定义为小于QL-1.5IQR或大于QU+1.5IQR的值,其中QL是下四分位数,QU是上四分位数。

四分位数(Quartile)是统计学分位数的一种,即把所有数值由小到大排列并分成四等份,处于三个分割点位置的数值就是四分位数。

  • 第一四分位数 (Q1),又称"较小四分位数",等于该样本中所有数值由小到大排列后第25%的数字。

  • 第二四分位数 (Q2),又称"中位数",等于该样本中所有数值由小到大排列后第50%的数字。

  • 第三四分位数 (Q3),又称"较大四分位数",等于该样本中所有数值由小到大排列后第75%的数字。

第三四分位数与第一四分位数的差距又称四分位距(InterQuartile Range, IQR)。

异常值要在上界和下界之外,这个界定值通常定义为小于QL-1.5IQR或大于QU+1.5IQR的值。QL称为下四分位数,表示全部观察值中有四分之一的数据取值比它小;QU称为上四分位数,表示全部观察值中有四分之一的数据取值比它大;IQR称为四分位数间距,是上四分位数QU与下四分位数QL之差,其间包含了全部观察值的一半。

def detectoutliers(data:list):
    """箱型图检测异常值"""
    data = data.tolist()
    outlier_list_col = []
    # Q1为数据占25%的数据值范围
    Q1 = np.percentile(data, 25)
    # Q3为数据占75%的数据范围
    Q3 = np.percentile(data, 75)
    IQR = Q3 - Q1
    #异常值的范围
    outlier_step = 1.5 * IQR
    for n in range(len(data)):
        if float(data[n]) < Q1 - outlier_step or float(data[n]) > Q3 + outlier_step:
            outlier_list_col.append(data[n])
    # print(outlier_list_col)
    return outlier_list_col

参考博客: 

https://blog.youkuaiyun.com/u011489887/article/details/78973856

https://blog.youkuaiyun.com/marstonyjiang/article/details/76263109

### 使用智能优化算法生成箱型图和雷达图 #### 方法概述 智能优化算法通常用于寻找最优解或近似最优解。当应用于可视化领域时,这些算法可以帮助自动调整图表参数以达到最佳视觉效果。对于箱型图和雷达图而言,可以通过遗传算法、粒子群优化等方法来优化以下几个方面: - 数据分布特征的突出显示 - 图表颜色方案的选择 - 坐标轴范围设置 - 标签位置安排 #### 箱型图绘制实例 为了展示如何利用智能优化算法改善箱型图的质量,下面给出一段基于Python `matplotlib`库实现的例子。此例子采用简单的模拟退火法来自适应地选择最合适的离群点阈值。 ```python import numpy as np import matplotlib.pyplot as plt from scipy import stats def simulated_annealing(data, initial_temp=1000, cooling_rate=0.98): """Simulated Annealing to find optimal outlier threshold.""" best_threshold = None current_temperature = initial_temp while current_temperature > 1e-8: new_threshold = max(0, min(np.random.normal(loc=current_temperature), data.max())) if not best_threshold or objective_function(new_threshold) < objective_function(best_threshold): best_threshold = new_threshold current_temperature *= cooling_rate return best_threshold def plot_boxplot_with_optimized_outliers(data): optimized_threshold = simulated_annealing(data) fig, ax = plt.subplots() # Plot boxplots with adjusted whiskers based on the optimized threshold. bp = ax.boxplot([data[data <= optimized_threshold]], vert=False) plt.show() # Example usage np.random.seed(42) example_data = np.concatenate((np.random.randn(100)*3+50, [75]*5)) plot_boxplot_with_optimized_outliers(example_data) ``` 这段代码展示了如何应用模拟退火算法找到一个合理的离群点检测界限,并据此调整箱型图中的胡须长度[^1]。 #### 雷达图绘制实例 针对雷达图,这里提供了一个使用MATLAB环境下的示例程序片段,该程序尝试通过差分进化算法(Differential Evolution Algorithm)动态调整各维度的最大最小刻度以及整体布局风格,使得最终呈现出来的图形更加清晰易读。 ```matlab function radarPlotWithOptimization(values, labels) % RADARPLOTWITHOPTIMIZATION Creates a radially symmetric spider chart using DE algorithm. nVars = length(labels); lb = zeros(nVars, 1); ub = ones(nVars, 1); options = optimoptions('ga', ... 'PopulationSize', 50,... 'MaxGenerations', 200,... 'Display', 'iter'); [x,fval] = ga(@(x) fitnessFunction(x, values), nVars, [],[],[],[], lb, ub,[], options); figure; polaraxes; hold on; for i = 1:nVars theta(i) = (i-1)/nVars * 2*pi; end fill(cos(theta).*fval*sin(theta)', sin(theta).*fval*cos(theta)', 'b'); text(pi/2, fval(end)+0.1, sprintf('%s\n%.2f',labels{end},values(end))); title('Radar Chart Optimized by Differential Evolution') legend({'Optimized'},'Location','BestOutside') hold off; function score = fitnessFunction(scales, originalValues) % Fitness function evaluates how well scales fit into given value ranges. normalized_values = bsxfun(@rdivide,originalValues,max(originalValues)); scaled_values = bsxfun(@times,scales,normalized_values); spread_penalty = sum(abs(diff(sort(scaled_values)))); overlap_penalty = any(sum(bsxfun(@gt,scaled_values,[mean(scaled_values)-std(scaled_values)]))>ceil(length(scales)/2)); score = -(spread_penalty + double(overlap_penalty)*inf); end end ``` 上述脚本定义了一种自定义适应度函数,它考虑到了尺度分配均匀性和避免重叠两个因素的影响,以此指导DE算法迭代求解过程直至收敛于一组理想的坐标轴比例因子[^2]。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值