首页 > 解决方案 > 获得 seaborn.catplot 中计算的平均值的标准误差

问题描述

我正在使用seaborn.catplotwithkind='point'来绘制我的数据。我想使用与 seaborn 相同的方法计算每个色调变量和每个类别的平均值 (SEM) 的标准误差,以确保我的计算值与绘制的误差条完全匹配。计算 SEM 和 95% 置信区间 (CI) 的默认解决方案包含自举算法,其中均值自举 1000 次以计算 SEM/CI。在较早的帖子中,我看到了一种可能为此提供功能的方法(使用 seaborn 源代码功能,例如seaborn.utils.ci()seaborn.algorithms.bootstrap()) 但我不确定如何实现它。由于自举使用随机抽样,因此还需要确保为绘图和获得 SEM 生成相同的 1000 个均值数组。

这是一个代码示例:

import numpy as np
import pandas as pd
import seaborn as sns

# simulate data
rng = np.random.RandomState(42)
measure_names = np.tile(np.repeat(['Train BAC','Test BAC'],10),2)
model_numbers = np.repeat([0,1],20)
measure_values = np.concatenate((rng.uniform(low=0.6,high=1,size=20),
                                rng.uniform(low=0.5,high=0.8,size=20)
                                ))
folds=np.tile([1,2,3,4,5,6,7,8,9,10],4)

plot_df = pd.DataFrame({'model_number':model_numbers,
                        'measure_name':measure_names,
                        'measure_value':measure_values,
                        'outer_fold':folds})

# plot data as pointplot
g = sns.catplot(x='model_number',
                y='measure_value',
                hue='measure_name',
                kind='point',
                seed=rng,
                data=plot_df)

产生:

在此处输入图像描述

我想获得这两种模型的所有训练和测试分数的 SEM。那是:

# obtain SEM for each score in each model using the same method as in sns.catplot
model_0_train_bac = plot_df.loc[((plot_df['model_number'] == 0) & (plot_df['measure_name'] == 'Train BAC')),'measure_value']
model_0_test_bac = plot_df.loc[((plot_df['model_number'] == 0) & (plot_df['measure_name'] == 'Test BAC')),'measure_value']
model_1_train_bac = plot_df.loc[((plot_df['model_number'] == 1) & (plot_df['measure_name'] == 'Train BAC')),'measure_value']
model_1_test_bac = plot_df.loc[((plot_df['model_number'] == 1) & (plot_df['measure_name'] == 'Test BAC')),'measure_value']

标签: pythonseabornconfidence-interval

解决方案


我不确定我是否要求您采集完全相​​同的样本。根据定义,引导是通过随机抽样来工作的,因此从一次运行到下一次运行会有一些变化(除非我弄错了)。

您可以像 seaborn 一样计算 CI:

# simulate data
rng = np.random.RandomState(42)
measure_names = np.tile(np.repeat(['Train BAC','Test BAC'],10),2)
model_numbers = np.repeat([0,1],20)
measure_values = np.concatenate((rng.uniform(low=0.6,high=1,size=20),
                                rng.uniform(low=0.5,high=0.8,size=20)
                                ))
folds=np.tile([1,2,3,4,5,6,7,8,9,10],4)

plot_df = pd.DataFrame({'model_number':model_numbers,
                        'measure_name':measure_names,
                        'measure_value':measure_values,
                        'outer_fold':folds})

x_col = 'model_number'
y_col = 'measure_value'
hue_col = 'measure_name'
ci = 95
est = np.mean
n_boot = 1000

for gr,temp_df in plot_df.groupby([hue_col,x_col]):
    print(gr,est(temp_df[y_col]), sns.utils.ci(sns.algorithms.bootstrap(temp_df[y_col], func=est,
                                          n_boot=n_boot,
                                          units=None,
                                          seed=rng)))

输出:

('Test BAC', 0) 0.7581071363371585 [0.69217109 0.8316217 ]
('Test BAC', 1) 0.6527812067134964 [0.59523784 0.71539669]
('Train BAC', 0) 0.8080546943810699 [0.73214414 0.88102816]
('Train BAC', 1) 0.6201161718490218 [0.57978654 0.66241543] 

请注意,如果您再次运行循环,您将获得相似但不完全相同的 CI。

如果您真的想获得 seaborn 在绘图中使用的确切值(请注意,如果您再次绘制相同的数据,这些值会略有不同),那么您可以直接从 Line2D 艺术家那里提取值用于绘制误差线:

g = sns.catplot(x=x_col,
                y=y_col,
                hue=hue_col,
                kind='point',
                ci=ci,
                estimator=est,
                n_boot=n_boot,
                seed=rng,
                data=plot_df)
for l in g.ax.lines:
    print(l.get_data())

输出:

(array([0., 1.]), array([0.80805469, 0.62011617]))
(array([0., 0.]), array([0.73203808, 0.88129836])) # <<<<
(array([1., 1.]), array([0.57828366, 0.66300033])) # <<<<
(array([0., 1.]), array([0.75810714, 0.65278121]))
(array([0., 0.]), array([0.69124145, 0.83297914])) # <<<<
(array([1., 1.]), array([0.59113739, 0.71572469])) # <<<<

推荐阅读