Python检验样本是否服从正态分布

2024-04-24 20:38

本文主要是介绍Python检验样本是否服从正态分布,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

在进行t检验、F检验之前,我们往往要求样本大致服从正态分布,下面介绍两种检验样本是否服从正态分布的方法。

1 可视化

我们可以通过将样本可视化,看一下样本的概率密度是否是正态分布来初步判断样本是否服从正态分布。

代码如下:

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt# 使用pandas和numpy生成一组仿真数据
s = pd.DataFrame(np.random.randn(500),columns=['value'])
print(s.shape)      # (500, 1)# 创建自定义图像
fig = plt.figure(figsize=(10, 6))
# 创建子图1
ax1 = fig.add_subplot(2,1,1)
# 绘制散点图
ax1.scatter(s.index, s.values)
plt.grid()      # 添加网格# 创建子图2
ax2 = fig.add_subplot(2, 1, 2)
# 绘制直方图
s.hist(bins=30,alpha=0.5,ax=ax2)
# 绘制密度图
s.plot(kind='kde', secondary_y=True,ax=ax2)     # 使用双坐标轴
plt.grid()      # 添加网格# 显示自定义图像
plt.show()

 可视化图像如下:

从图中可以初步看出生成的数据近似服从正态分布。为了得到更具说服力的结果,我们可以使用统计检验的方法,这里使用的是.scipy.stats中的函数。

2 统计检验

1)kstest

scipy.stats.kstest函数可用于检验样本是否服从正态、指数、伽马等分布,函数的源代码为:

def kstest(rvs, cdf, args=(), N=20, alternative='two-sided', mode='approx'):"""Perform the Kolmogorov-Smirnov test for goodness of fit.This performs a test of the distribution F(x) of an observedrandom variable against a given distribution G(x). Under the nullhypothesis the two distributions are identical, F(x)=G(x). Thealternative hypothesis can be either 'two-sided' (default), 'less'or 'greater'. The KS test is only valid for continuous distributions.Parameters----------rvs : str, array or callableIf a string, it should be the name of a distribution in `scipy.stats`.If an array, it should be a 1-D array of observations of randomvariables.If a callable, it should be a function to generate random variables;it is required to have a keyword argument `size`.cdf : str or callableIf a string, it should be the name of a distribution in `scipy.stats`.If `rvs` is a string then `cdf` can be False or the same as `rvs`.If a callable, that callable is used to calculate the cdf.args : tuple, sequence, optionalDistribution parameters, used if `rvs` or `cdf` are strings.N : int, optionalSample size if `rvs` is string or callable.  Default is 20.alternative : {'two-sided', 'less','greater'}, optionalDefines the alternative hypothesis (see explanation above).Default is 'two-sided'.mode : 'approx' (default) or 'asymp', optionalDefines the distribution used for calculating the p-value.- 'approx' : use approximation to exact distribution of test statistic- 'asymp' : use asymptotic distribution of test statisticReturns-------statistic : floatKS test statistic, either D, D+ or D-.pvalue :  floatOne-tailed or two-tailed p-value.

2)normaltest

scipy.stats.normaltest函数专门用于检验样本是否服从正态分布,函数的源代码为:

def normaltest(a, axis=0, nan_policy='propagate'):"""Test whether a sample differs from a normal distribution.This function tests the null hypothesis that a sample comesfrom a normal distribution.  It is based on D'Agostino andPearson's [1]_, [2]_ test that combines skew and kurtosis toproduce an omnibus test of normality.Parameters----------a : array_likeThe array containing the sample to be tested.axis : int or None, optionalAxis along which to compute test. Default is 0. If None,compute over the whole array `a`.nan_policy : {'propagate', 'raise', 'omit'}, optionalDefines how to handle when input contains nan. 'propagate' returns nan,'raise' throws an error, 'omit' performs the calculations ignoring nanvalues. Default is 'propagate'.Returns-------statistic : float or array``s^2 + k^2``, where ``s`` is the z-score returned by `skewtest` and``k`` is the z-score returned by `kurtosistest`.pvalue : float or arrayA 2-sided chi squared probability for the hypothesis test.

3)shapiro

scipy.stats.shapiro函数也是用于专门做正态检验的,函数的源代码为:

