python中的优化块(scipy) - 带直方图的直方图

时间:2013-09-10 08:29:01

标签: python scipy approximation

我需要通过模拟的直方图来拟合实验直方图(以确定最适合的模拟的几个参数)。我已经尝试过scipy.optimize中的curve_fit,但在这种情况下它不起作用:返回错误“...不是python函数”。是否可以在scipy或其他python模块中自动执行此操作?如果没有,请你给我一些可能算法的链接来自己调整它们吗?

1 个答案:

答案 0 :(得分:0)

从你所说的我认为以下内容应该有所帮助,看来你试图以错误的方式使用curve_fit:

您需要定义您想要适合的分布。例如,如果我有一些看起来normally distributed的数据,并且我想知道它们是否合适,以及哪些参数最适合,我会做以下事情:

import numpy as np
import pylab as plt
from scipy.optimize import curve_fit

# Create fake data and run it though `histogram` to get the experimental distribution
experimental = np.random.normal(10.0, 0.4, size=10000)
n, bins = plt.histogram(experimental, bins=100, normed=True)

# This just gives the mid points of the bins, many different (and better) ways exist to
# do this I'm sure
bins_mid_points = (0.5*(bins + np.roll(bins, 1)))[1:]

# Define the normal distribution as a function
def normal(x, sigma, mu):
    return np.exp(-(x - mu)**2 / (2 * sigma**2)) / (sigma * np.sqrt(2*np.pi))

# Fit the experimental data, 
popt, pcov = curve_fit(normal, xdata=bins_mid_points, ydata=n)

# Plot both 
plt.bar(bins[:-1], n, width=np.diff(bins))
plt.plot(bins_mid_points, normal(bins_mid_points, *popt), color="r", lw=3)

红线显示我们的模拟拟合,如果需要,您也可以将其绘制为直方图。 popt的输出提供了最适合数据的[sigma, mu]数组,而pcov可用于确定拟合的好坏程度。

请注意,我对histogram中的数据进行了规范化,这是因为我定义的函数是正常分布。

您需要仔细考虑您期望的分布以及您希望获得的统计数据。