2011-10-28 19 views
2

我正在做一些数据拟合使用pyminuit Python绑定的minuit最小化代码(http://code.google.com/p/pyminuit/)。最小化器接受一个函数并使用内省来提取要最小化的参数。一般来说,我想将给定特定函数的数据集的卡方值最小化以描述数据集。如何为任意函数定义chi2值函数?

我的问题:有没有一种方法来定义一个卡方函数,给出的参数不同数量的任意函数,返回一个函数,它给出了卡方值,该功能只包含的参数是在函数参数说明中最小化?

例子:

from scipy import * 
import minuit 
# Generate some data to fit 
data_x = arange(50) 
noise = 0.3 
data_y = data_x**3 + normal(0.0, noise) 
# Fit function, e.g. a cubic 
fit_func = lambda x, a1, a2, a3, a4: a1 + a2*x + a3*x**2 + a4*x**3 

# Minimisation function e.g. chi squared 
# Note this has only the parameters to be minimised in the definition (eg not data_x) 
min_func = lambda a1, a2, a3, a4: sum((fit_func(data_x, a1, a2, a3, a4) - data_y)**2/noise**2) 

这是我想写点东西像min_func = make_chi2(fit_func)。我不知道该怎么办,因为data_xdata_y只在函数的外部定义。为了完整性,其余的最小化程序看起来像:

# Initialise minimiser object with initial values 
m = minuit.Minuit(min_func, {'a1': 1.0, 'a2': 1.0, 'a3': 1.0, 'a4': 1.0}) 
# Run minimiser 
m.migrad() 
# Print minimised values - example output 
print m.values 
>>> {'a1': 0.000, 'a2': 0.000, 'a3': 0.000, 'a4': 1.000} 

感谢您的帮助提前!

+0

我会打电话的事实,pyminuit只能通过内省提取参数和不允许明确地命名它们是pyminuit方面至少有问题的设计。他们是否允许明确给出这些参数,你的问题将是微不足道的解决。 –

回答

1

由于PyMinuit使用自省,所以也必须使用自省。 make_chi_squared()可以实现这样的:

import inspect 

chi_squared_template = """ 
def chi_squared(%(params)s): 
    return (((f(data_x, %(params)s) - data_y)/errors) ** 2).sum() 
""" 

def make_chi_squared(f, data_x, data_y, errors): 
    params = ", ".join(inspect.getargspec(f).args[1:]) 
    exec chi_squared_template % {"params": params} 
    return chi_squared 

用法示例:

import numpy 

def f(x, a1, a2, a3, a4): 
    return a1 + a2*x + a3*x**2 + a4*x**3 

data_x = numpy.arange(50) 
errors = numpy.random.randn(50) * 0.3 
data_y = data_x**3 + errors 

chi_squared = make_chi_squared(f, data_x, data_y, errors) 
print inspect.getargspec(chi_squared).args 

印刷

['a1', 'a2', 'a3', 'a4'] 
+0

我写过这样的东西,但是这更简洁明了。谢谢! – almailer