np.polynomial.polynomial.polyfit似乎不适合Python中的数据

问题描述 投票:-1回答:1

我试图对373个数据点进行简单的线性拟合,但polyfit似乎失败了,我不知道为什么。

x = np.reshape(air_sst_new[:,90,180],(373))
y = np.reshape(olr_new[:,90,180],(373))

z = np.polynomial.polynomial.polyfit(x,y,1)

plt.figure()
plt.plot(x,y, '.')
xx = np.linspace(np.min(x),np.max(x))
yy = np.polynomial.polynomial.polyval(xx, z)
plt.plot(xx, yy)

Plot showing original data and the fit

上面编写的代码在使用随机生成的点时起作用,令人沮丧。

example_x = np.random.rand(373,180,360)
example_y = np.random.rand(373,180,360)

x = np.reshape(example_x[:,90,180], (373))
y = np.reshape(example_y[:,90,180], (373))

z = np.polynomial.polynomial.polyfit(x,y,1)

plt.figure()
plt.plot(x,y, '.')
xx = np.linspace(np.min(x), np.max(x))
yy = np.polynomial.polynomial.polyval(xx, z)
plt.plot(xx, yy)

Plot showing randomly generated data and correct fit

python numpy matplotlib curve-fitting
1个回答
2
投票

问题在于你的polyval中的参数顺序。 z是你的线性拟合系数数组,xx是用于绘制拟合的精细网格。

你用过:

z = np.polynomial.polynomial.polyfit(x,y,1)
yy = np.polynomial.polynomial.polyval(xx, z)

你应该使用:

z = np.polyfit(x,y,1)
yy = np.polyval(z, xx)

有关更多详细信息,请参阅官方文档here

© www.soinside.com 2019 - 2024. All rights reserved.