假设检验的基本思想

若对总体的某个假设是真实的,那么不利于或者不能支持这一假设的事件A在一次试验中是几乎不可能发生的;如果事件A真的发生了,则有理由怀疑这一假设的真实性,从而拒绝该假设;

假设检验实质上是对原假设是否正确进行检验,因此检验过程中要使原假设得到维护,使之不轻易被拒绝;否定原假设必须有充分的理由。同时,当原假设被接受时,也只能认为否定该假设的根据不充分,而不是认为它绝对正确

ks 检验

ks 检验分为 单样本 和两样本 检验;

单样本检验 用于 检验 一个数据的观测分布 是否符合 某种理论分布;

两样本检验 用于检验 两个样本是否 属于 同一分布,ks 检验 是 两样本检验最有用且最常用的非参数方法之一;

ks 检验 不仅能检验正态分布,还能检验其他分布;

def kstest(rvs, cdf, args=(), N=20, alternative='two-sided', mode='approx'):
"""
Parameters
----------
rvs : str, array_like, 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`.
Returns
-------
statistic : float
KS test statistic, either D, D+ or D-.
pvalue : float
One-tailed or two-tailed p-value.
"""

rvs:待检验的数据,1-D 数组

cdf:待检验的分布,如 norm 正态检验

alternative:默认为双尾检验,可以设置为‘less’或‘greater’作单尾检验

statistic:统计结果

pvalue:p 值 越大,越支持原假设,一般会和指定显著水平 5% 比较,大于 5%,支持原假设;【支持原假设无法否定原假设,不代表原假设绝对正确】

单样本检验示例

######### 非正态 #########
x1 = np.linspace(-15, 15, 9)
print(kstest(x1, 'norm'))
# KstestResult(statistic=0.4443560271592436, pvalue=0.03885014270517116) <0.05 ######### 正态 #########
np.random.seed(1000)
x2 = np.random.randn(100)
print(kstest(x2, 'norm'))
# KstestResult(statistic=0.06029093862878099, pvalue=0.8604070909241421) >0.05 #### 同一个数据(服从正态分布),不同的参数有截然不同的检测结果,说明 ks 检测 正态性 比较麻烦
x3 = np.random.normal(100, 0.01, 1000)
print(kstest(x3, 'norm'))
# KstestResult(statistic=1.0, pvalue=0.0) <0.05
print(kstest(x3, 'norm', alternative='greater'))
# KstestResult(statistic=0.0, pvalue=1.0) >0.05

两样本检验示例

import numpy as np
from scipy.stats import ks_2samp, kstest beta=np.random.beta(7, 5, 1000)
norm=np.random.normal(0, 1, 1000)
print(ks_2samp(beta, norm))
# Ks_2sampResult(statistic=0.578, pvalue=7.844864182954565e-155) # p-value比指定的显著水平(假设为5%)小,则我们完全可以拒绝假设:beta和norm不服从同一分布

shapiro 正态检验

专门做 正态检验 的模块

shapiro 不适合做样本数>5000的正态性检验,检验结果的P值可能不准确

