Week 5 - Curve fitting
Curve fitting Using 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 function
def func(t,a,b,c,d):
return a*pow(t,3)+b*t*t+c*t+d
def func1(t,a,b,c,d):
return a*t+b
#Reading Thermodynamic data File
def read_file():
temperature=[]
cp=[]
for line in open('data','r'):
values=line.split(',')
temperature.append(float(values[0]))
cp.append(float(values[1]))
return [temperature, cp]
#Main Program
temperature, cp= read_file()
#For Cubic Equation
popt,pcov=curve_fit(func,temperature,cp)
fit_cp=func(np.array(temperature), *popt)
#For Linear Equation
popt1,pcov1=curve_fit(func1,temperature,cp)
fit_cp1=func1(np.array(temperature), *popt1)
#Cubic Equation
plt.figure(1)
plt.plot(temperature,cp,color="blue",Linewidth=3)
plt.plot(temperature,fit_cp,color="red",Linewidth=3)
plt.xlabel('Temperature[k]')
plt.ylabel('Cp')
#Linear Equation
plt.figure(2)
plt.plot(temperature,cp,color="blue",Linewidth=3)
plt.plot(temperature,fit_cp1,color="red",Linewidth=3)
plt.xlabel('Temperature[k]')
plt.ylabel('Cp')
plt.xlabel('temperature[k]')
plt.ylabel('Cp')
plt.show()
Code Explanation:
Required Libraries including numpy,scipy.optimize and matplotlib.pyplot are imported
Func and func1 are programmed to accept the values of t,a,b,c and d and to return the value after calculating by using them all in cubic and linear equations respectively
The thermodynamic values file is read using read function,its value is seperated using split function and stored in two different matrices called temperature and cp.
popt and pcov values are found out using curve_fit function. Further the calculated values are stored by calling func function for cubic equations and stored in fit_cp.
popt1 and pcov1 values are found out using curve_fit function. Further the calculated values are stored by calling func1 function for Linear equations and stored in fit_cp1.
The plot of fit_cp and actual values are plotted on same graph for cubic polynomial equation.
The plot of fit_cp1 and actual values are plotted on same graph for linear equation.
Results:
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.