我在下图中给出了输入数据的直方图(黑色):
我试图拟合Gamma distribution
但不是整个数据,而只是拟合直方图的第一条曲线(第一种模式)。上图中的绿色图对应于我Gamma distribution
使用以下python
代码在所有样本上拟合时使用的代码scipy.stats.gamma
:
img = IO.read(input_file)
data = img.flatten() + abs(np.min(img)) + 1
# calculate dB positive image
img_db = 10 * np.log10(img)
img_db_pos = img_db + abs(np.min(img_db))
data = img_db_pos.flatten() + 1
# data histogram
n, bins, patches = plt.hist(data, 1000, normed=True)
# slice histogram here
# estimation of the parameters of the gamma distribution
fit_alpha, fit_loc, fit_beta = gamma.fit(data, floc=0)
x = np.linspace(0, 100)
y = gamma.pdf(x, fit_alpha, fit_loc, fit_beta)
print '(alpha, beta): (%f, %f)' % (fit_alpha, fit_beta)
# plot estimated model
plt.plot(x, y, linewidth=2, color='g')
plt.show()
我怎样才能将拟合限制在这个数据的有趣子集中?
更新1(切片):
我通过只保留低于前一个直方图最大值的值来分割输入数据,但结果并不令人信服:
这是通过# slice histogram here
在前面代码中的注释下方插入以下代码来实现的:
max_data = bins[np.argmax(n)]
data = data[data < max_data]
更新2(scipy.optimize.minimize):
下面的代码显示了如何scipy.optimize.minimize()
使用最小化能量函数来找到(alpha, beta)
:
import matplotlib.pyplot as plt
import numpy as np
from geotiff.io import IO
from scipy.stats import gamma
from scipy.optimize import minimize
def truncated_gamma(x, max_data, alpha, beta):
gammapdf = gamma.pdf(x, alpha, loc=0, scale=beta)
norm = gamma.cdf(max_data, alpha, loc=0, scale=beta)
return np.where(x < max_data, gammapdf / norm, 0)
# read image
img = IO.read(input_file)
# calculate dB positive image
img_db = 10 * np.log10(img)
img_db_pos = img_db + abs(np.min(img_db))
data = img_db_pos.flatten() + 1
# data histogram
n, bins = np.histogram(data, 100, normed=True)
# using minimize on a slice data below max of histogram
max_data = bins[np.argmax(n)]
data = data[data < max_data]
data = np.random.choice(data, 1000)
energy = lambda p: -np.sum(np.log(truncated_gamma(data, max_data, *p)))
initial_guess = [np.mean(data), 2.]
o = minimize(energy, initial_guess, method='SLSQP')
fit_alpha, fit_beta = o.x
# plot data histogram and model
x = np.linspace(0, 100)
y = gamma.pdf(x, fit_alpha, 0, fit_beta)
plt.hist(data, 30, normed=True)
plt.plot(x, y, linewidth=2, color='g')
plt.show()
上述算法收敛于 的子集data
,输出o
为:
x: array([ 16.66912781, 6.88105559])
但从下面的屏幕截图中可以看出,伽马图不适合直方图: