Stupid_Intern
Stupid_Intern

Reputation: 3460

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

I am not able to fit the polynomial regression line to the data.

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

Linear Regression

Polynomial Regression

Upvotes: 3

Views: 493

Answers (1)

Sheldore
Sheldore

Reputation: 39072

You have switched the order of polynomial coefficients and the x-values. As per docs, the first argument is the polynomial coefficients:

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.

Change the following line

ffit = poly.polyval(x_new, coefs)

to

ffit = poly.polyval(coefs, x_new)

EDIT:

Alternatively, try the following

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

Upvotes: 3

Related Questions