python 中的经验 cdf 类似于 matlab 的

Empirical cdf in python similiar to matlab's one

我在 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

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

[f,x] = ecdf(X);

得到 x 点的 cdf (f)。 Here 是它的文档。
在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()

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

获得样本后,您可以使用 np.unique* and np.cumsum:

的组合轻松计算 ECDF
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

例如:

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()


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

TypeError: unique() got an unexpected keyword argument 'return_counts'

在这种情况下,解决方法是获取 "inverse" 索引集并使用 np.bincount 计算出现次数:

quantiles, idx = np.unique(sample, return_inverse=True)
counts = np.bincount(idx)