gpt4 book ai didi

python - python 中的经验 cdf 类似于 matlab 的

转载 作者:行者123 更新时间:2023-11-28 21:49:33 25 4
gpt4 key购买 nike

我在 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 中不同。
我实现了 this我的 python 代码的解决方案(最重要的一个),但它看起来无法正常工作。

最佳答案

获得样本后,您可以使用 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

例如:

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


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

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

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

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

关于python - python 中的经验 cdf 类似于 matlab 的,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33345780/

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