具有可变长度

时间:2018-06-06 18:59:44

标签: python-3.x scipy curve-fitting

我是python(以及一般编程)的新手,并希望使用curve_fit进行多项式拟合,其中多项式的阶数(或拟合参数的数量)是可变的。

我制作了这个代码,该代码适用于固定数量的3个参数a,b,c

# fit function
def fit_func(x, a,b,c):
    p = np.polyval([a,b,c], x)
    return p

# do the fitting
popt, pcov = curve_fit(fit_func, x_data, y_data)

但是现在我想让我的拟合函数仅依赖于N个参数而不是a,b,c,...

我猜这不是一件很难的事情,但由于我的知识有限,我无法让它发挥作用。

我已经查看了this question,但我无法将其应用于我的问题。

2 个答案:

答案 0 :(得分:3)

您可以定义适合您的数据的功能,如下所示:

def fit_func(x, *coeffs):
    y = np.polyval(coeffs, x)
    return y

然后,当您调用curve_fit时,将参数p0设置为多项式系数的初始猜测。例如,此图由后面的脚本生成。

plot

import numpy as np
from scipy.optimize import curve_fit
import matplotlib.pyplot as plt


# Generate a sample input dataset for the demonstration.
x = np.arange(12)
y = np.cos(0.4*x)


def fit_func(x, *coeffs):
    y = np.polyval(coeffs, x)
    return y


fit_results = []
for n in range(2, 6):
    # The initial guess of the parameters to be found by curve_fit.
    # Warning: in general, an array of ones might not be a good enough
    # guess for `curve_fit`, but in this example, it works.
    p0 = np.ones(n)

    popt, pcov = curve_fit(fit_func, x, y, p0=p0)
    # XXX Should check pcov here, but in this example, curve_fit converges.

    fit_results.append(popt)


plt.plot(x, y, 'k.', label='data')

xx = np.linspace(x.min(), x.max(), 100)
for p in fit_results:
    yy = fit_func(xx, *p)
    plt.plot(xx, yy, alpha=0.6, label='n = %d' % len(p))

plt.legend(framealpha=1, shadow=True)
plt.grid(True)
plt.xlabel('x')
plt.show()

答案 1 :(得分:0)

polyval的参数指定p是从最高到最低的系数数组。 x是一个数字或数组,用于计算多项式。它说,以下。

  

如果p的长度为N,则此函数返回值:

     

p [0] * x **(N-1)+ p [1] * x **(N-2)+ ... + p [N-2] * x + p [N-1]

document

e.g。

def fit_func(p,x):
    z = np.polyval(p,x)
    return z

如果你在这里做数学是正确的。