Week 5 - Curve fitting
CURVE FITTING
Objectives
To write a code using a linear and a cubic polynomial equation that fits the data given.
Problem Statement
Curve fitting is a process of constructing a curve or a mathematical function, that has the best fit to a series of data points, possibly subject to constraints. It can either involve interpolation, where an exact fit to the data is required or smoothing, in which a smooth function is constructed that approximately fits the data. It can also be visualized as examining the relationship between one or more independent variables and a dependent variable, to define the best fit model of a relationship.
For example, a first-degree polynomial equation can be of the form,`y=ax+b`. This is an exact fit through any two points with distinct x-coordinates. Similarly, if a second-degree equation is considered, such as `y=ax^2+bx+c` it represents a curve fit through three points. Similarly, a third-degree equation of the form `y=ax^3+bx^2+cx+d` would represent a curve fit through four points.
The different types of curve fitting techniques include Linear, Polynomial, and Multiple Linear Regression fits, Nonlinear curve fitting, Implicit fitting, Surface fitting, etc. The following are some of the quantities that define the goodness of the fit criteria – Sum of Squares due to error method, R-Square method, Adjusted R-Square method, and Root mean square error method. These methods determine whether a fit obtained for a given data set is valid and accurate or if it needs any modifications.
Solution Procedure
Initially, plotting and math modules are imported to plot the required graphs and perform necessary calculations.
In addition to this, the NumPy and SciPy modules are also imported. SciPy is particularly used to gain access to the curve fitting function in python.
After this, a function is defined that contains information regarding the type of equation that would be used, and the input parameters required.
Later, another function is defined that is used in reading and importing data from the given data file.
Two empty arrays are initialized to temperature and cp respectively. The open command is used to refer to the particular data file. The split command is used later to differentiate between the two data values present in the same line.
Now, the values present in the data file are string characters. These are converted to float values and later updated in the respective arrays.
This function returns the temperature and cp values in the form of a single array.
In the next step, the curve fit operation is performed. This requires the values of temperature and cp, along with the function that defines the required equation.
The internal results of this curve fit operation are assigned to two parameters called popt and pcov.
Since this step generates the values of coefficients present in the defined equation, the values of cp are found out in the next step using the whole temperature array and the values of coefficients that are stored in popt.
This step is performed to refine the obtained curve.
Later, curves are plotted between temperature and cp along with temperature and refined cp values.
A comparison is obtained between the two.
The linear equation used in this case is as follows.
`y=a*t+b`
Similarly, the cubic polynomial equation used is as follows.
`y=at^3+bt^2+ct+d`
Here, a, b, c, and d represent the coefficients of these equations. Their values are obtained by using the curve fit solver.
The code for the linear fit function is as follows.
import math
import matplotlib.pyplot as plt
import numpy as np
from scipy.optimize import curve_fit
# Linear curve fit function
def linear_func(t,a,b):
return a*t + b
# Reading the thermodynamic data
def file():
temp = []
cp = []
for line in open('data','r'):
entries = line.split(',')
temp.append(float(entries[0]))
cp.append(float(entries[1]))
return[temp,cp]
# Performing curve fit operation
temp,cp = file()
popt,pcov = curve_fit(linear_func,temp,cp)
fit_cp = linear_func(np.array(temp),*popt)
# Plotting the results
plt.plot(temp,cp, color = 'red', linewidth = 3)
plt.plot(temp,fit_cp, color = 'blue', linewidth = 3)
plt.legend(['Actual Data','Curve Fit'])
plt.xlabel('Temperature[K]')
plt.ylabel('cp')
plt.savefig('Linear Curve fit')
plt.show()
Similarly, the code for the cubic fit function is as follows
import math
import matplotlib.pyplot as plt
import numpy as np
from scipy.optimize import curve_fit
# Cubic curve fit function
def cubic_func(t,a,b,c,d):
return a*pow(t,3) + b*pow(t,2) + c*t + d
# Reading the thermodynamic data
def file():
temp = []
cp = []
for line in open('data','r'):
entries = line.split(',')
temp.append(float(entries[0]))
cp.append(float(entries[1]))
return[temp,cp]
# Performing curve fit operation
temp,cp = file()
popt,pcov = curve_fit(cubic_func,temp,cp)
fit_cp = cubic_func(np.array(temp),*popt)
# Plotting the results
plt.plot(temp,cp, color = 'red', linewidth = 3)
plt.plot(temp,fit_cp, color = 'blue', linewidth = 3)
plt.legend(['Actual Data','Curve Fit'])
plt.xlabel('Temperature[K]')
plt.ylabel('cp')
plt.savefig('Cubic Curve fit')
plt.show()
Results
The following are the plots obtained between temperature and cp values in the case of a linear fit
Similarly, the plots obtained in the case of a cubic function is as follows.
Discussions
From the plots above, the graphs in red are obtained by plotting the values of temperature and cp by using the coefficients obtained by solving the curve fit function. The graphs in blue are obtained by plotting the values of temperature and refined values of cp. From the first graph, it is observed that the plotting of actual data does not produce a straight line as required, but after the refinement of the data, a perfect straight line is obtained. This can also be observed in the second graph as there is a slight variation between the two. This proves that the curve fit process is used in determining the perfect curve or relation between the independent and dependent variables.
Questions
What do popt and pcov mean?
The popt argument defines and stores the best -fit parameter values of the coefficients of the equation defined in the function. In simpler terms, it generates and stores the values of the coefficients. For example, in this case, popt stores the values of a, b, c, and d. Printing the values of popt in both cases generates the following output. The following figures represent the values of the coefficients in the case of linear and cubic equations respectively.
The pcov variable on the other hand contains the covariance matrix, which indicates the uncertainties and correlations between the parameters. It is mostly used when the data set has uncertainties. For example, if each data set point has a known vertical error or a standard deviation, the pcov values are used to correct it as it contains the true variance and covariance values stored in the form of a matrix.
What does np. array(temperature) do?
After performing the curve fit operation, refinement of curve fitting is done by running the defined function (containing the equation). This step includes passing the temperature as an array along with the popt argument that contains the values of coefficients. Temperature values are passed in the form of an array along with popt which is also in an array format. This generates refined cp values.
What does the * in *popt mean?
The * notation in the refining step along with popt is used to expand a list of values in the arguments in the function. This is used when the function has more than one parameter. In simpler terms, it helps in referring to the values stored in the popt array.
What needs to be done to make the curve fit perfect?
By observation, it can be concluded that the difference between the plots of actual data and curve fit in the case of a linear equation is greater than this difference in the case of a cubic equation. This proves that considering a higher-order equation produces accurate results, thus making the curve fit perfect. Another method is to generate the curve by breaking down the input values, i.e., the temperature values into different ranges, rather than considering all of them at the same time.