Week 5 - Curve fitting
Aim: To perform curve fit using python.
Objective: Answer the following questions and perform code in Python based on curve fitting.
Figure: Flow of the project
Questions to Answer
- What does popt and pcov mean?
Ans- popt- An array of optimal values for the parameters which minimize the sum of squares of residuals.
Ans- pcov-2d array which contains the estimated covariance of popt. The diagonals provide the variance of the parameter estimate.
- What does np.array(temperature) do?
Ans- np.array- converts the python list of temperature to a numpy array since operations like pow are allowed on numpy arrays and not python lists.
- What does the * in *popt mean?
*-reference to popt / the values stored in the array popt.
- Write code to fit a linear and cubic polynomial for the Cp data. Explain if your results are good or bad.
Code:
import numpy as np import matplotlib.pyplot as plt from scipy.optimize import curve_fit
#curve fit functiondef func(t,a,b,c,d,e): return a*t+b
#reading thermodynamic data filedef 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 programtemperature, cp=read_file()popt,pcov=curve_fit(func,temperature,cp)fit_cp=func(np.array(temperature),*popt)
plt.plot(temperature,cp,color="blue",linewidth=3)plt.plot(temperature,fit_cp,color="red",linewidth=3)plt.legend(['actual data','curve fit'])plt.xlabel('Temperature[K]')plt.ylabel('Cp')
plt.show()
Code for Cubic fit
import numpy as np import matplotlib.pyplot as plt from scipy.optimize import curve_fit #curve fit functiondef func(t,a,b,c,d): return a*pow(t,3)+b*pow(t,2)+c*t+d #reading thermodynamic data filedef 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 programtemperature, cp=read_file()popt,pcov=curve_fit(func,temperature,cp)fit_cp=func(np.array(temperature), *popt)
plt.plot(temperature,cp,color="blue",linewidth=3) plt.plot(temperature,fit_cp,color="red",linewidth=3) plt.legend(['actual data','curve fit']) plt.xlabel('Temperature[K]') plt.ylabel('Cp') plt.show()
Output
Linear
Cubic
Conclusions
The results are good for cubic fit because it is better than the linear as we can see it from the output plots.
- What needs to be done in order to make the curve fit perfectly?
- By increasing the order of equation used for curve fit.
- By minimizing the error in any regression method.