def shapiro(x):"""Perform the Shapiro-Wilk test for normality.The Shapiro-Wilk test tests the null hypothesis that thedata was drawn from a normal distribution.Parameters----------x : array_likeArray of sample data.Returns-------W : floatThe test statistic.p-value : floatThe p-value for the hypothesis test.

下面我们使用第一部分生成的仿真数据,用这三种统计检验函数检验生成的样本是否服从正态分布(p > 0.05),代码如下:

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt# 使用pandas和numpy生成一组仿真数据
s = pd.DataFrame(np.random.randn(500),columns=['value'])
print(s.shape)      # (500, 1)# 计算均值
u = s['value'].mean()
# 计算标准差
std = s['value'].std()  # 计算标准差
print('scipy.stats.kstest统计检验结果:----------------------------------------------------')
print(stats.kstest(s['value'], 'norm', (u, std)))
print('scipy.stats.normaltest统计检验结果:----------------------------------------------------')
print(stats.normaltest(s['value']))
print('scipy.stats.shapiro统计检验结果:----------------------------------------------------')
print(stats.shapiro(s['value']))

统计检验结果如下:

scipy.stats.kstest统计检验结果:----------------------------------------------------
KstestResult(statistic=0.01596290473494305, pvalue=0.9995623150120069)
scipy.stats.normaltest统计检验结果:----------------------------------------------------
NormaltestResult(statistic=0.5561685865675511, pvalue=0.7572329891688141)
scipy.stats.shapiro统计检验结果:----------------------------------------------------
(0.9985257983207703, 0.9540967345237732)

可以看到使用三种方法检验样本是否服从正态分布的结果中p-value都大于0.05,说明服从原假设,即生成的仿真数据服从正态分布。

参考

python数据分析----卡方检验,T检验,F检验,K-S检验

python使用scipy.stats数据(正态)分布检验方法

python 如何判断一组数据是否符合正态分布

这篇关于Python检验样本是否服从正态分布的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/932792

相关文章

Python开发文字版随机事件游戏的项目实例

《Python开发文字版随机事件游戏的项目实例》随机事件游戏是一种通过生成不可预测的事件来增强游戏体验的类型,在这篇博文中,我们将使用Python开发一款文字版随机事件游戏,通过这个项目,读者不仅能够... 目录项目概述2.1 游戏概念2.2 游戏特色2.3 目标玩家群体技术选择与环境准备3.1 开发环境3

Python中模块graphviz使用入门

《Python中模块graphviz使用入门》graphviz是一个用于创建和操作图形的Python库,本文主要介绍了Python中模块graphviz使用入门,具有一定的参考价值,感兴趣的可以了解一... 目录1.安装2. 基本用法2.1 输出图像格式2.2 图像style设置2.3 属性2.4 子图和聚

Python使用Matplotlib绘制3D曲面图详解

《Python使用Matplotlib绘制3D曲面图详解》:本文主要介绍Python使用Matplotlib绘制3D曲面图,在Python中,使用Matplotlib库绘制3D曲面图可以通过mpl... 目录准备工作绘制简单的 3D 曲面图绘制 3D 曲面图添加线框和透明度控制图形视角Matplotlib

一文教你Python如何快速精准抓取网页数据

《一文教你Python如何快速精准抓取网页数据》这篇文章主要为大家详细介绍了如何利用Python实现快速精准抓取网页数据,文中的示例代码简洁易懂,具有一定的借鉴价值,有需要的小伙伴可以了解下... 目录1. 准备工作2. 基础爬虫实现3. 高级功能扩展3.1 抓取文章详情3.2 保存数据到文件4. 完整示例

使用Python实现IP地址和端口状态检测与监控

《使用Python实现IP地址和端口状态检测与监控》在网络运维和服务器管理中,IP地址和端口的可用性监控是保障业务连续性的基础需求,本文将带你用Python从零打造一个高可用IP监控系统,感兴趣的小伙... 目录概述:为什么需要IP监控系统使用步骤说明1. 环境准备2. 系统部署3. 核心功能配置系统效果展

基于Python打造一个智能单词管理神器

《基于Python打造一个智能单词管理神器》这篇文章主要为大家详细介绍了如何使用Python打造一个智能单词管理神器,从查询到导出的一站式解决,感兴趣的小伙伴可以跟随小编一起学习一下... 目录1. 项目概述:为什么需要这个工具2. 环境搭建与快速入门2.1 环境要求2.2 首次运行配置3. 核心功能使用指

Python实现微信自动锁定工具

《Python实现微信自动锁定工具》在数字化办公时代,微信已成为职场沟通的重要工具,但临时离开时忘记锁屏可能导致敏感信息泄露,下面我们就来看看如何使用Python打造一个微信自动锁定工具吧... 目录引言:当微信隐私遇到自动化守护效果展示核心功能全景图技术亮点深度解析1. 无操作检测引擎2. 微信路径智能获

Python中pywin32 常用窗口操作的实现

《Python中pywin32常用窗口操作的实现》本文主要介绍了Python中pywin32常用窗口操作的实现,pywin32主要的作用是供Python开发者快速调用WindowsAPI的一个... 目录获取窗口句柄获取最前端窗口句柄获取指定坐标处的窗口根据窗口的完整标题匹配获取句柄根据窗口的类别匹配获取句

利用Python打造一个Excel记账模板

《利用Python打造一个Excel记账模板》这篇文章主要为大家详细介绍了如何使用Python打造一个超实用的Excel记账模板,可以帮助大家高效管理财务,迈向财富自由之路,感兴趣的小伙伴快跟随小编一... 目录设置预算百分比超支标红预警记账模板功能介绍基础记账预算管理可视化分析摸鱼时间理财法碎片时间利用财

Python中的Walrus运算符分析示例详解

《Python中的Walrus运算符分析示例详解》Python中的Walrus运算符(:=)是Python3.8引入的一个新特性,允许在表达式中同时赋值和返回值,它的核心作用是减少重复计算,提升代码简... 目录1. 在循环中避免重复计算2. 在条件判断中同时赋值变量3. 在列表推导式或字典推导式中简化逻辑