[Python] Curve fitting with polynomial

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. download.png

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 download.png

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

[Python] Curve fitting with polynomial
Implemented in Python PRML Chapter 1 Polynomial Curve Fitting
Draw Koch curve with Python Turtle
PRML diagram drawing Figure 1.4 Polynomial curve fitting
FizzBuzz with Python3
Scraping with Python
Statistics with python
Scraping with Python
Python with Go
PRML Chapter 1 Bayesian Curve Fitting Python Implementation
Twilio with Python
Integrate with Python
Play with 2016-Python
AES256 with python
Image processing with Python & OpenCV [Tone Curve]
Tested with Python
python starts with ()
with syntax (Python)
Bingo with python
Zundokokiyoshi with python
Excel with Python
Microcomputer with Python
Cast with python
Try to draw a life curve with python
Serial communication with Python
Zip, unzip with python
Django 1.11 started with Python3.6
Primality test with Python
Socket communication with Python
Data analysis with python 2
Try scraping with Python.
Learning Python with ChemTHEATER 03
Sequential search with Python
"Object-oriented" learning with python
Run Python with VBA
Handling yaml with python
Solve AtCoder 167 with python
Serial communication with python
[Python] Use JSON with Python
Learning Python with ChemTHEATER 05-1
Run prepDE.py with python3
1.1 Getting Started with Python
Collecting tweets with Python
Binarization with OpenCV / Python
Kernel Method with Python
Non-blocking with Python + uWSGI
Posting tweets with python
Drive WebDriver with python
Use mecab with Python3
[Python] Redirect with CGIHTTPServer
Voice analysis with python
Think yaml with python
Operate Kinesis with Python
Getting Started with Python
Use DynamoDB with Python
Zundko getter with python
Model fitting with lmfit
Primality test with python
Run Blender with python
Solve Sudoku with Python
Python starting with Windows 7