Week 5 - Curve fitting
Answer 1:-
In curve fitting, particularly when using nonlinear least squares fitting with functions like scipy.optimize.curve_fit() in Python, the output consists of two key variables:
1. popt (Optimal Parameters)
- popt is an array containing the best-fit parameters of the function.
- These parameters minimize the difference between the given data points and the model function.
- If you are fitting a function f(x,a,b,c)f(x, a, b, c)f(x,a,b,c), then popt will contain the estimated values of a,b,ca, b, ca,b,c.
Example:
If we fit a function f(x)=a⋅ebx+cf(x) = a \cdot e^{b x} + cf(x)=a⋅ebx+c,
popt might return:
pcov (Covariance Matrix)
- pcov is the covariance matrix of the estimated parameters.
- The diagonal elements of pcov represent the variance of each parameter.
- The square root of the diagonal elements gives the standard deviation (errors) of the parameters.
Example:
If pcov is:
ANS 2:
The "np.array(temperature)" command creates an array from the temperature values that were retrieved from the thermodynamic data file, using the "numpy" library. Having the temperature data in an array is useful in this code as it helps the code to calculate fitted "Cp" values for each respective temperature value based on the "popt" array.
ANS 3:
The "*" in the "*popt* tells the python code to indicate and return the values of the coefficients that are stored in the "popt" array.
ANS 4:
The python code for the linear curve fit model is shown in the section of code below:
import numpy as np
import matplotlib.pyplot as plt
from scipy.optimize import curve_fit
# Linear Fit Function
def linear_func(t, a, b):
return a*t + b
# Reading Thermodynamic 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()
# Linear Curve Fitting
popt, pcov = curve_fit(linear_func, temperature, cp)
fit_cp1 = linear_func(np.array(temperature), *popt)
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 [K]")
plt.ylabel("Cp")
plt.show()
total_cp = np.sum(cp)
numval_cp = np.size(cp)
avg_cp = total_cp/numval_cp
print('Average Cp is:', avg_cp)
# GOF Characteristics
for i in range(numval_cp):
sst = np.sum(pow((cp[i]-avg_cp),2))
ssr = np.sum(pow((cp[i]-fit_cp1[i]),2))
# R-Squared Value
r_squared = 1-(ssr/sst)
print("R-Squared:", r_squared)
# Root Mean Square Error (RMSE)
rmse = pow((ssr/numval_cp),0.5)
print("RMSE:", rmse)
First, the basic python libraries of "numpy", "matplotlib.pyplot" are imported into the python script along with the "curve_fit" function from the "scipy" module. Next, a function is created with the basic structure of the linear model with the variables of a, t, and b. The linear model will be of the form, y=mx+cy=mx+ci.e. a straight line.
Next, another function called "read_file" is created to read the thermodynamic file data. Within this function, two empty arrays are created for the temperature and "Cp" data. After this, a for loop is created that reads the data from the thermodynamic file by specifying the file name, "data" and the variable "r" which represents reading the data from the "data" file. This command will only be successful if the data file is located in the same directory as the python script. Within the for loop, a variable called " values" is created to separate the temperature and "Cp" data from the thermodynamic data file wherever a comma is located in every line, using the "line.split" command. Finally, the for loop ends by adding the separated temperature and "Cp" data in to the respective empty arrays using the "append" command. The distinction is made between the temperature and "Cp" values using the index positions of 0 and 1 respectively. The function ends by returning the temperature and "Cp" values.
Then, the main program begins wherein the "read_file" function is called to retrieve the temperature and "Cp" data. Next, the curve fitting is performed using the "curve_fit" function from the "scipy" module. The variables of "popt" and "pcov" are created to store the values of the coefficients and the covriance of the coefficients respectively. Within the "curve_fit" function, the linear function named "linear_func" is called out along with the temperature and "Cp" values.
ANS 5:
To make the curve fit model better, there are two methods that can be followed. The first method involves adjusting the fitted function using a trial and error method and observing the changes in the graphical output to see if the model is a better fit to the actual data. There are unlimited combinations of coefficients to try and observe whether the model is a better fit or not. However, this method has a limitation with respect to the order of the polynomial. This is because no matter how many combinations of coefficients we try, the order of that model will only reach a maximum level of fit that cannot be exceeded. this is when the second method of using higher order polynomials is more useful. When using higher order polynomials, the fitted model will be a better fit to the actual data. This is because higher order polynomials have more coefficients and thus have more coefficients that can be adjusted to be a better fit. From the previous question, it was evident that the cubic fitted model was superior to the linear fitted model. The cubic fitted model had better goodness of fit characteristics and followed the shape of the actual data more closely on the graph