Python数据正态性检验实现过程


Posted in Python onApril 18, 2020

在做数据分析或者统计的时候,经常需要进行数据正态性的检验,因为很多假设都是基于正态分布的基础之上的,例如:T检验。

在Python中,主要有以下检验正态性的方法:

1.scipy.stats.shapiro ——Shapiro-Wilk test,属于专门用来做正态性检验的模块,其原假设:样本数据符合正态分布。

注:适用于小样本。

其函数定位为:

def shapiro(x):
  """
  Perform the Shapiro-Wilk test for normality.

  The Shapiro-Wilk test tests the null hypothesis that the
  data was drawn from a normal distribution.

  Parameters
  ----------
  x : array_like
    Array of sample data.

  Returns
  -------
  W : float
    The test statistic.
  p-value : float
    The p-value for the hypothesis test.

x参数为样本值序列,返回值中第一个为检验统计量,第二个为P值,当P值大于指定的显著性水平,则接受原假设。

2.scipy.stats.kstest(K-S检验):可以检验多种分布,不止正态分布,其原假设:数据符合正态分布。

其函数定义为:

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 G(x) of an observed
  random variable against a given distribution F(x). Under the null
  hypothesis the two distributions are identical, G(x)=F(x). The
  alternative hypothesis can be either 'two-sided' (default), 'less'
  or 'greater'. The KS test is only valid for continuous distributions.

  Parameters
  ----------
  rvs : str, array or callable
    If 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 random
    variables.
    If a callable, it should be a function to generate random variables;
    it is required to have a keyword argument `size`.
  cdf : str or callable
    If 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, optional
    Distribution parameters, used if `rvs` or `cdf` are strings.
  N : int, optional
    Sample size if `rvs` is string or callable. Default is 20.
  alternative : {'two-sided', 'less','greater'}, optional
    Defines the alternative hypothesis (see explanation above).
    Default is 'two-sided'.
  mode : 'approx' (default) or 'asymp', optional
    Defines the distribution used for calculating the p-value.

     - 'approx' : use approximation to exact distribution of test statistic
     - 'asymp' : use asymptotic distribution of test statistic

  Returns
  -------
  statistic : float
    KS test statistic, either D, D+ or D-.
  pvalue : float
    One-tailed or two-tailed p-value.

参数是:

rvs:待检验数据。

cdf:检验分布,例如'norm','expon','rayleigh','gamma'等分布,设置为'norm'时表示正态分布。

alternative:默认为双侧检验,可以设置为'less'或'greater'作单侧检验。

model:'approx'(默认值),表示使用检验统计量的精确分布的近视值;'asymp':使用检验统计量的渐进分布。

其返回值中第一个为统计量,第二个为P值。

3.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 comes
  from a normal distribution. It is based on D'Agostino and
  Pearson's [1]_, [2]_ test that combines skew and kurtosis to
  produce an omnibus test of normality.


  Parameters
  ----------
  a : array_like
    The array containing the sample to be tested.
  axis : int or None, optional
    Axis along which to compute test. Default is 0. If None,
    compute over the whole array `a`.
  nan_policy : {'propagate', 'raise', 'omit'}, optional
    Defines how to handle when input contains nan. 'propagate' returns nan,
    'raise' throws an error, 'omit' performs the calculations ignoring nan
    values. 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 array
    A 2-sided chi squared probability for the hypothesis test.

其参数:

axis=None 可以表示对整个数据做检验,默认值是0。

nan_policy:当输入的数据中有nan时,'propagate',返回空值;'raise' 时,抛出错误;'omit' 时,忽略空值。

其返回值中,第一个是统计量,第二个是P值。

4.scipy.stats.anderson:由 scipy.stats.kstest 改进而来,用于检验样本是否属于某一分布(正态分布、指数分布、logistic 或者 Gumbel等分布)

其函数定义为:

def anderson(x, dist='norm'):
  """
  Anderson-Darling test for data coming from a particular distribution

  The Anderson-Darling tests the null hypothesis that a sample is
  drawn from a population that follows a particular distribution.
  For the Anderson-Darling test, the critical values depend on
  which distribution is being tested against. This function works
  for normal, exponential, logistic, or Gumbel (Extreme Value
  Type I) distributions.

  Parameters
  ----------
  x : array_like
    array of sample data
  dist : {'norm','expon','logistic','gumbel','gumbel_l', gumbel_r',
    'extreme1'}, optional
    the type of distribution to test against. The default is 'norm'
    and 'extreme1', 'gumbel_l' and 'gumbel' are synonyms.

  Returns
  -------
  statistic : float
    The Anderson-Darling test statistic
  critical_values : list
    The critical values for this distribution
  significance_level : list
    The significance levels for the corresponding critical values
    in percents. The function returns critical values for a
    differing set of significance levels depending on the
    distribution that is being tested against.

其参数:

x和dist分别表示样本数据和分布。

返回值有三个,第一个表示统计值,第二个表示评价值,第三个是显著性水平;评价值和显著性水平对应。

对于不同的分布,显著性水平不一样。

Critical values provided are for the following significance levels:

  normal/exponenential
    15%, 10%, 5%, 2.5%, 1%
  logistic
    25%, 10%, 5%, 2.5%, 1%, 0.5%
  Gumbel
    25%, 10%, 5%, 2.5%, 1%

关于统计值与评价值的对比:当统计值大于这些评价值时,表示在对应的显著性水平下,原假设被拒绝,即不属于某分布。

