python中的经验cdf类似于matlab的一个

Pho*_*ght 2 python statistics matlab numpy matplotlib

我在matlab中有一些代码,我想重写成python.它是一个简单的程序,它计算一些分布并以双对数刻度绘制它.

我遇到的问题是计算cdf.这是matlab代码:

for D = 1:10
    delta = D / 10;
    for k = 1:n
        N_delta = poissrnd(delta^-alpha,1);
        Y_k_delta = ( (1 - randn(N_delta)) / (delta.^alpha) ).^(-1/alpha);
        Y_k_delta = Y_k_delta(Y_k_delta > delta);
        X(k) = sum(Y_k_delta);
        %disp(X(k))

    end
    [f,x] = ecdf(X);

    plot(log(x), log(1-f))
    hold on
end
Run Code Online (Sandbox Code Playgroud)

在matlab中,我可以简单地使用:

[f,x] = ecdf(X);
Run Code Online (Sandbox Code Playgroud)

在点x获得cdf(f).是它的文档.
在python中它更复杂:

import numpy as np
from scipy.stats import norm
import matplotlib.pyplot as plt
from statsmodels.distributions.empirical_distribution import ECDF

alpha = 1.5
n = 1000
X = []
for delta in range(1,5):
    delta = delta/10.0
    for k in range(1,n + 1):
        N_delta = np.random.poisson(delta**(-alpha), 1)
        Y_k_delta = ( (1 - np.random.random(N_delta)) / (delta**alpha) )**(-1/alpha)
        Y_k_delta = [i for i in Y_k_delta if i > delta]
        X.append(np.sum(Y_k_delta))

    ecdf = ECDF(X)

    x = np.linspace(min(X), max(X))
    f = ecdf(x)
    plt.plot(np.log(f), np.log(1-f))

plt.show()
Run Code Online (Sandbox Code Playgroud)

它使我的情节看起来很奇怪,绝对不像matlab那样平滑.
我认为问题是我不理解ECDF函数或它的工作方式与matlab不同.
我为我的python代码实现了这个解决方案(最重要的一点),但看起来它无法正常工作.

ali*_*i_m 5

获得样本后,您可以使用np.unique*和组合轻松计算ECDF np.cumsum:

import numpy as np

def ecdf(sample):

    # convert sample to a numpy array, if it isn't already
    sample = np.atleast_1d(sample)

    # find the unique values and their corresponding counts
    quantiles, counts = np.unique(sample, return_counts=True)

    # take the cumulative sum of the counts and divide by the sample size to
    # get the cumulative probabilities between 0 and 1
    cumprob = np.cumsum(counts).astype(np.double) / sample.size

    return quantiles, cumprob
Run Code Online (Sandbox Code Playgroud)

例如:

from scipy import stats
from matplotlib import pyplot as plt

# a normal distribution with a mean of 0 and standard deviation of 1
n = stats.norm(loc=0, scale=1)

# draw some random samples from it
sample = n.rvs(100)

# compute the ECDF of the samples
qe, pe = ecdf(sample)

# evaluate the theoretical CDF over the same range
q = np.linspace(qe[0], qe[-1], 1000)
p = n.cdf(q)

# plot
fig, ax = plt.subplots(1, 1)
ax.hold(True)
ax.plot(q, p, '-k', lw=2, label='Theoretical CDF')
ax.plot(qe, pe, '-r', lw=2, label='Empirical CDF')
ax.set_xlabel('Quantile')
ax.set_ylabel('Cumulative probability')
ax.legend(fancybox=True, loc='right')

plt.show()
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述


*如果您使用的是早于1.9.0的numpy版本,np.unique则不接受return_counts关键字参数,您将获得TypeError:

TypeError: unique() got an unexpected keyword argument 'return_counts'
Run Code Online (Sandbox Code Playgroud)

在这种情况下,解决方法是获取一组"反向"索引并用于np.bincount计算出现次数:

quantiles, idx = np.unique(sample, return_inverse=True)
counts = np.bincount(idx)
Run Code Online (Sandbox Code Playgroud)