【问题标题】:curve_fit with polynomials of variable length具有可变长度多项式的曲线拟合
【发布时间】:2018-11-16 13:43:15
【问题描述】:

我是 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)

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

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

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

【问题讨论】:

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


【解决方案1】:

您可以像这样定义适合您的数据的函数:

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

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

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()

【讨论】:

  • 谢谢你,这对我帮助很大!
【解决方案2】:

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

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

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

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

例如

t= np.array([3,4,5,3])
y = fit_func(t,5)
503

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

【讨论】:

    猜你喜欢
    • 2018-02-16
    • 2019-04-20
    • 2019-09-05
    • 2020-01-11
    • 1970-01-01
    • 2021-10-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多