我希望用
在这个例子中,我选择了勒让德多项式。当我使用多项式函数
为什么随着多项式次数的增加,我的拟合结果并没有更加准确?(可以看到20、200和300次多项式基本相同。)多项式包中是否有任何规则化选项?
我尝试实现自己的回归函数,但感觉像是在重复造轮子。制作自己的拟合函数是否是最好的前进道路?
numpy.polynomial
多项式精确表示我的嘈杂数据。如何做到这一点?在这个例子中,我选择了勒让德多项式。当我使用多项式函数
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()
polyfit
就是为普通多项式而设计的legfit
。我已经思考过这个问题。我认为这需要超过 2 秒钟的谷歌搜索才能回答。 - kilojoulespolyfit
来进行拟合吗?它是否比legfit
更好用呢?您必须使用Legendre多项式吗?还是只需拟合数据即可? - Joepolyfit
会更好呢? - kilojoules