【问题标题】:Python: two normal distributionPython:两个正态分布
【发布时间】:2017-01-05 13:25:56
【问题描述】:

我有两个数据集,其中测量了两个值。我对差异的值和标准偏差之间的差异感兴趣。我制作了一个直方图,我想拟合两个正态分布。计算最大值之间的差异。我还想评估在数据集中我对一个值的数据要少得多的影响。我已经看过这个链接,但这并不是我真正需要的: Python: finding the intersection point of two gaussian curves

for ii in range(2,8):
   # Kanal = ii - 1
    file = filepath + '\Mappe1.txt'
    data = np.loadtxt(file, delimiter='\t', skiprows=1)
    data = data[:,ii]
    plt.hist(data,bins=100)
    plt.xlabel("bins")
    plt.ylabel("Counts")
    plt.tight_layout()
    plt.grid()
    plt.figure()

plt.show()

【问题讨论】:

  • 什么是plt?此类信息显然与您的问题相关,但在您的问题中缺失。
  • 来自matplotlib
  • 如果您想使用高斯混合模型,这可能会变得很棘手。阅读这些内容。
  • 这两个样本在统计上是独立的吗?

标签: python histogram normal-distribution


【解决方案1】:

使用 scipy 可以轻松实现快速而肮脏的装配:

from scipy.optimize import curve_fit #non linear curve fitting tool
from matplotlib import pyplot as plt

def func2fit(x1,x2,m_1,m_2,std_1,std_2,height1, height2): #define a simple gauss curve
    return height1*exp(-(x1-m_1)**2/2/std_1**2)+height2*exp(-(x2-m_2)**2/2/std_2**2)

init_guess=(-.3,.3,.5,.5,3000,3000) 
#contains the initial guesses for the parameters (m_1, m_2, std_1, std_2, height1, height2) using your first figure

#do the fitting
fit_pars, pcov =curve_fit(func2fit,xdata,ydata,init_guess) 
#fit_pars contains the mean, the heights and the SD values, pcov contains the estimated covariance of these parameters 

plt.plot(xdata,func2fit(xdata,*fit_pars),label='fit') #plot the fit

如需进一步参考,请参阅 scipy 手册页: curve_fit

【讨论】:

    【解决方案2】:

    假设两个样本是独立的,则无需使用曲线拟合来处理此问题。是基本统计。下面是一些执行所需计算的代码,并在注释中注明了来源。

    ## adapted from http://onlinestatbook.com/2/estimation/difference_means.html
    
    from random import gauss
    from numpy import sqrt
    
    sample_1 = [ gauss(0,1) for _ in range(10) ]
    sample_2 = [ gauss(1,.5) for _ in range(20) ]
    
    n_1 = len(sample_1)
    n_2 = len(sample_2)
    
    mean_1 = sum(sample_1)/n_1
    mean_2 = sum(sample_2)/n_2
    
    SSE = sum([(_-mean_1)**2 for _ in sample_1]) + sum([(_-mean_2)**2 for _ in sample_2])
    df = (n_1-1) + (n_2-1)
    MSE = SSE/df
    
    n_h = 2 / ( 1/n_1 + 1/n_2 )
    s_mean_diff = sqrt( 2* MSE / n_h )
    
    print ( 'difference between means', abs(n_1-n_2))
    print ( 'std dev of this difference', s_mean_diff )
    

    【讨论】:

    • 看起来很棒。它可以处理我的大部分数据。但除了在你的例子中,两个峰来自一个数据文件。所以我没有sample_1和sample_2。在好的情况下,峰之间的距离足够远,因此我可以轻松地拆分数据并使用您的方法。但是在我发布的情节中,山峰彼此如此接近的情况下可以做什么?
    • 这是估计单变量高斯混合模型的业务,我不像专家。除此之外,SO 是关于编程的。我建议初步访问stats.stackexchange.com 以获取最新建议,甚至可能就您可以使用哪些软件提供建议。祝你好运!
    猜你喜欢
    • 1970-01-01
    • 2013-04-10
    • 2016-06-11
    • 2018-09-04
    • 1970-01-01
    • 2012-11-10
    • 1970-01-01
    • 2021-06-06
    • 2015-12-09
    相关资源
    最近更新 更多