Challenge

Curve fitting using Python

AIM: Write code to fit a linear and cubic polynomial curve using python

Objective:

  1. Write code to fit a linear and cubic polynomial curve using python.
  2. Find parameter used to measure the fitness characteristics of curve

Theoretical background:

Curve fitting is the process of constructing a curve, or mathematical functions, which possess the closest proximity to the real series of data. By curve fitting, we can mathematically construct the functional relationship between the observed dataset and parameter values, etc. It is highly effective in the mathematical modeling of some natural processes.

Least Squares Method is the most commonly used technique as long as the fitting function is a polynomial

Parameter to measure fitness characteristics of curve

  1. The sum of squares due to error (SSE)
  2. R-square
  3. Adjusted R-square
  4. Root mean squared error (RMSE)
  1. SUM OF SQUARES DUE TO ERROR (SSE)

`SSE=∑_(i=1)^n(Y(i)-f(x(i)))^2`

  1. SUM OF SQUARES OF REGRESSION (SSR)

`SSR=∑_(i=1)^n(f(x(i))-Mean)^2`SSR=∑i=1n▒(f(x(i))-Mean)2">

  1. R-square

This quantity that measures how successful the fit is in explaining the variation of the data. Put another way, R-square is the square of the correlation between the response values and the predicted response values. It is also called the square of the multiple correlation coefficient and the coefficient of multiple determination.

0 for the worst possible fit for the data set

1 for the best possible fit for the data set

`R^2=(SSR)/(SST)`

Where

`SST=SSR+SSE`

  1. Adjusted R-square:

Adjusted R-square is a normalizing variation of R-square which neglects the variation of R-square due to insignificant independent variables.

`R_adjusted^2=1-[((1-R^2)(n-1))/(n-k-1)]`

where,

n - the number of datapoints

k - the number of independent variables

  1. Root mean squared error (RMSE):

This statistic is also known as the fit standard error and the standard error of the regression. It is an estimate of the standard deviation of the random component in the data, and is defined as,

`RMSE=√(SSE)/n)`

where,

n is the total number of datapoints available.

Main program:

  • Linear curve fitting
import numpy as np 
import matplotlib.pyplot as plt 
from scipy .optimize import curve_fit 

def func (t,a,b):
	return a*t +b 


def read_file():
	temp=[]
	cp = []
	for line in open ('data','r'):
		values = line.split(',')
		temp.append (float (values[0]))
		cp.append(float(values[1]))

	return [temp,cp]

temp,cp = read_file ()
popt,pcov= curve_fit(func,temp,cp)
fit_cp = func(np.array(temp),*popt)

plt.plot(temp,cp,color="red",linewidth=3)
plt.plot (temp,fit_cp,color="blue",linewidth=3 )
plt.legend (['actual data','curve fit data'])
plt.xlabel('temprature[K]')
plt.ylabel('cp')
plt.show()
  • Polynomial curve fitting
import numpy as np 
import matplotlib.pyplot as plt 
from scipy .optimize import curve_fit 

def func (t,a,b,c,d):
	return a*pow(t,3) + b*pow(t,2) + c*t +d


def read_file():
	temp=[]
	cp = []
	for line in open ('data','r'):
		values = line.split(',')
		temp.append (float (values[0]))
		cp.append(float(values[1]))

	return [temp,cp]

temp,cp = read_file ()
popt,pcov= curve_fit(func,temp,cp)
fit_cp = func(np.array(temp),*popt)

plt.plot(temp,cp,color="red",linewidth=3)
plt.plot (temp,fit_cp,color="blue",linewidth=3 )
plt.legend (['actual data','curve fit data'])
plt.xlabel('temprature[K]')
plt.ylabel('cp')
plt.show()

Procedure:

  • import math,matplotlib,numpy and scipy module
  • scipy module is required to do curve fitting
  • define function which we want to be curve fit
  • define the function to read the file and spliting the data and append to empty temprature and cp array
  • curve fit is done which returns two array "popt" and "pcov" and popt is optimal value for parameters so that squared residuals is minimized
  • "pcov" means estimated co-variance of popt.The diagonal provide variance of parameter estimate
  • In passing command popt in curve fit we have used it is *popt that is because * is pointer operator and it points out all element in array
  • predicted cp calculated as fit_cp for linear and cubic function
  • graph is plotted with predicted cp data and compared with original data set

Plot:

Conclusion:

  • from above graph we can see cubic fit best fitted the curve rather than linear fit so by using higher order polynomial we can get best fit.
  • we can also use splitting data method to get best fit.

Result:

  • program to fit the curve for linear and cubic polynomial has been successfully done.
Your portfolio, next

Ship work like this
in your own course.

Talk to a career counsellor

Free 20-minute call. We'll map the right course to where you want to work.

By submitting you agree to our Terms and Privacy Policy.

Talk to a career counsellor

Free 20-minute call. We'll map the right course to where you want to work.

By submitting you agree to our Terms and Privacy Policy.