Curve Fitting using Python
AIM: Write a python code to fit a linear and cubic polynomial for the given Cp data.
SOLUTION:
Coding:
"""
Linear and Cubic Polynomial curve fit for the cp data
"""
import numpy as np
import matplotlib.pyplot as plt
from scipy.optimize import curve_fit
# Linear polynomial curve fit
def fun1(t1, a1, b1):
return a1*t1 + b1
# Cubic polynomial curve fit
def fun2(t2, a2, b2, c2, d2):
return a2*pow(t2,3) + b2*pow(t2,2) + c2*t2 + d2
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]
temperature, cp=read_file()
popt, pcov=curve_fit(fun1,temperature,cp)
fit_cp1=fun1(np.array(temperature), *popt)
popt, pcov=curve_fit(fun2,temperature,cp)
fit_cp2=fun2(np.array(temperature), *popt)
plt.figure(1)
plt.plot(temperature,cp,color="blue",linewidth=3)
plt.plot(temperature,fit_cp1,color="red",linewidth=3)
plt.legend(['Actual data','curve fit'])
plt.xlabel('Temperature')
plt.ylabel('Cp')
plt.figure(2)
plt.plot(temperature,cp,color="blue",linewidth=3)
plt.plot(temperature,fit_cp2,color="red",linewidth=3)
plt.legend(['Actual data','curve fit'])
plt.xlabel('Temperature')
plt.ylabel('Cp')
plt.show()
Output:
- Linear curve fit
- Cubic polynomial curve fit
Explanation:
- Curve fitting is 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. It is highly effective in the mathematical modeling of some natural processes.
- In this program we first import the nump, matplotlib and scipy module.
- Then we define two function, one for linear polynomial and another for cubic polynomial as shown in the coding.
- Then we get the value of cp with respect to temperature. By using line.split(',') command we split the temperture and cp value fo oxygen and append to temperature and cp array as shown in coding.
- Then we calculate fit curve by using the below command,
popt, pcov=curve_fit(fun1,temperature,cp)
fit_cp1=fun1(np.array(temperature), *popt)
- Finally plot the original curve and calculated curve fit of cp data with respect to temperature.
- From this analysis, increasing the order of polynomials gives better curve fit. So if we use fourth order polynomial we get a better curve fit.
Question1: What does popt and pcov mean?
Answer: popy means Optimal values for the parameters or optimum values of the coefficients of the cubic equation; pcov means the estimated covariance of popt.
Question2: What does np.array(temperature) do?
Answer: Numpy array is a central data structure of the numpy library, which is a numerical library of Python. 'np.array()' is used to create a numpy array and the temperature is passed as the data of the array.
Question3: What does the * in *popt mean?
Answer: *popt unpacks the popt array, so the two optimized parameter values become the second and third arguments to the function.
Question4: What needs to be done in order to make the curve fit perfect?
Answer: Using a polynomial with degree two you can fit the curve to your point. Generally it is not a proper way. It may cause over-fitting. It means that the generalization is not considered here. In other words the error of the chosen model will be high when the model is applied for a new data. Therefore, validation techniques such as cross validation are used to solve this problem. In cross validation, the data is split into k folds (e.g. 10 folds). Then, the first fold is used to validate the model. After that, the next fold is used for validation and so on(i.e divide the data points in subregions and fit curve for each region seperately).