首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >如何为任意函数定义chi2值函数?

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

Stack Overflow用户
提问于 2011-10-28 09:50:22
回答 1查看 617关注 0票数 2

我正在做一些数据拟合,使用(http://code.google.com/p/pyminuit/)。minimiser接受一个函数并使用内省来提取要最小化的参数。通常,我希望最小化给定描述数据集的特定函数的数据集的齐平方值。

我的问题是:是否有一种方法来定义一个具有不同参数的任意函数,它返回一个函数,该函数给出了该函数的齐平方值,并且只包含函数参数规范中要最小化的参数?

示例:

代码语言:javascript
运行
复制
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只是在函数之外定义的。为了完整起见,最小化例程的其余部分看起来如下:

代码语言:javascript
运行
复制
# 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}

谢谢你提前帮忙!

EN

Stack Overflow用户

回答已采纳

发布于 2011-10-28 11:20:12

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

代码语言:javascript
运行
复制
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

示例用法:

代码语言:javascript
运行
复制
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

打印

代码语言:javascript
运行
复制
['a1', 'a2', 'a3', 'a4']
票数 1
EN
查看全部 1 条回答
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/7927670

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档