Performed curve fitting of the given data using python and check which polynomial function is the best fit for the data given.
Objective: Perform curve fitting of the given data using python and check which function is the best fit
for the data given.
Given data link: https://drive.google.com/file/d/1vWi9Vj3AdQf0gqUK1u9jwS8zg92BHGR0/view
1. What does popt and pcov mean?
Ans.
- popt:(array) Optimized parametre to fit the function so that the residual of the function can be minimized.
- pcov: (2darray) The estimated covariance of popt. The diagonals provide the variance of the parameter
estimate. To compute one standard deviation errors on the parameters use perr = np.sqrt(np.diag(pcov)).
2. What does np.array(temperature) do?
Ans. It stores all the value of temperature in an array so that each value of temperature can be called with
the respective value of cp.
3. What does the * in *popt mean?
Ans. Instead of passing the value of co-efficient of a function we can use '*popt' which contains the
value of co-efficient and can be called with just one command.
4. Write code to fit a linear and cubic polynomial for the Cp data. Explain if your results are good or bad.
Procedure:
1. Open the sublime text file and first save the file with the extension .py.
2. Import some modules into the command window like:
- import matplotlib.pyplot as plt
This module helps us to plot the graph of the given result.- import math
This module helps us to use mathematical functions like pie, sine, cos, etc.- import numpy
This module helps us to do mathematical operations on an element of an array.
Whenever we want to define more than one value in a single variable we have to use an array and numpy.linspace is also the same thing it stores value in a range like this;
3. numpy.linspace (lower limit, upper limit, no. of division)
This works acc. to a formula:
Size of division = (upper limit-lower limit)/(no. of division-1)
Use an empty array for storing a value which we get from FOR loop, theta1 & theta2 will store 10 values.
4. from scipy.optimize import curve_fit: Tries to fit a function f that you must know to a set of points.
5. Append is a command that will continuously append the value of a variable. It keeps on adding the values into an existing array.
so for that, we have to define an empty array for that variable which we are going to use append command. Temp is a variable in which we store values from append command.
5. use plt.plot() command to plot the graph of the given result and use plt.figure() command.
For proper animation we use .plt.xlim & plt.ylim command.
6. def func(t,a,b): here t is a variable and a, b is constant in linear equation.
7. Define another function read_file(): Create the FOR loop for reading the file which we have in our database by the name of 'Data' which contains temperature and cp values. we
append those all values into an empty array of name temperature and cp.
Linear fit curve coding:
import numpy as np
import matplotlib.pyplot as plt
from scipy.optimize import curve_fit
# curve fit function
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)
print(popt)
plt.plot(temperature, cp, 'r--', label='actual curve')
plt.plot(temperature, fit_cp,'orange', label = 'Fit curve')
plt.legend()
plt.xlabel('Temperature [k]', color='red')
plt.ylabel('cp',color='red')
plt.title('Specific Heat vs Temperature,(Linear fit)')
plt.savefig('linear fit curve')
plt.show()
Output plot:
Cubic fit curve coding:
#curve fir with cubic function
import numpy as np
import matplotlib.pyplot as plt
from scipy.optimize import curve_fit
# curve fit function(cubic)
def func1(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(func1, temperature, cp)
fit_cp = func1(np.array(temperature), *popt)
print(popt)
plt.plot(temperature, cp, 'r--', label='actual curve')
plt.plot(temperature, fit_cp,'g', label = 'Fit curve')
plt.legend()
plt.xlabel('Temperature [k]', color='red')
plt.ylabel('cp',color='red')
plt.title('Specific Heat vs Temperature,(Cubic Fit)')
plt.savefig('Cubic fit curve')
plt.show()
Output plot:
5. What needs to be done in order to make the curve fit perfect?
Ans. In order to make best fit we can start with least degree of polynomial and check whether it interpolation perfectly or not, like with this given data we have check with linear function
and cubic function after that cubic function comes out to be best fit but if the further increase the degree in this case it will not match the actual curve so we wll take cubic function for the
given problem. Likewise in other problem we have to check which is the best it can be higher degree polynomial or exponential function it completely depends on the nature of the actual
data points.
Conclusion:
- When we have more no of data it become difficult to curve fit and pass through all the points because chances of inherent error increases.
- Curve fitting is used to carry out system simulation and optimization
* To determine the values of properties at intermediate points.
* To do the trend.
* For Hypothesis testing
- For small number of parametres exact fit is possible but not for large number of parametres so we use best fit for large input parametres.