def shapiro(x):
"""
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 = np.random.rand(100)
print(stats.shapiro(x))
# (0.9387611746788025, 0.00016213695926126093) <0.05 ######### 正态 #########
x1 = stats.norm.rvs(loc=5, scale=3, size=100)
print(stats.shapiro(x1))
# (0.9818177223205566, 0.18372832238674164) >0.05 np.random.seed(1000)
x2 = np.random.randn(100)
print(stats.shapiro(x2))
# (0.9930729269981384, 0.89242023229599) >0.05 #### 同样的数据,ks 检测 非正态,shapiro 检测 正态
x3 = np.random.normal(100, 0.01, 1000)
print(stats.shapiro(x3))
# (0.9976787567138672, 0.17260634899139404) >0.05

normaltest

也是专门做 正态检测 的模块

def normaltest(a, axis=0, nan_policy='propagate'):
"""
Parameters
----------
a : array_like
The array containing the sample to be tested.
Returns
-------
statistic : float or array
pvalue : float or array
A 2-sided chi squared probability for the hypothesis test.
"""

示例

######### 非正态 #########
x = np.random.rand(100)
print(normaltest(x))
# NormaltestResult(statistic=17.409796250892015, pvalue=0.00016577184786199797) <0.05 ######### 正态 #########
x1 = np.random.randn(10, 20)
print(normaltest(x1, axis=None))
#NormaltestResult(statistic=1.8245865103063612, pvalue=0.4016021909152733) >0.05 np.random.seed(1000)
x2 = np.random.randn(100)
print(normaltest(x2))
# NormaltestResult(statistic=1.2417269613653144, pvalue=0.5374801334521462) >0.05 #### 同样的数据,ks 检测 非正态,shapiro 检测 正态, normaltest 检测 正态
x3 = np.random.normal(100, 0.01, 1000)
print(normaltest(x3))
# NormaltestResult(statistic=3.3633106484154944, pvalue=0.18606572188584633) >0.05

anderson

增强版的 ks 检测

def anderson(x, dist='norm'):
"""
Anderson-Darling test for data coming from a particular distribution.
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.
"""

anderson 有三个输出值,第一个为统计数,第二个为评判值,第三个为显著性水平,

评判值与显著性水平对应,

对于正态性检验,显著性水平为:15%, 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.

示例

######### 非正态 #########
x1 = np.random.rand(100)
print(anderson(x1))
# AndersonResult(statistic=2.297910919361925, critical_values=array([0.555, 0.632, 0.759, 0.885, 1.053]), significance_level=array([15. , 10. , 5. , 2.5, 1. ]))
### 统计数 大于 评判值,拒绝假设,非正态 ######### 正态 #########
x2 = np.random.randn(100)
print(anderson(x2))
# AndersonResult(statistic=0.35148092757619054, critical_values=array([0.555, 0.632, 0.759, 0.885, 1.053]), significance_level=array([15. , 10. , 5. , 2.5, 1. ]))
### 统计数 小于 评判值,正态 #### 同样的数据,ks 检测 非正态,shapiro 检测 正态
np.random.seed(1000)
x3 = np.random.normal(100, 0.01, 1000)
print(anderson(x3))
# AndersonResult(statistic=0.201867508676969, critical_values=array([0.574, 0.653, 0.784, 0.914, 1.088]), significance_level=array([15. , 10. , 5. , 2.5, 1. ]))
### 统计数 小于 评判值,正态

Q-Q 图

QQ 图功能很多,本文仅介绍如何使用它进行 正态性检测

def probplot(x, sparams=(), dist='norm', fit=True, plot=None, rvalue=False)

示例

import numpy as np
import matplotlib.pyplot as plt
import scipy.stats as st fig, axs = plt.subplots(3, 1) ######### 非正态 #########
x1 = np.random.randint(1, 100, 100)
st.probplot(x1, plot=axs[0]) ######### 正态 #########
np.random.seed(1000)
x2 = np.random.randn(100)
st.probplot(x2, plot=axs[1]) #### ks 检验非正态,看看 qq 图
x3 = np.random.normal(100, 0.01, 1000)
st.probplot(x3, plot=axs[2]) plt.show()

输出:图 1 为 非正态,图 2 3 为正态

红色线条表示正态分布,蓝色线条表示样本数据,蓝色越接近红色参考线,说明越符合预期分布(这是是正态分布)

正态化处理

在做回归分析时,经常需要 把 非正态 数据 转换成 正态 数据,方法如下

在一些情况下(P值<0.003)上述方法很难实现正态化处理,此时可使用 BOX-COX 转换,但是当P值>0.003时两种方法均可,优先考虑普通的平方变换

boxcox 示例

from scipy.stats import kstest, shapiro
from scipy.stats import boxcox
import matplotlib.pyplot as plt
from scipy import stats fig, axs = plt.subplots(2, 1)
np.random.seed(12345) x = np.random.normal(100, 20, 200) + np.random.normal(40, 5, 200)
x = np.log2(x) print(shapiro(x))
# (0.9857848882675171, 0.04184681549668312) ### 非正态
stats.probplot(x, plot=axs[0]) x2, _ = boxcox(x)
print(shapiro(x2))
# (0.9948143362998962, 0.7225888967514038) ### 正态
stats.probplot(x2, plot=axs[1])
plt.show()

输出:上图为 非正态,下图为 经 boxcox 转换后的 正态数据

参考资料:

https://blog.csdn.net/QimaoRyan/article/details/72861387

https://www.jianshu.com/p/a264b8a245d2  ks检验

https://www.cnblogs.com/arkenstone/p/5496761.html    ks检验

https://docs.scipy.org/doc/scipy/reference/generated/scipy.stats.anderson.html#scipy.stats.anderson    scipy.stats.anderson

https://docs.scipy.org/doc/scipy-0.7.x/reference/generated/scipy.stats.kstest.html  scipy.stats.kstest

SciPy - 正态性 与 KS 检验的更多相关文章

  1. s检验|k-S检验|适应性检验|独立性检验|Cintinuity correction |Fisher‘s Exact Test|Likelihood Ratio|Person Chi-Square|φ系数|Cramer’s V|列联系数

    应用统计学: s检验是检验否符合正态,而k-S检验是检验否符合一种分布. 已知分布便知道参数,知道参数不知道分布. 适应性检验 多项式分布的情况如下例: 二项分布是多项式分布一种情况,所以就是上式中只 ...

  2. 连续型变量的推断性分析——t检验

    连续型变量的推断性分析方法主要有t检验和方差分析两种,这两种方法可以解决一些实际的分析问题,下面我们分别来介绍一下这两种方法 一.t检验(Student's t test) t检验也称student ...

  3. R 正态性检验:正态概率图

    检验模型是否满足正态性假设的方法: 1.正态概率图 这是我编写的画正态概率图的函数: #绘制正态概率图 plot_ZP = function(ti) #输入外部学生化残差 { n = length(t ...

  4. 数据分布转换:非正态 -> 正态

    来源:丁香园论坛:SPSS上的把非正态分布数据转换为正态分布数据 一楼 可以应用变量变换的方法,将不服从正态分布的资料转化为非正态分布或近似正态分布.常用的变量变换方法有对数变换.平方根变换.倒数变换 ...

  5. 【R】正态检验与R语言

    正态检验与R语言 1.Kolmogorov–Smirnov test 统计学里, Kolmogorov–Smirnov 检验(亦称:K–S 检验)是用来检验数据是否符合某种分布的一种非参数检验,通过比 ...

  6. Jarque-Bera test|pp图|K-S检验|

    Jarque-Bera test: 如何绘制pp图?   找该直线的截距和斜率,通过截距和斜率的值找到正态参数均值和方差,可对这些正态参数进行正态检验. K-S检验的的特点? 并不是只针对正态分布,是 ...

  7. PP图|QQ图|正态性检验|K-S检验|S-W检验|

    应用统计学: 物理条件一致时,有理由认为方差是一致的.配对检验可排除物理影响,使方差变小,但是自由度降低了,即样本数变小.二项分布均值假设检验的模型要依据前面的假设条件: PP图统计图要看中间的贴近情 ...

  8. 正态QQ图的原理

    code{white-space: pre;} pre:not([class]) { background-color: white; }if (window.hljs && docu ...

  9. 使用K-S检验一个数列是否服从正态分布、两个数列是否服从相同的分布

    假设检验的基本思想: 若对总体的某个假设是真实的,那么不利于或者不能支持这一假设的事件A在一次试验中是几乎不可能发生的.如果事件A真的发生了,则有理由怀疑这一假设的真实性,从而拒绝该假设. 实质分析: ...

随机推荐

  1. Flutter 裁剪类组件 最全总结

    注意:无特殊说明,Flutter版本及Dart版本如下: Flutter版本: 1.12.13+hotfix.5 Dart版本: 2.7.0 ClipRect ClipRect组件使用矩形裁剪子组件, ...

  2. 2020Ubuntu server1804最新安装后的配置

    一.Putty进行ssh连接. 完成最基本配置之后,就远程连接服务器了.在windows是我习惯putty 在我以前的老电脑里面找一个putty是0.6版本的,连上Ip ,还是原来的配方,还是原来的味 ...

  3. 内存管理 malloc free 的实现

    libc 中提供非常好用的  malloc free 功能,如果自己实现一个,应该怎么做. 要实现 malloc free 需要有 可以分配内存使用的堆,和记录内存使用情况的链表. 如下图所示,堆从高 ...

  4. ElasticSearch 6.2.4 实践

    参考资料 ElasticSearch 官网 ElasticSearch,Kibana,Asp.net Core with docker 示例 阮一峰 ElasticSearch 基础概念 索引(ind ...

  5. 浅谈Java中静态代码块和非静态代码块

    静态代码块: static{} 执行优先级高于非静态的初始化块,它会在类初始化(类初始化这个问题改天再详细讨论)的时候执行一次,执行完成便销毁,它仅能初始化类变量,即static修饰的数据成员. 非静 ...

  6. Simulink仿真入门到精通(十九) 总结回顾&自我练习

    从2019年12月27到2020年2月12日,学习了Simulink仿真及代码生成技术入门到精通,历时17天. 学习的比较粗糙,有一些地方还没理解透彻,全书梳理总结: Simulink的基础模块已基本 ...

  7. (转)GNU风格ARM汇编语法指南(非常详细)1

    原文地址:http://zqwt.012.blog.163.com/blog/static/120446842010111481551809/ 汇编源程序一般用于系统最基本的初始化:初始化堆栈指针.设 ...

  8. GoJS学习笔记 (转)

    目录 基础概念 开始绘制图形 1. 通过代码构建图形 2. 通过 GraphObject.make 构建图形 3. 使用 Model 和 Templates 创建图形 获取图形数据 获取所有 Node ...

  9. python获取群成员信息

    #coding: utf-8 import itchat,datetime from itchat.content import TEXT itchat.auto_login(hotReload=Tr ...

  10. 使用WireShark进行网络流量安全分析

    WireShark的过滤规则 伯克利包过滤(BPF)(应用在wireshark的捕获过滤器上) ** 伯克利包过滤中的限定符有下面的三种:** Type:这种限定符表示指代的对象,例如IP地址,子网或 ...