用积分函数拟合数据 [英] Fitting data with integral function

查看:56
本文介绍了用积分函数拟合数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当使用curve_fit 来自 scipy.optimize在python中拟合一些数据,首先定义拟合函数(例如二阶多项式)如下:

When using curve_fit from scipy.optimize to fit a some data in python, one first defines the fitting function (e.g. a 2nd order polynomial) as follows:

  1. def f(x, a, b):返回 a*x**2+b*x
  2. 然后进行拟合popt, pcov = curve_fit(f,x,y)

但现在的问题是,如何定义第 1 点中的函数.如果函数包含积分(或离散和),例如:

But the question is now, how does one go about defining the function in point 1. if the function contains an integral (or a discrete sum), e.g.:

仍然给出了 x 和 f(x) 的实验数据,所以第 2 点与我想象的类似,一旦我可以在 python 中定义 f(x).顺便说一句,我忘了说,假设 g(t) 在这里具有众所周知的形式,并且包含拟合参数,即多项式示例中给出的 a 和 b 等参数.任何帮助深表感谢.这个问题真的应该是一个通用的问题,帖子中使用的函数只是随机示例.

The experimental data is still given for x and f(x), so point 2. would be similar I imagine once I can define f(x) in python. By the way I forgot to say that it is assumed that g(t) has a well known form here, and contains the fitting parameters, i.e. parameters like a and b given in the polynomial example. Any help is much appreciated. The question is really supposed to be a generic one, and the functions used in the post are just random examples.

推荐答案

这是一个拟合根据积分定义的曲线的示例.曲线是 sin(t*w)/t+pt 从 0 到 Pi 的积分.我们的 x 个数据点对应于 w,我们正在调整 p 参数以使数据适合.

Here's an example of fitting a curve defined in terms of an integral. The curve is the integral of sin(t*w)/t+p over t from 0 to Pi. Our x data points correspond to w, and we're adjusting the p parameter to to get the data to fit.

import math, numpy, scipy.optimize, scipy.integrate

def integrand(t, args):
    w, p = args
    return math.sin(t * w)/t + p

def curve(w, p):
    res = scipy.integrate.quad(integrand, 0.0, math.pi, [w, p])
    return res[0]

vcurve = numpy.vectorize(curve, excluded=set([1]))

truexdata = numpy.asarray([0.0, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0])
trueydata = vcurve(truexdata, 1.0)

xdata = truexdata + 0.1 * numpy.random.randn(8)
ydata = trueydata + 0.1 * numpy.random.randn(8)

popt, pcov = scipy.optimize.curve_fit(vcurve,
                                      xdata, ydata,
                                      p0=[2.0])
print popt

这将打印出相当接近 1.0 的内容,这是我们在创建 trueydata 时用作 p 的内容.

That'll print something out fairly close to 1.0, which is what we used as p when we created the trueydata.

请注意,我们在曲线函数上使用 numpy.vectorize 来生成与 scipy.optimize.curve_fit 兼容的矢量化版本.

Note that we use numpy.vectorize on the curve function to produce a vectorized version compatible with scipy.optimize.curve_fit.

这篇关于用积分函数拟合数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