If you want to curve fit the sample data with polynomial, you can easily do it by using numpy's polyfit. The curve is represented by the following polynomial. polyfit will calculate $ a_n $ in the formula below.
y = \sum^{N}_{n=0} a_n x^n
The values returned by polyfit are listed in descending order. The formula is as follows.
y = \sum^N_{n=0} a_n x^{N-n}
If you want to draw a curve graph using the coefficients obtained by polyfit, prepare the value of x in numpy.linspace etc. and pass the coefficient and x to numpy.polyval to calculate y.
The figure below shows the result of curve fitting with sample data and linear equation. You can get the coefficient just by setting numpy.polyfit (x, y, 1). x and y are data and 1 is the order.
w = np.polyfit(x,y,1)
xs = np.linspace(np.min(x),np.max(x),100)
ys = np.polyval(w,xs)
fig = plt.figure()
ax = fig.add_subplot(111)
ax.scatter(x, y,label='input')
ax.plot(xs, ys, 'r-', lw=2, label='polyfit')
ax.set_title('polyfit w = [%.2f, %.2f]' % (w[0],w[1]))
ax.set_xlabel('x')
ax.set_ylabel('y')
ax.legend(loc='best',frameon=False)
ax.grid(True)
The sample data was created as follows.
def getData1(numPoints, w,b, nstdev, xmin=0.0, xmax=1.0 ):
x = scipy.stats.uniform.rvs(loc=xmin, scale=xmax-xmin,size=numPoints)
n = scipy.stats.norm.rvs(size=numPoints, scale=nstdev)
y = w * x + b + n
return x, y
x, y = getData1(100, 1.5, 10, 10, xmin=0, xmax=100)
The result of curve fitting with a cubic polynomial
w = np.polyfit(x,y,3)
xs = np.linspace(np.min(x),np.max(x),100)
ys = np.polyval(w,xs)
fig = plt.figure()
ax = fig.add_subplot(111)
ax.scatter(x, y,label='input')
ax.plot(xs, ys, 'r-', lw=2, label='polyfit')
ax.set_title('polyfit w = [%.2f, %.2f, %.2f, %.2f]' % (w[0],w[1],w[2],w[3]))
ax.set_xlabel('x')
ax.set_ylabel('y')
ax.legend(loc='best',frameon=False)
ax.grid(True)
The sample data was created as follows.
def getData2(numPoints, Amp, freq, phase, nstdev, xmin=0.0, xmax=np.pi*2.0 ):
x = scipy.stats.uniform.rvs(loc=xmin, scale=xmax-xmin,size=numPoints)
n = scipy.stats.norm.rvs(size=numPoints, scale=nstdev)
y = Amp*np.sin(freq * x + phase) + n
return x, y
x, y = getData2(100, 10, 1.0, 0.0, 5, xmin=0, xmax=np.pi*2.0)
Reference URL https://docs.scipy.org/doc/numpy/reference/generated/numpy.polyfit.html https://docs.scipy.org/doc/numpy/reference/generated/numpy.polyval.html#numpy.polyval
Recommended Posts