Python np.lognormal 为 big average 和 St Dev 提供无限结果

Fab*_*tti 3 python statistics numpy mean standard-deviation

我正在尝试为我的数据绘制对数正态分布。使用以下代码:

mu, sigma = 136519., 50405. # mean and standard deviation
hs = np.random.lognormal(mu, sigma, 1000) #mean, s dev , Size
count, bins, ignored = plt.hist(hs, 100, normed=True)     
x = np.linspace(min(bins), max(bins), 10000)
pdf = (math.exp(-(np.log(x) - mu)**2 / (2 * sigma**2)))
#plt.axis('tight')
plt.plot(x, pdf, linewidth=2, color='r')
Run Code Online (Sandbox Code Playgroud)

正如你所看到的,我的均值和西格玛是很大的值,它会产生一个问题,即 hs 趋于无穷大,从而产生错误。如果我输入 mu =3 和 sigma =1 之类的东西,它会起作用,对大数字有什么建议吗?

更新 1:

我用第一个答案更正了我的代码,但现在我只能得到一条直线:

 mu, sigma = 136519 , 50405 # mean and standard deviation

    normal_std = np.sqrt(np.log(1 + (sigma/mu)**2))
    normal_mean = np.log(mu) - normal_std**2 / 2
    hs = np.random.lognormal(normal_mean, normal_std, 1000)
    print(hs.max())    # some finite number
    print(hs.mean())   # about 136519
    print(hs.std())    # about 50405

#    hs = np.random.lognormal(mu, sigma, 1000) #mean, s dev , Size
#    
    count, bins, ignored = plt.hist(hs, 100, normed=True) 

    x = np.linspace(min(bins), max(bins), 10000)
    pdfT = [];
    for el in range (len(x)):
        pdfTmp = (math.exp(-(np.log(x[el]) - mu)**2 / (2 * sigma**2)))
        pdfT += [pdfTmp]


    #plt.axis('tight')
    pdf = np.asarray(pdfT)
    plt.plot(x, pdf, linewidth=2, color='r')
Run Code Online (Sandbox Code Playgroud)

图片pdf

小智 7

np.random.lognormal中的参数 mu 和 sigma不是对数正态分布的均值和 STD。它们是基础正态分布的均值和 STD ,即log(X)。这意味着通过传递 136519平均值,您要求 NumPy 生成大小exp(136519)约为 的数字10**60000,远远超出双精度限制。

通过一些代数,您可以np.random.lognormal从您拥有的参数中获得正确的参数。

mu, sigma = 136519., 50405.
normal_std = np.sqrt(np.log(1 + (sigma/mu)**2))
normal_mean = np.log(mu) - normal_std**2 / 2
hs = np.random.lognormal(normal_mean, normal_std, 1000)
print(hs.max())    # some finite number
print(hs.mean())   # about 136519
print(hs.std())    # about 50405
Run Code Online (Sandbox Code Playgroud)