Week 5 - Curve fitting
Aim: To perform Curve Fitting.
Theory:
Curve Fitting: Curve fitting is one of the most powerful and most widely used analysis tools in Origin. Curve fitting examines the relationship between one or more predictors (independent variables) and a response variable (dependent variable), with the goal of defining a "best fit" model of the relationship.
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.
Linear curve fitting, or linear regression, is when the data is fit to a straight line. Although there might be some curve to your data, a straight line provides a reasonable enough fit to make predictions.
Since the equation of a generic straight line is always given by f(x)= a x + b, the question becomes: what a and b will give us the best fit line for our data?
Considering the vertical distance from each point to a prospective line as an error, and summing them up over our range, gives us a concrete number that expresses how far from ‘best’ the prospective line is.
A line that provides a minimum error can be considered the best straight line.
Since it’s the distance from our points to the line we’re interested in—whether it is positive or negative distance is not relevant—we square the distance in our error calculations. This also allows us to weight greater errors more heavily. So this method is called the least square approach.
(ii) Polynomial curve fitting is when we fit our data to the graph of a polynomail function. The same least squares method can be used to find the polynomial, of a given degree, that has a minimum total error.
1. What does popt and pcov mean? (Watch the video to get some context)
popt stores the coefficients that are calculated by the curve_fit function. It is a output .
The pcov variable contains the covariance matrix, which indicates the uncertainties and correlations between parameters. This is mostly useful when the data has uncertainties. pcov stores the estimated co variance in the popt values . This is also a output. This is a 2D array
2. What does np.array(temperature) do?
This command converts each value of temperature in the data file into an array using numpy module.
3. What does the * in *popt mean?
Helps to refer the values stored in the popt array.
4. Write code to fit a linear and cubic polynomial for the Cp data. Explain if your results are good or bad.
Python code for Linear Polynomial
import numpy as np
import matplotlib.pyplot as plt
from scipy.optimize import curve_fit
def func(t, a, b):
return a*t + b
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(func, temperature, cp)
fit_cp = func(np.array(temperature), *popt)
plt.plot(temperature, cp,,linewidth=3)
plt.plot(temperature, fit_cp,,linewidth=3)
plt.legend(['Actual data', 'Curve fit'])
plt.xlabel('Temperature[K]')
plt.ylabel('Cp')
plt.show()
Python code for cubic polynomial
import numpy as np
import matplotlib.pyplot as plt
from scipy.optimize import curve_fit
def func(t, a, b, c, d):
return a*pow(t,3) + b*pow(t,2) + c*t + d
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(func, temperature, cp)
fit_cp = func(np.array(temperature), *popt)
plt.plot(temperature, cp,,linewidth=3)
plt.plot(temperature, fit_cp,,linewidth=3)
plt.legend(['Actual data', 'Curve fit'])
plt.xlabel('Temperature[K]')
plt.ylabel('Cp')
plt.show()
5. What needs to be done in order to make the curve fit perfect?
If we increase the order of the polynomial, the error produced will be less and curve fit perfectly. On increasing the order of the polynomial the shape of the curve matches to that of the given data set.
6. Show empirically as to how well your curve has been fit.
How to choose the best fit?
Upon finding a curve which satisfies the data points there are 4 quantities which help us measure the goodness of fit criteria or how well the equation is a representing the datapoints. There are,
SSE (Sum of error squared)
SSR (Sum of error squared)
SST (sum of the squared total)
RMSE (Root mean squared error)
SST = SSR/SST
RMSE = (SSE/1)^0.5
For linear polynomial function

For cubic polynomial function

Results:
Linear fit

Cubic Fit

Conclusion
Curve fitting for the given data set is performed using linear polynomial function and also cubic polynomial function.
Best curve fit is obtained by increasing the order of the polynomial like in our case as we increase the order of polynomial from 1 to 3 we can see that the errors get minimised.