首页 文章

将numpy多项式拟合到噪声数据

提问于
浏览
3

我想用 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()

enter image description here

2 回答

  • 2

    在拟合中使用适当间隔的简单方法是使用勒让德类

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

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

  • 0

    勒让德多项式意味着在区间[-1,1]上使用 . 尝试用适合的 2*x/x[-1] - 1 替换 x ,你会发现一切都很好:

    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)
    

    enter image description here

相关问题