我正在尝试使用numpy包对一组数据进行多项式拟合。
以下是代码,它可以成功运行。当阶数达到20左右(非常高)时,拟合的线似乎符合数据。然而,在最后,它说"Polyfit可能是糟糕的条件“。
我该如何解决这个问题呢?
def gen_data_9(length=5000):
x = 2.0 * (np.random.rand(length) - 0.5) * np.pi * 2.0
f = lambda x: np.exp(-x**2) * (-x) * 5 + x / 3
y = f(x) + np.random.randn(len(x)) * 0.5
return x, y, f
fig,ax = plt.subplots(3,3,figsize = (16,16))
for n in range(3):
for k in range(3):
order = 20*n+10*k+1
z = np.polyfit(x,y,order)
p = np.poly1d(z)
ax[n,k].scatter(x,y,label = "Real data",s=1)
ax[n,k].scatter(x,p(x),label = "Polynomial with order={}".format(order),
color='C1',s=1)
ax[n,k].legend()
fig.show()发布于 2018-04-18 23:11:30
TL;DR:在这种情况下,警告的意思是:使用较低的顺序!
请注意,当多项式的次数很大或采样点的间隔居中时,拟合多项式系数的条件本身就很差。在这些情况下,应始终检查配合的质量。当多项式拟合不能令人满意时,样条曲线可能是一个很好的选择。
换句话说,警告告诉您要仔细检查结果。如果他们看起来很好,不用担心。但是他们还好吗?要回答这个问题,您不仅应该评估用于拟合的数据点(这些数据点通常匹配得很好,特别是在过度拟合时),还应该评估结果拟合。请考虑以下内容:
xp = np.linspace(-1, 1, 10000) * 2 * np.pi
for n in range(3):
for k in range(3):
order = 20*n+10*k+1
print(order)
z = np.polyfit(x,y,order)
p = np.poly1d(z)
ax[n,k].scatter(x,y,label = "Real data",s=1)
ax[n,k].plot(xp,p(xp),label = "Polynomial with order={}".format(order), color='C1')
ax[n,k].legend()在这里,我们在间隔比样本数据更精细的点上评估多项式。这就是结果:

你可以看到,对于订单40以上的订单来说,结果真的很好。这与我收到的警告不谋而合。
https://stackoverflow.com/questions/49902585
复制相似问题