Project

Curve Fitting - Python

AIM : To write a code to perform curve fitting

THEORY :

Curve fitting is the process of constructing a curve or mathematical function, that has the best fit to a series of data points, possibly subject to constraints. Curve fitting can involve either interpolation, where an exact fit to the data is required, or smoothing, in which a smooth function is constructed that approximately fits the data. A related topic is regression analysis, which focuses more on questions of statistical interference such as how much uncertainty is present in a curve that is fit to data observed with random errors. Fitted curves can be used as an aid for data visualization, to infer values of a function where no data are available, and to summarize the relationships among two or more variables.

Curve fitting can also be described as 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.

The accuracy of the curve fit can be improved by increasing the degree of the polynomial. So, a 'Best fit' can be obtained by increasing the degree of the polynomial.

PERFECT FIT : The perfect fit is achieved when the geometric distances from the given points to the fitting curve are zero . This means that the curve fits perfectly on the points . To get a perfect fit we can increase to a order of the polynomials , this method increases the accuracy and reduces errors .

BEST FIt :The best fit is achieved when the geometric distances from the given points to the fitting curve are minimized, in the least squares sense. Finding the best fit reduces to the minimization of the objective function where denotes the fitting curve.

Upon finding a curve which satisfies the data points there are 4 quantities which help us measure the goodness of fit criteria or how well the equation is a representing the datapoints.

  • The sum of squares due to error (SSE)
  • R-square
  • Adjusted R-square
  • Root mean squared error (RMSE)

https://projects.skill-lync.com/projects/Curve-Fitting-and-criterion-to-choose-best-fit-41860

link for data : https://drive.google.com/file/d/1vWi9Vj3AdQf0gqUK1u9jwS8zg92BHGR0/view

  • popt : It is the optimal value of the parameters so that the sum of square residuals is minimized.
  • pcov : The pcov variable contains the covariance matric, which includes the uncertainities and correlations between parameters. This is mostly useful when the data has uncertainities.
  • np.array : np.array is used in the following code so that we can put the values of temperature in to an array one by one . ( numpy module )
  • *popt : coefficient of polynomials.

CODE :

1. quadratic fit

import numpy as np
import matplotlib.pyplot as plt
from scipy.optimize import curve_fit




# curve_fit(f,x,y)

file = open('data','r')

def read_file() :

	temperature = []
	cp =[]

	for line in file :	
		values = line.split(',')
		temperature.append(float(values[0]))
		cp.append(float(values[1]))

	return [temperature,cp]              

	
def func(t,a,b,c):

	return a*pow(t,2)+b*t +c


temperature,cp = read_file()
popt, pcov = curve_fit(func,temperature,cp)             #popt i.e optimum parameters are returned which then can be passed to the funvction
fit_cp = func(np.array(temperature),*popt)

plt.plot(temperature,cp,linewidth = 3 , color = 'red')
plt.plot(temperature,fit_cp,linewidth = 3 , color = 'blue')
plt.xlabel('temperature in K')
plt.ylabel('specific heat')
plt.legend(['actual fit','quadratic fit'])
plt.grid()
plt.savefig('quadratic_fit')
plt.show()  

Figure :

2. cubic fit

import numpy as np
import matplotlib.pyplot as plt
from scipy.optimize import curve_fit




# curve_fit(f,x,y)

file = open('data','r')

def read_file() :

	temperature = []
	cp =[]

	for line in file :	
		values = line.split(',')
		temperature.append(float(values[0]))
		cp.append(float(values[1]))

	return [temperature,cp]              

	
def func(t,a,b,c,d):

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


temperature,cp = read_file()
popt, pcov = curve_fit(func,temperature,cp)             #popt i.e optimum parameters are returned which then can be passed to the funvction
fit_cp = func(np.array(temperature),*popt)

plt.plot(temperature,cp,linewidth = 3 , color = 'red')
plt.plot(temperature,fit_cp,linewidth = 3 , color = 'blue')
plt.legend('temperature','cp')
plt.legend(['actual_fit','cubic_fit'])
plt.xlabel('temperature in K')
plt.ylabel('specific heat')
plt.grid()
plt.savefig('cubic_fit')
plt.show()  

3. power 4 fit

import numpy as np
import matplotlib.pyplot as plt
from scipy.optimize import curve_fit




# curve_fit(f,x,y)

file = open('data','r')

def read_file() :

	temperature = []
	cp =[]

	for line in file :	
		values = line.split(',')
		temperature.append(float(values[0]))
		cp.append(float(values[1]))

	return [temperature,cp]              

	
def func(t,a,b,c,d,e):

	return a*pow(t,4)+b*pow(t,3) +c*pow(t,2)+d*t +e


temperature,cp = read_file()
popt, pcov = curve_fit(func,temperature,cp)             #popt i.e optimum parameters are returned which then can be passed to the funvction
fit_cp = func(np.array(temperature),*popt)

plt.plot(temperature,cp,linewidth = 3 , color = 'red')
plt.plot(temperature,fit_cp,linewidth = 3 , color = 'blue')
plt.legend(['actual_fit','poly_fit'])
plt.xlabel('temperature in K')
plt.ylabel('specific heat')
plt.grid()  
plt.savefig('poly_fit')
plt.show()

CONCLUSION :

Inorder to improve the curve fit , the degree of polynomial must be increased .

Higher the degree of polynomial better is the curve fit obtained.

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.