Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/321.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何为任意函数定义chi2值函数?_Python_Scipy - Fatal编程技术网

Python 如何为任意函数定义chi2值函数?

Python 如何为任意函数定义chi2值函数?,python,scipy,Python,Scipy,我正在使用pyminuit Python绑定对minuit最小化代码进行数据拟合(http://code.google.com/p/pyminuit/). 最小化器接受一个函数并使用内省来提取要最小化的参数。一般来说,我希望在给定描述数据集的特定函数的情况下,最小化数据集的卡方值 我的问题是:有没有一种方法可以定义一个卡方函数,给定一个具有不同参数数的任意函数,该函数返回一个函数,该函数给出该函数的卡方值,并且只包含函数参数规范中要最小化的参数 例如: from scipy import * i

我正在使用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\u func=make\u chi2(fit\u func)
。我不知道该怎么办,因为
data\u x
data\u 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}

提前谢谢你的帮助

既然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']

我认为pyminuit仅通过内省提取参数,并且不允许显式命名这些参数,至少在pyminuit方面是一个有问题的设计。如果他们允许显式地给出参数,那么你的问题解决起来就很简单了。我写过类似这样的东西,但这要简洁得多。谢谢