【问题标题】:Fit lognormal function to count data拟合对数正态函数来计算数据
【发布时间】:2020-08-03 11:15:49
【问题描述】:

我有一组粒度数据,这些数据按大小分箱并按分箱宽度标准化。我想为这些数据拟合一个对数正态分布函数,但我遇到了一些问题。大多数软件(例如scipy.stats.lognormal.fit)都需要原始数据,似乎没有办法对已经分箱的数据进行同样的拟合。

将这些数据拟合到对数正态分布的最佳方法是什么?我制作了一个包含可用数据的 csv 文件:https://drive.google.com/file/d/1wxsJuyu7rv0VQBHAYyreZmQqKiIZ7dz5/view?usp=sharing

【问题讨论】:

    标签: python numpy scipy statistics data-science


    【解决方案1】:

    我发现最好的方法是使用scipy.optimize.curve_fit。下面是一些示例代码,使用上面的示例数据:

    import matplotlib.pyplot as plt
    import pandas as pd
    import numpy as np
    from scipy.optimize import curve_fit
    
    # Define lognormal PDF as function of x, mu, and sigma
    def lognorm_fit(x, mu, sigma):
        y = (1/(sigma*x*np.sqrt(2*np.pi))) * np.exp(-1* ((np.log(x) - mu)**2/(2*sigma**2)))
        return y
    
    # Open data
    df = pd.read_csv('./data.csv')
    
    # Read data, using the lower bin limit as x
    count = df['count']
    x = df['lower_bin_limit']
    width = df['upper_bin_limit'] - df['lower_bin_limit']
    
    # Divide by bin width and normalize by total count
    y = count/width/(count.sum())
    plt.plot(x,y)
    
    # Use curve_fit to find the two parameters in lognom_fit function
    # Curve fit returns a tuple of (mu, sigma) and the covariance,
    # Which isn't needed.
    (mu,sigma), _ = curve_fit(lognorm_fit, xdata=x, ydata=y)
    print(mu, sigma)
    
    # Generate lognorm PDF using values of mu, sigma
    yy = lognorm_fit(x, mu, sigma)
    
    # Plot Results
    plt.plot(x,y)
    plt.plot(x, yy)
    plt.xscale('log')
    plt.show()
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-10-23
      • 1970-01-01
      • 2012-12-12
      • 2019-07-27
      • 2019-07-10
      • 1970-01-01
      相关资源
      最近更新 更多