【问题标题】:fit numpy polynomials to noisy data将 numpy 多项式拟合到噪声数据
【发布时间】:2018-08-18 11:35:34
【问题描述】:

我想用一个numpy.polynomial 多项式准确地表示我的嘈杂数据。我怎样才能做到这一点?。

在这个例子中,我选择了 Legendre 多项式。当我使用多项式legfit 函数时,它返回的系数要么非常大,要么非常小。所以,我认为我需要某种正则化。

当我增加多项式的次数时,为什么我的拟合没有变得更准确? (可以看出,20、200 和 300 度多项式本质上是相同的。)多项式包中是否有任何正则化选项?

我尝试实现自己的回归函数,但感觉就像我在重新发明轮子。让我自己的拟合功能是前进的最佳途径吗?

from scipy.optimize import least_squares as mini
import matplotlib.pyplot as plt
import numpy as np

x = np.linspace(0, 5, 1000)
tofit = np.sin(3 * x) + .6 * np.sin(7*x) - .5 * np.cos(3 * np.cos(10 * x))

# This is here to illustrate what I expected the legfit function to do
# I expected it to do least squares regression with some sort of regularization.
def myfitfun(x, y, deg):
    def fitness(a):
       return ((np.polynomial.legendre.legval(x, a) - y)**2).sum() + np.sum(a ** 2)
    return mini(fitness, np.zeros(deg)).x

degrees = [2, 4, 8, 16, 40, 200]
plt.plot(x, tofit, c='k', lw=4, label='Data')
for deg in degrees:
    #coeffs = myfitfun(x, tofit, deg)
    coeffs = np.polynomial.legendre.legfit(x, tofit, deg)
    plt.plot(x, np.polynomial.legendre.legval(x, coeffs), label="Degree=%i"%deg)
plt.legend()

【问题讨论】:

  • 它并没有变得更准确,因为您可能需要非常非常小的系数来获得那么高的度数。但它们不能小于 1e-15 左右...en.wikipedia.org/wiki/…
  • @Joe polyfit 是否适用于 Legendre 多项式?如果不是,它不适合我的问题。我编辑了我的问题以删除“任何多项式都可以”。至于机器精度的问题,我认为您没有正确诊断问题。
  • polyfit 只是 legfit 但对于正则多项式。我想过这个问题。我认为这需要超过 2 秒的谷歌搜索才能回答。
  • 您是否尝试过polyfit 是否比legfit 工作得更好?你必须使用勒让德多项式吗?还是仅仅拟合数据?

标签: python numpy curve-fitting


【解决方案1】:

在拟合中使用适当区间的简单方法是使用 Legendre 类

from numpy.polynomial import Legendre as L
p = L.fit(x, y, order)

这将缩放数据并将其移动到区间 [-1, 1] 并跟踪缩放因子。

【讨论】:

    【解决方案2】:

    Legendre 多项式适用于区间 [-1,1]。尝试将x 替换为适合您的2*x/x[-1] - 1,您会发现一切都很好:

    nx = 2*x/x[-1] - 1
    for deg in degrees:
        #coeffs = myfitfun(x, tofit, deg)
        coeffs = np.polynomial.legendre.legfit(nx, tofit, deg)
        plt.plot(x, np.polynomial.legendre.legval(nx, coeffs), label="Degree=%i"%deg)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2010-09-27
      • 2020-01-24
      • 1970-01-01
      • 1970-01-01
      • 2018-03-16
      • 1970-01-01
      • 2019-04-17
      相关资源
      最近更新 更多