如何将多项式回归线拟合到数据

How to fit the polynomial regression line to the data

#plotting values 
x_max = np.max(X) + 100
x_min = np.min(X) - 100#calculating line values of x and y
x = np.linspace(x_min, x_max, 1000)
y = b0 + b1 * x #plotting line 
plt.plot(x, y, color='#00ff00', label='Linear Regression')#plot the data point
plt.scatter(X, Y, color='#ff0000', label='Data Point')# x-axis label
plt.xlabel('Time')#y-axis label
plt.ylabel('Signal Strength MHz')
plt.legend()
plt.show()

我无法将多项式回归线拟合到数据。

coefs = np.polyfit(X, Y, 4)
x_new = np.linspace(X[0], X[-1], num=len(X)*10)
ffit = poly.polyval(x_new, coefs)
plt.plot(x_new, ffit, label = 'Polynomial Regression')
plt.scatter(X, Y, color='#ff0000', label='Data Point')# x-axis label
plt.xlabel('Time')#y-axis label
plt.ylabel('Signal Strength MHz')
plt.show()

您调换了多项式系数和 x 值的顺序。根据 docs,第一个参数是多项式系数:

numpy.polyval(p, x)

Parameters:

p : array_like or poly1d object 1D array of polynomial coefficients (including coefficients equal to zero)

x : array_like or poly1d object A number, an array of numbers, or an instance of poly1d, at which to evaluate p.

更改以下行

ffit = poly.polyval(x_new, coefs)

ffit = poly.polyval(coefs, x_new)

编辑:

或者,尝试以下方法

coefs = np.polyfit(X, Y, 4)
x_new = np.linspace(X[0], X[-1], num=len(X)*10)
ffit = np.poly1d(coefs)
plt.plot(x_new, ffit(x_new), label = 'Polynomial Regression')