如何定义任意函数的chi2值函数?

2024-06-26 07:39:07 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在使用pyminuit Python绑定对minuit最小化代码进行一些数据拟合(http://code.google.com/p/pyminuit/). 最小化器接受一个函数,并使用自省来提取要最小化的参数。一般来说,我希望在给定描述数据集的特定函数的情况下最小化数据集的卡平方值。在

我的问题是:有没有一种方法可以定义一个卡平方函数,在给定一个具有不同数量参数的任意函数的情况下,返回一个函数,该函数给出该函数的卡平方值,只包含函数参数规范中要最小化的参数?在

示例:

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只在函数之外定义。为完整起见,其余的最小化程序如下所示:

^{pr2}$

提前感谢您的帮助!在


Tags: 数据函数a2data参数定义a1情况
1条回答
网友
1楼 · 发布于 2024-06-26 07:39:07

因为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

用法示例:

^{pr2}$

印刷

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

相关问题 更多 >