Week 5 - Curve fitting
1. curve_fit function returns 2 values - popt and pcov.
popt-Array which contains the best fit parameters for the coefficients, so that the sum of square of residuals for the function will be minimized.
pcov-2D Array which contains the covariances, and indicates the corrlations and uncertainties between the parameters.
2. np.array(temperature) converts the 'temperature' array into a numpy array.
3. Refers to the coefficient values stored in popt.
4.
import math
import numpy as np
import matplotlib.pyplot as plt
from scipy.optimize import curve_fit
#Linear Function Definition
def LinFunc(t,a,b):
return (a*t+b)
#Cubic Function Definition
def CubicFunc(t,a,b,c,d):
return a*pow(t,3)+b*pow(t,2)+c*t+d
#Reading the Data File
def readfile():
temp=[]
cp=[]
for l in open('data','r'):
values=l.split(',')
temp.append(float(values[0]))
cp.append(float(values[1]))
return [temp,cp]
#Solving for Linear
temp,cp=readfile()
popt,pcov=curve_fit(LinFunc,temp,cp)
fitfunc=LinFunc(np.array(temp),*popt)
ssr1=np.sum(pow(np.array(cp)-np.array(fitfunc),2))
print('Sum of Squares of Residuals(Linear Fit):',ssr1)
#Solving for Cubic
temp,cp=readfile()
popt,pcov=curve_fit(CubicFunc,temp,cp)
cubefit=CubicFunc(np.array(temp),*popt)
ssr2=np.sum(pow(np.array(cp)-np.array(cubefit),2))
print('Sum of Squares of Residuals(Cubic Fit):',ssr2)
if(ssr2
As is evident from the plots, the cubic fit is a much better fit as compared to the linear fir. More number of points lie on the regression line. Residuals are less as distance from the point to the line are less. Due to this reason the Sum of Squares of Residuals , as calculated in the code is less.
This code as seen, is used to fit the given functoin of Cp as a function of temperature. We take both linear and cubic relationship, and store these models as separate functions. The given values of Cp and Temperature are read from the data file using the readfile function. These values are then stored in temp and cp arrays respectively.The curve_fit function is used to fit the linear and cubic functions separately. Then the best possible parameter values stored in popt are taken to find the values of Cp. The observed values and predicted values are then plotted on the graph as shown.Sum of Squares of Residuals of the y value,or Cp,is calculated.It is clearly seen that the sum of squares of residuals is much lesser for cubic fit as compared to linear fit, proving that the cubic fit is a better fit for the given data.
5. To improve the fit, or to make the curve fit perfect ,a higher order polynomial can be used. Or the temperature can be divided into 2 ranges.