Week 5 - Curve fitting
1. What does popt and pcov mean?
A.
popt is an array where each coefficient of the equation is produced with consideration for the degree of the polynomial.
The covariance of popt is organized as a 2D array called pcov. Covariance provides the relationship between two values, and in this case, pcov provides the relationship between the pop values.
2. What does np. array(temperature) do?
A. A group of items kept in consecutive memory regions is known as an array. The goal is to group objects of the same category for storage. The array command in Python is contained in a package named numpy. In our challenge, the temperature is kept in a 3200-data array.
3. What does the * in *popt mean?
A. The "*" in the "*popt* tells the Python code to indicate and return the values of the coefficients that are 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.
A.Code for linear polynomial using given Cp data
PROGRAM
import numpy as np
import matplotlib.pyplot as plt
from scipy.optimize import curve_fit
# Cubic Fit Function
def cubic_func(t, a, b, c, d):
return a*pow(t,3) + b*pow(t,2) + c*t + d
# 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]
# Cubic Curve Fitting
temperature, cp = read_file()
popt, pcov = curve_fit(cubic_func, temperature, cp)
fit_cp2 = cubic_func(np.array(temperature), *popt)
plt.plot(temperature, cp, color = "YELLLOW", linewidth = 3)
plt.plot(temperature, fit_cp2, color = "BLACK", linewidth = 3)
plt.legend(["Actual Data", "Curve Fit"])
plt.xlabel("Temperature [K]")
plt.ylabel("Cp")
plt.show()
# GOF Characteristics
total_cp = np.sum(cp)
numval_cp = np.size(cp)
avg_cp = total_cp/numval_cp
print('Average Cp is:', avg_cp)
# Linear Curve GOF
for i in range(numval_cp):
sst = np.sum(pow((cp[i]-avg_cp),2))
ssr = np.sum(pow((cp[i]-fit_cp2[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)
RESULT:
Average Cp is: 1182.785685525818 R-Squared: 0.932478836047853 RMSE: 0.5759268074944738
PLOT:
FOR CUBIC POLYNOMIAL:
PROGRAM:
import numpy as np
import matplotlib.pyplot as plt
from scipy.optimize import curve_fit
# Cubic Fit Function
def cubic_func(t, a, b, c, d):
return a*pow(t,3) + b*pow(t,2) + c*t + d
# 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]
# Cubic Curve Fitting
temperature, cp = read_file()
popt, pcov = curve_fit(cubic_func, temperature, cp)
fit_cp2 = cubic_func(np.array(temperature), *popt)
plt.plot(temperature, cp, color = "ORANGE", linewidth = 1)
plt.plot(temperature, fit_cp2, color = "GREEN", linewidth = 2)
plt.legend(["Actual Data", "Curve Fit"])
plt.xlabel("Temperature [K]")
plt.ylabel("Cp")
plt.show()
# GOF Characteristics
total_cp = np.sum(cp)
numval_cp = np.size(cp)
avg_cp = total_cp/numval_cp
print('Average Cp is:', avg_cp)
# Linear Curve GOF
for i in range(numval_cp):
sst = np.sum(pow((cp[i]-avg_cp),2))
ssr = np.sum(pow((cp[i]-fit_cp2[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)
EXPLANATION OF CODE:
The R-Squared value was 0.989, and the RMSE value was 0.238 to three decimal places, according to the goodness of fit calculations. The cubic model's R-squared value was closer to 1 and its RMSE value was lower than the linear model's R-squared value. In this regard, the cubic model outperforms the linear model in terms of fit. Additionally, we can observe from the graph output that the cubic model more closely matches the real data set. According to these findings, the cubic model is superior to the linear model.
RESULT:
Average Cp is: 1182.785685525818 R-Squared: 0.9885089679730077 RMSE: 0.23758928546337932
PLOT:
So we can conclude that the cubic polynomial equation gives a better result than the linear equation by the variation in the error.
5. What needs to be done to make the curve fit perfectly?
A. There are two ways that the curve fit model might be improved. The first approach is tweaking the fitted function by trial and error and checking the changes in the graphical output to determine if the model is more accurately representing the data. Many possible permutations of coefficients may be used to test whether the model is more accurate or not. Regarding the order of the polynomial, this technique is constrained. This is because no matter how many different combinations of coefficients we try, the order of that model can only attain a certain degree of fit. When employing higher-order polynomials, the second approach, is more beneficial. The fitted model will match the data more closely if higher-order polynomials are used. This is because higher-order polynomials contain more coefficients, more of which may be changed to improve fit. It was clear from the preceding question that the cubic fitted model outperformed the linear fitted model. The cubic fitted model closely matched the form of the real data on the graph and had greater goodness of fit characteristics.
6. Show empirically how well your curve has been fit?
A.
LINEAR POLYNOMIAL
CURVE POLYNOMIAL