Week 5 - Curve fitting
AIM: Write a program to perform curve fitting and determine the fitness of the curve.
OBJECTIVES:
- Write codes to fit a linear and cubic polynomial for the cp data.
- Plot the linear and cubic fit curves along with raw data points.
- Measure the fitness characteristics for both the curves.
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 stastical analysis 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.
Linear curve fit is linear approach to modelling the relationship between a scalar response and one or more explanatory variables.
Nonlinear regression is an analysis in which observational data arer modelled by a function which is nonlinear combination of model parameters.
Goodness of fit of stastical model describes how well it fits the set of observations. Measure of goodness of fit typically summarize the discrepancy between observed values and the values expected under model in question.
To choose the best fit following parameters are considered-
1. Sum of square of errors(SSE).
2. R-square
3. Adjusted R-square
4. Root mean square(RSME)
GOVERNING EQUATIONS:



We will use all the above equations for calculating the fitness of the curve for both the linear and cubic polynomial.
STEPS:
In starting we will first import the basic libraries which will be usefull in programming this challenge which are "math", "matplotlib","numpy",and the most important "curve_fit" from the "scipy".
After that we will define the functions for linear and cubic curve fit.
Later we read the input file and will extract temperature and the specific heat data from it by using the split command. While extracting we will first define the temperature and cp blank arrays and then will append the values from it into them.
Now we come to our main program where we perform the curve fits by using its command which takes input variables temperature and the cp.
"popt" and "pcov" are used as outputs for storing parameters obtained by curve_fit. Another vaiable named "fit_cp" is used for storing new values of cp calculated by using temperature values and cp values. Plots of both polynomials are made with raw data sets so that we can see the fitness of the curve.
To measure the fitness characteristics various parameters such as (SSE),(SSR),(SST),(R-square) and lastly the "RSME" are calculated .
The plot having highest R-square valueor closest to 1 is considered to be good fit.
CODE:
import math
import matplotlib.pyplot as plt
import numpy as np
from scipy.optimize import curve_fit
# Linear Curve fit function
def func_lcf(t,a,b):
return a*t+b
# Cubic Curve fit function
def func_ccf(t,a,b,c,d):
return a*pow(t,3)+b*pow(t,2)+c*t+d
# Reading the thermodynamic file
def read_file():
temp=[]
cp=[]
for line in open('data (1)','r'):
values= line.split(',')
temp.append(float(values[0]))
cp.append(float(values[1]))
return [temp,cp]
#Main program
# For linear fit
temp,cp=read_file()
popt,pcov=curve_fit(func_lcf,temp,cp)
fit_cp_l=func_lcf(np.array(temp),*popt)
plt.figure(1)
plt.plot(temp,cp,'b--')
plt.plot(temp,fit_cp_l,color='red')
plt.legend(['Actual Data','Curve fit'])
plt.xlabel('Temperature(k)')
plt.ylabel('Specific Heat')
plt.title('Linear Curve Fit')
plt.show()
#For Cubic fit
popt,pcov=curve_fit(func_ccf,temp,cp)
fit_cp_c=func_ccf(np.array(temp),*popt)
plt.figure(2)
plt.plot(temp,cp,'b--')
plt.plot(temp,fit_cp_c,color='red')
plt.legend(['Actual Data','Curve Fit'])
plt.xlabel('Temperature(k)')
plt.ylabel('Specific Heat')
plt.title('Cubic Curve Fit')
plt.show()
# Measuring the Fitness Characteristics Of curves
s=np.sum(cp)
l=np.size(cp)
m=s/l
print('Mean of all cp is:',m)
print(' ')
#For linear curve fit
linear_sse=0
linear_ssr=0
for i in range(1):
linear_error=abs((np.sum((cp[i]-fit_cp_l[i]))))
linear_sse= linear_sse+pow(linear_error,2)
linear_ssr=linear_ssr+np.sum(pow((fit_cp_l[i]-m),2))
print('For Linear curve Fit')
linear_sst=linear_sse+linear_ssr
print('linear_sst:',linear_sst)
linear_R2=linear_ssr/linear_sst
print('linear_R2:',linear_R2)
linear_rsme=pow((linear_sse/1),0.5)
print('linear_rsme:',linear_rsme)
print(' ')
# For Cubic Curve fit
cubic_sse=0
cubic_ssr=0
for j in range(1):
cubic_error=abs(np.sum((cp[j]-fit_cp_c[j])))
cubic_sse=cubic_sse+(pow(cubic_error,2))
cubic_ssr=cubic_ssr+np.sum(pow((fit_cp_c[j]-m),2))
print('For cubic curve fit')
cubic_sst=cubic_sse+cubic_ssr
print('cubic_sst:',cubic_sst)
cubic_R2=cubic_ssr/cubic_sst
print('cubic_R2:',cubic_R2)
cubic_rsme=pow((cubic_sse/1),0.5)
print('cubic_rsme:',cubic_rsme)
RESULTS:


Goodness of fit for linear and cubic curves are-

From the above results we can observe that the value for R-square for cubic curve is more closer to 1 i.e 0.99 so we can say that the cubic curve has a good fit rather then the linewr one.
QUESTION- ANSWERS:
QUES1: What does popt and pcov means?
ANS: "popt" is an array that stores the values of the coefficients that are being pasQYsed in a given function.
"pcov" is a two dimensional array that stores the values of the estimated covariance of popt i.e the coefficients.
QUES2: What does np.array(temperature) do?
ANS: This command convert each value of temperature in data file into array using the numpy module.
QUES3: What does the *in*popt mean?
ANS: It indicates and returns each coefficient stored in popt array.
QUES4: What needs to be done in order to make the curve fit perfect?
ANS: In order to make the curve fit perfect we can increase the order of polynomial or break the data set into different groups of certain range or both.