【问题标题】:Fitting un-normalized gaussian in histogram python在直方图python中拟合未归一化的高斯
【发布时间】:2016-07-26 11:02:09
【问题描述】:

我有一张深色图像(原始格式),并绘制了图像和图像的分布。如您所见,16 点有一个高峰,请忽略它。我想通过这个直方图拟合高斯曲线。我用这种方法来适应: Un-normalized Gaussian curve on histogram。然而;我的高斯拟合永远不会接近它应该是的。将图像转换为正确的绘图格式是我做错了什么,还是有其他问题?

这是我用来生成这些数据的当前代码:

import numpy as np
import matplotlib.pyplot as plt
from scipy.optimize import curve_fit

def fitGaussian(x,a,mean,sigma):
    return (a*np.exp(-((x-mean)**2/(2*sigma))))

fname = 'filepath.raw'
im = np.fromfile(fname,np.int16)
im.resize([3056,4064])

plt.figure()
plt.set_cmap(viridis)
plt.imshow(im, interpolation='none', vmin=16, vmax=np.percentile(im.ravel(),99))
plt.colorbar()
print 'Saving: ' + fname[:-4] + '.pdf'
plt.savefig(fname[:-4]+'.pdf')

plt.figure()
data = plt.hist(im.ravel(), bins=4096, range=(0,4095))

x = [0.5 * (data[1][i] + data[1][i+1]) for i in xrange(len(data[1])-1)]
y = data[0]

popt, pcov = curve_fit(fitGaussian, x, y, [500000,80,10])
x_fit = py.linspace(x[0], x[-1], 1000)
y_fit = fitGaussian(x_fit, *popt)
plt.plot(x_fit, y_fit, lw=4, color="r")        

plt.xlim(0,300)
plt.ylim(0,1e6)
plt.show()   

编辑:(回复 Reblochon Masque)

如果我在 16 点移除垃圾箱,我仍然会得到同样的效果:

【问题讨论】:

  • 我不完全确定我理解你在做什么,但似乎你可能想要消除直方图上 20 左右的尖峰
  • @ReblochonMasque 即使我在 16 处消除了垃圾箱。我得到了类似的结果,它只是向右移动。查看我的编辑。
  • 我猜你得到这条曲线是因为你将 Gaußian 拟合到所有的 bin 中,其中大部分是零。您可以仅将曲线拟合到非零 bin,但这很麻烦。
  • 已经更好了...好建议 kazemakase;检查它的一种简单方法可能是减少垃圾箱的数量,以便所有都有值(尝试使用 5-8 可能吗?)

标签: python matplotlib curve-fitting data-fitting


【解决方案1】:

拟合的高斯显得太低了,因为它适合所有的 bin,其中大部分是零。一种解决方案是仅将高斯拟合到非零 bin。

我使用np.histogram 而不是plt.hist 来获取bin vaules,但这只是个人喜好问题。重要的部分是xhyh的定义

import numpy as np
import matplotlib.pyplot as plt
from scipy.optimize import curve_fit

# Generate example data
x = np.random.randn(100000) * 50 + 75
x = np.round(x / 10) * 10
x = x[x >= 20]

yhist, xhist = np.histogram(x, bins=np.arange(4096))

xh = np.where(yhist > 0)[0]
yh = yhist[xh]

def gaussian(x, a, mean, sigma):
    return a * np.exp(-((x - mean)**2 / (2 * sigma**2)))

popt, pcov = curve_fit(gaussian, xh, yh, [10000, 100, 10])

plt.plot(yhist)
i = np.linspace(0, 300, 301)
plt.plot(i, gaussian(i, *popt))
plt.xlim(0, 300)

附: Sigma 通常表示标准偏差而不是方差。这就是为什么我在 gaussian 函数中对其进行平方。

【讨论】:

    猜你喜欢
    • 2016-07-05
    • 1970-01-01
    • 2014-11-12
    • 2018-09-21
    • 2017-10-10
    • 2018-02-17
    • 2018-08-07
    • 2015-08-11
    • 2022-01-06
    相关资源
    最近更新 更多