python - 如何正确使用 scipy 的 skew 和 kurtosis 函数?

标签 python numpy scipy statistics

skewness 是衡量数据集对称性的参数,kurtosis 是衡量其尾部与正态分布相比的重度,例如 here .

scipy.stats 提供了一种计算这两个数量的简单方法,请参见 scipy.stats.kurtosisscipy.stats.skew

根据我的理解,使用刚才提到的函数,normal distribution 的偏度和峰度都应该为 0。但是,我的代码并非如此:

import numpy as np
from scipy.stats import kurtosis
from scipy.stats import skew

x = np.linspace( -5, 5, 1000 )
y = 1./(np.sqrt(2.*np.pi)) * np.exp( -.5*(x)**2  )  # normal distribution

print( 'excess kurtosis of normal distribution (should be 0): {}'.format( kurtosis(y) ))
print( 'skewness of normal distribution (should be 0): {}'.format( skew(y) ))

输出是:

excess kurtosis of normal distribution (should be 0): -0.307393087742

skewness of normal distribution (should be 0): 1.11082371392

我做错了什么?

我使用的版本是

python: 2.7.6
scipy : 0.17.1
numpy : 1.12.1

最佳答案

这些函数计算 probability density distribution 的矩(这就是为什么它只需要一个参数)并且不关心值的“函数形式”。

这些适用于“随机数据集”(将它们视为平均值、标准差、方差等度量):

import numpy as np
from scipy.stats import kurtosis, skew

x = np.random.normal(0, 2, 10000)   # create random values based on a normal distribution

print( 'excess kurtosis of normal distribution (should be 0): {}'.format( kurtosis(x) ))
print( 'skewness of normal distribution (should be 0): {}'.format( skew(x) ))

给出:

excess kurtosis of normal distribution (should be 0): -0.024291887786943356
skewness of normal distribution (should be 0): 0.009666157036010928

改变随机值的数量可以提高准确度:

x = np.random.normal(0, 2, 10000000)

导致:

excess kurtosis of normal distribution (should be 0): -0.00010309478605163847
skewness of normal distribution (should be 0): -0.0006751744848755031

在您的情况下,函数“假定”每个值具有相同的“概率”(因为这些值是均匀分布的,并且每个值只出现一次)所以从 skew 的角度来看,并且kurtosis 它处理的是非高斯概率密度(不确定这到底是什么),这解释了为什么结果值甚至不接近 0:

import numpy as np
from scipy.stats import kurtosis, skew

x_random = np.random.normal(0, 2, 10000)

x = np.linspace( -5, 5, 10000 )
y = 1./(np.sqrt(2.*np.pi)) * np.exp( -.5*(x)**2  )  # normal distribution

import matplotlib.pyplot as plt

f, (ax1, ax2) = plt.subplots(1, 2)
ax1.hist(x_random, bins='auto')
ax1.set_title('probability density (random)')
ax2.hist(y, bins='auto')
ax2.set_title('(your dataset)')
plt.tight_layout()

enter image description here

关于python - 如何正确使用 scipy 的 skew 和 kurtosis 函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45483890/

相关文章:

numpy - numpy安装错误。 (Mingw32CCompiler实例没有属性 'compile_options')

python - 为什么 .ix 包含在索引范围的末尾?

python - 微分方程的解在 boost::odeint 和 scipy.integrate 中完全不同

python - 稀疏矩阵上的降维 (TSNE/PCA)

python - 将 ASCII 字符转换为十六进制转义字符串

Python django 管理 : How can I show only items belonging to specific model in an admin page?

python - Django 是否附带用于 django.contrib.auth 模块的身份验证模板?

python - 比较 N 个文件的第一列,如果找到匹配则打印第一个文件和剩余文件的第二列

Python初始化随机值的多维numpy数组

python - 如何在Python上增量创建稀疏矩阵?