Skip to main content
 首页 » 编程设计

python之如何修复 numpy 中的 "polyfit maybe poorly conditioned"

2025年05月04日15linjiqin

我正在尝试使用 numpy 包对一组数据进行 polyfit。

下面是代码,可以运行成功。当阶数达到 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() 

请您参考如下方法:

TL;DR:在这种情况下,警告意味着:使用较低的顺序!

引用documentation :

Note that fitting polynomial coefficients is inherently badly conditioned when the degree of the polynomial is large or the interval of sample points is badly centered. The quality of the fit should always be checked in these cases. When polynomial fits are not satisfactory, splines may be a good alternative.

换句话说,警告告诉您仔细检查结果。如果他们看起来很好,请不要担心。但他们还好吗?要回答这个问题,您不仅应该评估用于拟合的数据点的结果拟合(这些数据点通常匹配得很好,尤其是在过度拟合时)。考虑一下:

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

在这里,我们在比样本数据间隔更细的点上评估 polyfit。这是结果:

您可以看到,对于 40 笔及以上的订单,结果真的很不错。这与我收到的警告一致。