2.7 `scipy.stats`:统计


文档摘要

2.7 :统计 2.7 :统计 模块是 SciPy 库中用于统计计算的核心模块。它包含了大量的统计函数、概率分布、描述性统计、假设检验等工具,为数据分析和科学计算提供了强大的支持。 2.7.1 概率分布 提供了多种连续和离散概率分布,例如正态分布、均匀分布、泊松分布等。每个分布都有一些常用的方法: : 概率密度函数 (Probability Density Function),连续分布使用。 : 概率质量函数 (Probability Mass Function),离散分布使用。 : 累积分布函数 (Cumulative Distribution Function)。 : 生存函数 (Survival Function),即 1 - cdf(x)。

2.7 scipy.stats:统计

2.7 scipy.stats:统计

scipy.stats 模块是 SciPy 库中用于统计计算的核心模块。它包含了大量的统计函数、概率分布、描述性统计、假设检验等工具,为数据分析和科学计算提供了强大的支持。

2.7.1 概率分布

scipy.stats 提供了多种连续和离散概率分布,例如正态分布、均匀分布、泊松分布等。每个分布都有一些常用的方法:

  • pdf(x, *args, loc=0, scale=1): 概率密度函数 (Probability Density Function),连续分布使用。

  • pmf(x, *args, loc=0): 概率质量函数 (Probability Mass Function),离散分布使用。

  • cdf(x, *args, loc=0, scale=1): 累积分布函数 (Cumulative Distribution Function)。

  • sf(x, *args, loc=0, scale=1): 生存函数 (Survival Function),即 1 - cdf(x)。

  • ppf(q, *args, loc=0, scale=1): 分位点函数 (Percent Point Function),即 cdf 的反函数。

  • isf(q, *args, loc=0, scale=1): 逆生存函数 (Inverse Survival Function),即 sf 的反函数。

  • moment(n, *args, loc=0, scale=1): n 阶中心矩。

  • stats(*args, loc=0, scale=1, moments='mv'): 返回均值 (mean)、方差 (variance)、偏度 (skewness)、峰度 (kurtosis)。

  • entropy(*args, loc=0, scale=1): 计算熵。

  • fit(data, *args, loc=0, scale=1): 使用最大似然估计拟合分布参数。

  • rvs(*args, loc=0, scale=1, size=1, random_state=None): 生成随机变量。

2.7.1.1 连续分布

