Issue
I am trying to use the polyfit function for curve fitting. The noisy data is generated using 3rd order polynomial and am using the 3rd degree when calling polyfit function. But the resulting plot doesn't have any element of curve in it:
import matplotlib.pyplot as plt
import numpy as np
noise_scale = 100
number_of_samples = 100
x = 25*(np.random.rand(number_of_samples,1)-0.8)
y = 5*x+20*x**2+1*x**3 + noise_scale*np.random.randn(number_of_samples,1)
xs = x.flatten()
ys = y.flatten()
p3 = np.poly1d(np.polyfit(xs, ys, 3))
plt.plot(xs,ys,'b.',xs, p3(xs),'r--')
I would like to know what am doing wrong here.
thanks
Solution
plt.plot()
plots points in the order their coordinates appear in the xs
and ys
arrays and connects successive points by straight line segments. Since numbers in the xs
array are in a random order, these straight line segments zigzag back and forth as the values of xs
increase and decrease. In order to get a plot of a polynomial function, the array xs
needs to be sorted from the smallest value to the largest. The array ys
needs to be sorted accordingly so that the y-coordinates of points still correspond to their associated x-coordinates. This can be done as follows:
import matplotlib.pyplot as plt
import numpy as np
noise_scale = 100
number_of_samples = 100
x = 25*(np.random.rand(number_of_samples,1)-0.8)
y = 5*x+20*x**2+1*x**3 + noise_scale*np.random.randn(number_of_samples,1)
xs = x.flatten()
ys = y.flatten()
# sort coordinates
s = np.argsort(xs)
xs = xs[s]
ys = ys[s]
p3 = np.poly1d(np.polyfit(xs, ys, 3))
plt.plot(xs,ys,'b.',xs, p3(xs),'r--')
This gives:
Answered By - bb1
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.