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 读取 Excel 数据

《如何使用Python读取Excel数据》:本文主要介绍使用Python读取Excel数据的详细教程,通过pandas和openpyxl,你可以轻松读取Excel文件,并进行各种数据处理操... 目录使用 python 读取 Excel 数据的详细教程1. 安装必要的依赖2. 读取 Excel 文件3. 读

Python的time模块一些常用功能(各种与时间相关的函数)

《Python的time模块一些常用功能(各种与时间相关的函数)》Python的time模块提供了各种与时间相关的函数,包括获取当前时间、处理时间间隔、执行时间测量等,:本文主要介绍Python的... 目录1. 获取当前时间2. 时间格式化3. 延时执行4. 时间戳运算5. 计算代码执行时间6. 转换为指

利用Python调试串口的示例代码

《利用Python调试串口的示例代码》在嵌入式开发、物联网设备调试过程中,串口通信是最基础的调试手段本文将带你用Python+ttkbootstrap打造一款高颜值、多功能的串口调试助手,需要的可以了... 目录概述:为什么需要专业的串口调试工具项目架构设计1.1 技术栈选型1.2 关键类说明1.3 线程模

Python ZIP文件操作技巧详解

《PythonZIP文件操作技巧详解》在数据处理和系统开发中,ZIP文件操作是开发者必须掌握的核心技能,Python标准库提供的zipfile模块以简洁的API和跨平台特性,成为处理ZIP文件的首选... 目录一、ZIP文件操作基础三板斧1.1 创建压缩包1.2 解压操作1.3 文件遍历与信息获取二、进阶技

Python Transformers库(NLP处理库)案例代码讲解

《PythonTransformers库(NLP处理库)案例代码讲解》本文介绍transformers库的全面讲解,包含基础知识、高级用法、案例代码及学习路径,内容经过组织,适合不同阶段的学习者,对... 目录一、基础知识1. Transformers 库简介2. 安装与环境配置3. 快速上手示例二、核心模

Python正则表达式语法及re模块中的常用函数详解

《Python正则表达式语法及re模块中的常用函数详解》这篇文章主要给大家介绍了关于Python正则表达式语法及re模块中常用函数的相关资料,正则表达式是一种强大的字符串处理工具,可以用于匹配、切分、... 目录概念、作用和步骤语法re模块中的常用函数总结 概念、作用和步骤概念: 本身也是一个字符串,其中

Python使用getopt处理命令行参数示例解析(最佳实践)

《Python使用getopt处理命令行参数示例解析(最佳实践)》getopt模块是Python标准库中一个简单但强大的命令行参数处理工具,它特别适合那些需要快速实现基本命令行参数解析的场景,或者需要... 目录为什么需要处理命令行参数?getopt模块基础实际应用示例与其他参数处理方式的比较常见问http

python实现svg图片转换为png和gif

《python实现svg图片转换为png和gif》这篇文章主要为大家详细介绍了python如何实现将svg图片格式转换为png和gif,文中的示例代码讲解详细,感兴趣的小伙伴可以跟随小编一起学习一下... 目录python实现svg图片转换为png和gifpython实现图片格式之间的相互转换延展:基于Py

Python中的getopt模块用法小结

《Python中的getopt模块用法小结》getopt.getopt()函数是Python中用于解析命令行参数的标准库函数,该函数可以从命令行中提取选项和参数,并对它们进行处理,本文详细介绍了Pyt... 目录getopt模块介绍getopt.getopt函数的介绍getopt模块的常用用法getopt模

Python利用ElementTree实现快速解析XML文件

《Python利用ElementTree实现快速解析XML文件》ElementTree是Python标准库的一部分,而且是Python标准库中用于解析和操作XML数据的模块,下面小编就来和大家详细讲讲... 目录一、XML文件解析到底有多重要二、ElementTree快速入门1. 加载XML的两种方式2.