常见的连续分布包括:

  • norm: 正态分布 (Normal Distribution)

  • uniform: 均匀分布 (Uniform Distribution)

  • expon: 指数分布 (Exponential Distribution)

  • gamma: Gamma 分布 (Gamma Distribution)

  • beta: Beta 分布 (Beta Distribution)

  • t: 学生 t 分布 (Student's t-Distribution)

代码实践:正态分布

import numpy as np from scipy.stats import norm import matplotlib.pyplot as plt # 定义 x 轴范围 x = np.linspace(-5, 5, 100) # 计算正态分布的 PDF pdf = norm.pdf(x) # 绘制 PDF plt.plot(x, pdf) plt.xlabel('x') plt.ylabel('PDF') plt.title('Normal Distribution PDF') plt.grid(True) plt.show() # 计算正态分布的 CDF cdf = norm.cdf(x) # 绘制 CDF plt.plot(x, cdf) plt.xlabel('x') plt.ylabel('CDF') plt.title('Normal Distribution CDF') plt.grid(True) plt.show() # 生成 1000 个服从正态分布的随机数 random_numbers = norm.rvs(size=1000) # 绘制直方图 plt.hist(random_numbers, bins=30, density=True) plt.xlabel('Value') plt.ylabel('Frequency') plt.title('Histogram of Random Numbers from Normal Distribution') plt.grid(True) plt.show() # 计算均值和标准差 mean, std = norm.stats(loc=0, scale=1) print(f"Mean: {mean}, Standard Deviation: {std}")

2.7.1.2 离散分布

常见的离散分布包括:

  • binom: 二项分布 (Binomial Distribution)

  • poisson: 泊松分布 (Poisson Distribution)

  • randint: 离散均匀分布 (Discrete Uniform Distribution)

代码实践:泊松分布

import numpy as np from scipy.stats import poisson import matplotlib.pyplot as plt # 定义 x 轴范围 x = np.arange(0, 20) # 计算泊松分布的 PMF (假设 lambda = 5) pmf = poisson.pmf(x, mu=5) # 绘制 PMF plt.plot(x, pmf, marker='o') plt.xlabel('x') plt.ylabel('PMF') plt.title('Poisson Distribution PMF (lambda=5)') plt.grid(True) plt.show() # 计算泊松分布的 CDF (假设 lambda = 5) cdf = poisson.cdf(x, mu=5) # 绘制 CDF plt.plot(x, cdf, marker='o') plt.xlabel('x') plt.ylabel('CDF') plt.title('Poisson Distribution CDF (lambda=5)') plt.grid(True) plt.show() # 生成 1000 个服从泊松分布的随机数 (假设 lambda = 5) random_numbers = poisson.rvs(mu=5, size=1000) # 绘制直方图 plt.hist(random_numbers, bins=20, density=True) plt.xlabel('Value') plt.ylabel('Frequency') plt.title('Histogram of Random Numbers from Poisson Distribution (lambda=5)') plt.grid(True) plt.show() # 计算均值和方差 mean, var = poisson.stats(mu=5) print(f"Mean: {mean}, Variance: {var}")

2.7.2 描述性统计

scipy.stats 提供了计算描述性统计量的函数,例如均值、中位数、方差、标准差、偏度、峰度等。

  • describe(a, axis=0, ddof=1, bias=True, nan_policy='propagate'): 计算描述性统计量。

  • gmean(a, axis=0): 计算几何平均数。

  • hmean(a, axis=0): 计算调和平均数。

  • trim_mean(a, proportiontocut, axis=0): 计算截尾平均数。

  • skew(a, axis=0, bias=True): 计算偏度。

  • kurtosis(a, axis=0, fisher=True, bias=True): 计算峰度。

  • moment(a, moment=1, axis=0): 计算 n 阶中心矩。

代码实践:描述性统计

import numpy as np from scipy.stats import describe, skew, kurtosis # 创建一个示例数据集 data = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]) # 计算描述性统计量 description = describe(data) print(description) # 计算偏度 skewness = skew(data) print(f"Skewness: {skewness}") # 计算峰度 kurt = kurtosis(data) print(f"Kurtosis: {kurt}")

2.7.3 假设检验

scipy.stats 提供了多种假设检验的函数,例如 t 检验、卡方检验、 Kolmogorov-Smirnov 检验等。

  • ttest_1samp(a, popmean, axis=0): 单样本 t 检验。

  • ttest_ind(a, b, axis=0, equal_var=True): 独立样本 t 检验。

  • ttest_rel(a, b, axis=0): 配对样本 t 检验。

  • chisquare(f_obs, f_exp=None): 卡方检验。

  • kstest(rvs, cdf, args=(), N=20): Kolmogorov-Smirnov 检验。

代码实践:独立样本 t 检验

import numpy as np from scipy.stats import ttest_ind # 创建两个示例数据集 data1 = np.array([1, 2, 3, 4, 5]) data2 = np.array([6, 7, 8, 9, 10]) # 进行独立样本 t 检验 t_statistic, p_value = ttest_ind(data1, data2) print(f"T-statistic: {t_statistic}") print(f"P-value: {p_value}") # 判断是否显著 alpha = 0.05 if p_value < alpha: print("Reject the null hypothesis") else: print("Fail to reject the null hypothesis")

2.7.4 相关性分析

scipy.stats 提供了计算相关系数的函数,例如皮尔逊相关系数、斯皮尔曼相关系数等。

  • pearsonr(x, y): 计算皮尔逊相关系数和 p 值。

  • spearmanr(a, b, axis=0): 计算斯皮尔曼相关系数和 p 值。

代码实践:皮尔逊相关系数

import numpy as np from scipy.stats import pearsonr # 创建两个示例数据集 x = np.array([1, 2, 3, 4, 5]) y = np.array([2, 4, 6, 8, 10]) # 计算皮尔逊相关系数 correlation, p_value = pearsonr(x, y) print(f"Pearson correlation coefficient: {correlation}") print(f"P-value: {p_value}")

2.7.5 统计图表

虽然 scipy.stats 本身不直接提供绘图功能,但可以结合 matplotlib 等库来可视化统计数据和结果。

代码实践:绘制直方图和核密度估计 (KDE)

import numpy as np import matplotlib.pyplot as plt from scipy.stats import norm from scipy.stats import gaussian_kde # 生成一些随机数据 data = np.random.normal(loc=0, scale=1, size=1000) # 绘制直方图 plt.hist(data, bins=30, density=True, alpha=0.5, label='Histogram') # 计算核密度估计 kde = gaussian_kde(data) x = np.linspace(-5, 5, 100) plt.plot(x, kde(x), label='KDE') # 绘制正态分布曲线作为参考 plt.plot(x, norm.pdf(x), label='Normal PDF') plt.xlabel('Value') plt.ylabel('Density') plt.title('Histogram and KDE') plt.legend() plt.grid(True) plt.show()

2.7.6 scipy.stats 模块结构图

2.7.7 总结

scipy.stats 模块是 SciPy 库中用于统计分析的重要组成部分。它提供了丰富的统计函数和概率分布,可以进行描述性统计、假设检验、相关性分析等操作。通过结合 matplotlib 等库,可以方便地可视化统计数据和结果。熟练掌握 scipy.stats 模块,可以为数据分析和科学计算提供强大的支持。


作者与出处
原作者: 灏天文库
来源:灏天文库
整理: 灏天文库整理
由灏天文库平台收录,内容或由平台用户上传,仅供学习交流
发布者: 作者: 灏天文库 转发
评论区 (0)
U