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

时间:2015-10-26 12:27:55

标签: python matlab numpy matplotlib statistics

我在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中,我可以简单地使用:

[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解决方案(最多一点),但看起来它无法正常工作。

1 个答案:

答案 0 :(得分:5)

获得样本后,您可以使用np.unique *和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()

enter image description here

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

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

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

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