SciPy Curve Fitting
OBJECTIVE: To curve fit given data using linear and cubic polynomial.
- For curve fitting, we imported curve_fit from scipy library.
- Defined two function, func and func1 which are used for fitting curve.
- Defined another function read_file to read temperature and cp values.
- Values were split using (,) and values were append in array temperature and cp.
- Under curve_fit, three parameters was passed,x valuesof graph, yvalues of graph and polynomial function to be used for curve fitting.
- fit_cp conatins the y(x)()cp values which will be used for curve fit. X values are temperature values.
- popt is the coefficient of polynomial funvtion used for curve fitting.
- we are passing temperature as numpy array and also coefficient of function which are obtained by *popt in main polynomial function.
- After executing, we can see curve fit for two polynomial.
curve fit using linear polynomial
curve fit using cubic polynomial
Finally to know whether curve fit is good or not, errors were calculated:
Using these errors SSR,SSE,SST, R^2 and RMSE, we can easily deduce the fit is good or not.
If `R^2`is greater than 0.95, the fit is assumed to be good.
From output and also from graph we can see cubic ploynomial is better than linear polynomial.
#curve fitting
#Luv Kumar
import numpy as np
import matplotlib.pyplot as plt
from scipy.optimize import curve_fit
#curvefit function linear
def func(t,a,b):
return a*t + b
def func1(t,a,b,c,d):
return a*t**3+b*t**2+c*t+ d
#read the thermodynamic datafile
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()
popt,pcov = curve_fit(func,temperature,cp)
popt1,pcov1 = curve_fit (func1,temperature,cp)
fit_cp = func(np.array(temperature), *popt)
fitcp1= func1(np.array(temperature), *popt1)
plt.plot(temperature,cp,color=\"blue\",linewidth=3)
plt.plot(temperature,fit_cp,color=\"red\",linewidth=3)
plt.legend([\'actual data\',\'curve fit\'])
plt.figure()
plt.plot(temperature,cp,color=\"blue\",linewidth=3)
plt.plot(temperature,fitcp1,color=\"orange\",linewidth=3)
plt.legend([\'actual data\',\'curve fit\'])
plt.xlabel(\'temperature[K]\')
plt.ylabel(\'cp\')
plt.show()
SSE = []
for i in range(0,len(cp)):
SSE.append(pow((cp[i]-fit_cp[i]),2))
SSESUM = sum(SSE)
#print(SSESUM)
mean1 =(np.mean(cp))
#print(mean1)
SSR=[]
for i in range(0,len(cp)):
SSR.append(pow((fit_cp[i]-mean1),2))
SSRSUM = sum(SSR)
#print(SSRSUM)
SST = SSRSUM + SSESUM
#print(SST)
#print(SSE[-1])
RSQUARE=SSRSUM/SST
print(\"linear fit\",RSQUARE)
sse1 = []
for i in range(0,len(cp)):
sse1.append(pow((cp[i]-fitcp1[i]),2))
ssesum1= sum(sse1)
mean2 = (np.mean(cp))
#print(mean2)
ssr2 = []
for i in range(0,len(cp)):
ssr2.append(pow((fitcp1[i]-mean1),2))
ssr2sum= sum(ssr2)
sst=ssesum1+ssr2sum
#print(sst)
rsquare = ssr2sum/sst
print(\'cubic fit\',rsquare)