gpt4 book ai didi

python - NumPy 百分位函数不同于 MATLAB 的百分位函数

转载 作者:太空狗 更新时间:2023-10-29 20:10:56 25 4
gpt4 key购买 nike

当我尝试在 MATLAB 中计算第 75 个百分位数时,得到的值与在 NumPy 中得到的值不同。

MATLAB:

>> x = [ 11.308 ;   7.2896;   7.548 ;  11.325 ;   5.7822;   9.6343;
7.7117; 7.3341; 10.398 ; 6.9675; 10.607 ; 13.125 ;
7.819 ; 8.649 ; 8.3106; 12.129 ; 12.406 ; 10.935 ;
12.544 ; 8.177 ]

>> prctile(x, 75)

ans =

11.3165

Python + NumPy:

>>> import numpy as np

>>> x = np.array([ 11.308 , 7.2896, 7.548 , 11.325 , 5.7822, 9.6343,
7.7117, 7.3341, 10.398 , 6.9675, 10.607 , 13.125 ,
7.819 , 8.649 , 8.3106, 12.129 , 12.406 , 10.935 ,
12.544 , 8.177 ])

>>> np.percentile(x, 75)
11.312249999999999

我也用 R 检查了答案,我得到了 NumPy 的答案。

回复:

> x <- c(11.308 ,   7.2896,   7.548 ,  11.325 ,   5.7822,   9.6343,
+ 7.7117, 7.3341, 10.398 , 6.9675, 10.607 , 13.125 ,
+ 7.819 , 8.649 , 8.3106, 12.129 , 12.406 , 10.935 ,
+ 12.544 , 8.177)
> quantile(x, 0.75)
75%
11.31225

这是怎么回事?有没有办法让 Python 和 R 的行为反射(reflect) MATLAB 的行为?

最佳答案

MATLAB 显然默认使用中点插值。NumPy 和 R 默认使用线性插值:

In [182]: np.percentile(x, 75, interpolation='linear')
Out[182]: 11.312249999999999

In [183]: np.percentile(x, 75, interpolation='midpoint')
Out[183]: 11.3165

了解linearmidpoint 之间的区别,考虑这个简单的例子:

In [187]: np.percentile([0, 100], 75, interpolation='linear')
Out[187]: 75.0

In [188]: np.percentile([0, 100], 75, interpolation='midpoint')
Out[188]: 50.0

要编译最新版本的 NumPy(使用 Ubuntu):

mkdir $HOME/src
git clone https://github.com/numpy/numpy.git
git remote add upstream https://github.com/numpy/numpy.git
# Read ~/src/numpy/INSTALL.txt
sudo apt-get install libatlas-base-dev libatlas3gf-base
python setup.py build --fcompiler=gnu95
python setup.py install

使用 git 而不是 pip 的优点是升级(或降级)到其他版本的 NumPy 非常容易(而且您也可以获得源代码):

git fetch upstream
git checkout master # or checkout any other version of NumPy
cd ~/src/numpy
/bin/rm -rf build
cdsitepackages # assuming you are using virtualenv; otherwise cd to your local python sitepackages directory
/bin/rm -rf numpy numpy-*-py2.7.egg-info
cd ~/src/numpy
python setup.py build --fcompiler=gnu95
python setup.py install

关于python - NumPy 百分位函数不同于 MATLAB 的百分位函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24764966/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com