Week 5 - Curve fitting
CURVE FITTING
AIM – Write python program to fit curve to given data and answer the given questions.
OBJECTIVES-
- Write a basic script to fit curve to given data.
- Answer the following questions.
- What does popt and pcov mean?
- What does np.array(temperature) do?
- What does the * in *popt mean?
- Write code to fit a linear and cubic polynomial for the Cp data. Explain if your results are good or bad.
- What needs to be done in order to make the curve fit perfect?
INTRODUCTION-
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 statistical inference 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. Extrapolation refers to the use of a fitted curve beyond the range of the observed data, and is subject to a degree of uncertainty since it may reflect the method used to construct the curve as much as it reflects the observed data.
SOLUTION-
What does popt and pcov mean?
The curve_fit function returns two items, which we call popt and pcov. The popt argument are the best-fit parameters for coefficients of our polynomial function we are trying to fit curve i.e. a, b and c in our case.
The pcov variable contains the covariance matrix, which indicates the uncertainties and correlations between these parameters. It is mostly useful when the data has uncertainties and there are large numbers of data points.
What does np.array(temperature) do?
It passes values of temperature from data as one dimensional array allowing us to plot actual data.
What does the * in *popt mean?
The * notation will expand a list of values into the arguments of the function. This is useful if your function has more than one or two parameters.
Write code to fit a linear and cubic polynomial for the Cp data. Explain if your results are good or bad.
For linear polynomial = `= at+b`
"""
Program to curve fit linear polynomial to given data.
By Sushant Kumar Mishra
"""
import numpy as np
import matplotlib.pyplot as plt
from scipy.optimize import curve_fit
#defining linear polynomial
def func (t,a,b):
return a*t+b
#definig function to read our data file
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)
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')
plt.ylabel('cp')
plt.show()
Plot:
For Cubic polynomial = `at^3+bt^2+ct+d`
"""
Program to curve fit linear polynomial to given data.
By Sushant Kumar Mishra
"""
import numpy as np
import matplotlib.pyplot as plt
from scipy.optimize import curve_fit
#defining cubic polynomial
def func (t,a,b,c,d):
return a*pow(t,3)+b*pow(t,2)+c*t+d
#definig function to read our data file
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)
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')
plt.ylabel('cp')
plt.show()
Plot:
Cleary, from above plots we can see that cubic polynomial curve fit is good while linear polynomial curve fit is bad. Moreover this can be verified analytically by comparing values of SSE in both cases.
What needs to be done in order to make the curve fit perfect?
It can be done using a higher order polynomial like `at^4+bt^3+ct^2+dt+e`
Following plot shows comparison between curve fit function and actual data. It can easily be observed that both are almost same.
Plot:
Moreover, we can break temperature range in two or more parts to use different functions for each part and hence, obtain best fit.