If the returned statistic is larger than these critical values then for the corresponding significance level, the null hypothesis that the data come from the chosen distribution can be rejected.

5.skewtest 和kurtosistest 检验:用于检验样本的skew(偏度)和kurtosis(峰度)是否与正态分布一致,因为正态分布的偏度=0,峰度=3。

偏度:偏度是样本的标准三阶中心矩。

Python数据正态性检验实现过程

峰度:峰度是样本的标准四阶中心矩。

Python数据正态性检验实现过程

6. 代码如下:

import numpy as np
from scipy import stats

a = np.random.normal(0,2,50)
b = np.linspace(0, 10, 100)

# Shapiro-Wilk test
S,p = stats.shapiro(a)
print('the shapiro test result is:',S,',',p)

# kstest(K-S检验)
K,p = stats.kstest(a, 'norm')
print(K,p)

# normaltest
N,p = stats.normaltest(b)
print(N,p)

# Anderson-Darling test
A,C,p = stats.anderson(b,dist='norm')
print(A,C,p)

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持三水点靠木。

Python 相关文章推荐
Django中URL视图函数的一些高级概念介绍
Jul 20 Python
python正则表达式爬取猫眼电影top100
Feb 24 Python
TensorFlow卷积神经网络之使用训练好的模型识别猫狗图片
Mar 14 Python
Python流行ORM框架sqlalchemy安装与使用教程
Jun 04 Python
python selenium 查找隐藏元素 自动播放视频功能
Jul 24 Python
Python imageio读取视频并进行编解码详解
Dec 10 Python
python中的subprocess.Popen()使用详解
Dec 25 Python
python pycharm最新版本激活码(永久有效)附python安装教程
Sep 18 Python
Python判断远程服务器上Excel文件是否被人打开的方法
Jul 13 Python
对Python 字典元素进行删除的方法
Jul 31 Python
python 使用建议与技巧分享(四)
Aug 18 Python
Django怎么在admin后台注册数据库表
Nov 14 Python
如何基于线程池提升request模块效率
Apr 18 #Python
新建文件时Pycharm中自动设置头部模板信息的方法
Apr 17 #Python
使用python无账号无限制获取企查查信息的实例代码
Apr 17 #Python
jupyter notebook中美观显示矩阵实例
Apr 17 #Python
Python3将ipa包中的文件按大小排序
Apr 17 #Python
利用pyecharts读取csv并进行数据统计可视化的实现
Apr 17 #Python
pyecharts动态轨迹图的实现示例
Apr 17 #Python
You might like
php使用PDO从数据库表中读取数据的实现方法(必看)
2017/06/02 PHP
php中加密解密DES类的简单使用方法示例
2020/03/26 PHP
PHP使用Http Post请求发送Json对象数据代码解析
2020/07/16 PHP
lib.utf.js
2007/08/21 Javascript
使用JSLint提高JS代码质量方法分享
2013/12/16 Javascript
jQuery中offset()方法用法实例
2015/01/16 Javascript
jquery实现列表上下移动功能
2016/02/25 Javascript
jquery 动态合并单元格的实现方法
2016/08/26 Javascript
js利用appendChild对标签进行排序的实现方法
2016/10/16 Javascript
微信小程序 获取微信OpenId详解及实例代码
2016/10/31 Javascript
WebView启动支付宝客户端支付失败的问题小结
2017/01/11 Javascript
使用Node.js写一个代码生成器的方法步骤
2019/05/10 Javascript
解决微信浏览器缓存站点入口文件(IIS部署Vue项目)
2019/06/17 Javascript
vue组件中节流函数的失效的原因和解决方法
2020/12/02 Vue.js
[36:02]DOTA2上海特级锦标赛D组小组赛#2 Liquid VS VP第一局
2016/02/28 DOTA
Cpy和Python的效率对比
2015/03/20 Python
python使用BeautifulSoup分析网页信息的方法
2015/04/04 Python
python tensorflow基于cnn实现手写数字识别
2018/01/01 Python
从DataFrame中提取出Series或DataFrame对象的方法
2018/11/10 Python
python使用mitmproxy抓取浏览器请求的方法
2019/07/02 Python
Python Tkinter模块 GUI 可视化实例
2019/11/20 Python
PyCharm使用Docker镜像搭建Python开发环境
2019/12/26 Python
CSS3中利用animation属性创建雪花飘落特效
2014/05/14 HTML / CSS
详解FireFox下Canvas使用图像合成绘制SVG的Bug
2019/07/10 HTML / CSS
HTML5 WebSocket实现点对点聊天的示例代码
2018/01/31 HTML / CSS
埃弗顿足球俱乐部官方网上商店:Everton Direct
2018/01/13 全球购物
英国屋顶用品和材料超市:Roofing Supplies UK
2019/08/24 全球购物
Magee 1866官网:Donegal粗花呢外套和大衣专家
2019/11/01 全球购物
北京SQL新华信咨询
2016/09/30 面试题
预防传染病方案
2014/06/14 职场文书
党在我心中的演讲稿
2014/09/13 职场文书
迎新生标语大全
2014/10/06 职场文书
故宫导游词
2015/01/31 职场文书
2015年大学宣传部工作总结
2015/05/26 职场文书
导游词之云南-元阳梯田
2019/10/08 职场文书
淡雅古典唯美少女娇媚宁静迷人写真
2022/03/21 杂记