skewness 是衡量数据集对称性的参数,kurtosis 是衡量其尾部与正态分布相比的重度,例如 here .
scipy.stats
提供了一种计算这两个数量的简单方法,请参见 scipy.stats.kurtosis
和 scipy.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()
关于python - 如何正确使用 scipy 的 skew 和 kurtosis 函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45483890/