You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Scipy中ks_2samp未返回statistic_location,如何获取该值?

双样本Kolmogorov-Smirnov检验获取统计量位置的解决方案

问题分析

你遇到的情况是因为使用的Scipy版本过低——旧版本的scipy.stats.ks_2samp仅返回统计量(statistic)和p值(pvalue),而文档中提到的statistic_location(两个CDF最大差异的位置)是Scipy后续版本新增的返回字段。

解决方法

方法1:升级Scipy版本

升级到1.9.0及以上版本的Scipy,就能直接从返回结果中获取statistic_location:

  1. 执行升级命令:
pip install --upgrade scipy
  1. 升级后调用代码示例:
import numpy as np
from scipy import stats

n1 = np.random.normal(0, 1, 20)
n2 = np.random.normal(1, 1, 20)
result = stats.ks_2samp(n1, n2)

# 提取所需结果
print(f"统计量: {result.statistic}")
print(f"p值: {result.pvalue}")
print(f"CDF最大差异位置: {result.statistic_location}")

方法2:手动计算(无法升级版本时)

如果无法升级Scipy,可以手动计算最大差异位置:

import numpy as np
from scipy import stats

n1 = np.random.normal(0, 1, 20)
n2 = np.random.normal(1, 1, 20)

# 合并并排序所有样本点
sorted_points = np.sort(np.concatenate([n1, n2]))
# 计算两个样本的经验CDF
cdf_n1 = stats.ecdf(n1).cdf(sorted_points)
cdf_n2 = stats.ecdf(n2).cdf(sorted_points)
# 计算CDF差值的绝对值
diff_abs = np.abs(cdf_n1 - cdf_n2)
# 找到最大差值对应的位置
max_diff_idx = np.argmax(diff_abs)
statistic_location = sorted_points[max_diff_idx]

print(f"手动计算的CDF最大差异位置: {statistic_location}")

内容的提问来源于stack exchange,提问作者k2pctdn

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.28 20:33:18