Python program for curve fitting the data of specific heat
AIM: Write a PYTHON Program to perform curve fitting and understand the parameters affecting the curve fit
OBJECTIVES:
- Write code to fit a linear and cubic polynomial for the Cp data.
- Plot the linear and cubic fit curves along with the raw data points.
- Understand the parameters used to measure the fitness characteristics for both the curves
- Explain the need of curve fitting
- Calculation of goodness of fit of given curve characteristics
GOVERNING EQUATIONS AND LAWS:
- Suppose each of these n points has an individual error (difference in y co-ordinate values)
The error for a general "i" point can be given by the function:
ERROR = `| y ( i ) − f ( x ( i ) ) |` , where `y = f(x)`
- To find Sum of Square of Errors:
`SSE = sum_(i=0)^N Err(i)^2`
- Form of the equation:
`f ( x ) = A 1 + A 2 ⋅ x + A 3 ⋅ x ^2 + ... + A n ⋅ x^(n − 1)`
- To calculate Sum of Square of Regression:
`SSR = sum_(i=0)^N ( f ( x ( i ) ) − M e a n ) ^2`
- To calculate Sum of Square of Total Error:
`S S T = S S R + S S E`
- R-square
This quantity that measures how successful the fit is in explaining the variation of the data. Put another way, R-square is the square of the correlation between the response values and the predicted response values. It is also called the square of the multiple correlation coefficient and the coefficient of multiple determination
`R^2 = (SSR)/{SST)`
- To Calculate Root Mean Squared Error:
`RMSE = sqrt((SSE)/n`, Where n in number of data points
INPUT:
https://drive.google.com/file/d/1vWi9Vj3AdQf0gqUK1u9jwS8zg92BHGR0/view
BRIEF EXPLAINATION:
- What is Curve Fitting ?
Curve fitting is the process of constructing a curve, or mathematical functions, which possess the closest proximity to the real series of data. By curve fitting, we can mathematically construct the functional relationship between the observed dataset and parameter values, etc. It is highly effective in the mathematical modelling of some natural processes
- Need of Curve Fitting:
Curve fitting, also known as regression analysis, is used to find the "best fit" line or curve for a series of data points. Most of the time, the curve fit will produce an equation that can be used to find points anywhere along the curve. In some cases, you may not be concerned about finding an equation. Instead, you may just want
to use a curve fit to smooth the data and improve the appearance of your plot
- Polynomial Selection:
This function fits a curve through your data, of the form `y=m0 + m1 * x + m2 * x^2 + m3*x^3 +...+ m9 * x^9`.
The more complex the curvature of the data, the higher the polynomial order required to fit it. There are nodata restrictions associated with this curve fit.
In this program we use third order polynomial for curve fitting to obtain the best fir possible and to avoid much deviation
- How to choose 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,
- The sum of squares due to error (SSE)
- R-square
- Adjusted R-square
- Root mean squared error (RMSE)
CODE AND STEP-WIDE EXPLAINATION:
case1)
"""
Curve fit using a Linear polynomial
"""
# importing required modules
import numpy as np
import matplotlib.pyplot as plt
from scipy.optimize import curve_fit
# setting up a linear function
def fun(t, a, b,):
val = a*t + b
return val
# function to open-up the data file
def read_file():
# setting up a file handle
fh = open('data', 'r')
temp = []
cp = []
for line in fh:
# splitting using comma as deliminator
values = line.split(',')
temperatures = float(values[0])
cps = float(values[1])
temp.append(temperatures)
cp.append(cps)
return [temp, cp]
# invoking the function created
temp, cp = read_file()
# dividing the data into 2 sets
temp1 = temp[0:1600]
temp2 = temp[1600:]
cp1 = cp[0:1600]
cp2 = cp[1600:]
# main program
# implimenting curve fit
popt, pcov = curve_fit(fun, temp, cp)
popt1, pcov1 = curve_fit(fun, temp1, cp1)
popt2, pcov2 = curve_fit(fun, temp2, cp2)
# '*' refers to all the values
fit_cp = fun(np.array(temp), *popt)
fit_cp1 = fun(np.array(temp1), *popt1)
fit_cp2 = fun(np.array(temp2), *popt2)
# plotting the graph
plt.plot(temp, cp, color='blue',Linewidth=3)
plt.plot(temp1, fit_cp1, color='red',Linewidth=3)
plt.plot(temp2, fit_cp2, color='red',Linewidth=3)
plt.legend(['Actual data', 'curve fit 1 ','curve fit 2'])
plt.show()
"""
Calculating error and choosing best fit
for linear data
"""
# mean of the data-set
M = np.mean(cp)
# sum of square of error (0 initially)
SSE = 0
# sum of square of regression (0 initially)
SSR = 0
for i in range(len(cp)):
SSE += pow(cp[i] - fit_cp[i], 2)
SSR += pow(cp[i] - M,2)
SST = SSE + SSR
# R-square
R_square = SSR/SST
print('The value of R-square for Linear fit is', R_square)
# Root mean Square Error
RMSE = pow(SSE/len(cp),0.5)
print('The value of RMSE for Linear fit is', RMSE)
RESULT AND DISCUSSION
In the above plot we could see that if we use linear function the curve does not fit well, and we could improve the accuracy of curve by splitting the data itno number of sets
Hence you could observe the variation between the actual and the fitted curve, hence it is not considered as a good fit
Since the value of R-square is less than 0.95 hence the curve is not consider as a good fit and the value of RMSE is greater than 20
Case2)
"""
Curve fit using a cubic polynomial
"""
# importing required modules
import numpy as np
import matplotlib.pyplot as plt
from scipy.optimize import curve_fit
# setting up a cubic function
def fun(t, a, b, c, d):
val = a*pow(t,3) + b*pow(t,2) + c*t + d
return val
# function to open-up the data file
def read_file():
# setting up a file handle
fh = open('data', 'r')
temp = []
cp = []
for line in fh:
# splitting using comma as deliminator
values = line.split(',')
temperatures = float(values[0])
cps = float(values[1])
temp.append(temperatures)
cp.append(cps)
return [temp, cp]
# invoking the function created
temp, cp = read_file()
# dividing the data into 2 sets
temp1 = temp[0:1600]
temp2 = temp[1600:]
cp1 = cp[0:1600]
cp2 = cp[1600:]
# main program
# implimenting curve fit
popt, pcov = curve_fit(fun, temp, cp)
popt1, pcov1 = curve_fit(fun, temp1, cp1)
popt2, pcov2 = curve_fit(fun, temp2, cp2)
# '*' refers to all the values
fit_cp = fun(np.array(temp), *popt)
fit_cp1 = fun(np.array(temp1), *popt1)
fit_cp2 = fun(np.array(temp2), *popt2)
# plotting the graph
plt.plot(temp, cp, color='blue',Linewidth=3)
plt.plot(temp1, fit_cp1, color='red',Linewidth=3)
plt.plot(temp2, fit_cp2, color='red',Linewidth=3)
plt.legend(['Actual data', 'curve fit 1 ','curve fit 2'])
plt.show()
"""
Calculating error and choosing best fit
for cubic data
"""
# mean of the data-set
M = np.mean(cp)
# sum of square of error (0 initially)
SSE = 0
# sum of square of regression (0 initially)
SSR = 0
for i in range(len(cp)):
SSE += pow(cp[i] - fit_cp[i], 2)
SSR += pow(cp[i] - M,2)
SST = SSE + SSR
# R-square
R_square = SSR/SST
print('The value of R-square for cubic fit is', R_square)
RMSE = pow(SSE/len(cp),0.5)
print('The value of RMSE for cubic fit is', RMSE)
RESULT AND DISCUSSION:
We could see that the Curve is not a perfect fit but it is a good fit and quite accurate as compared to the linear fit
Hence there is very low error between the actual and the calculated fit, as we have implimented split-wise segregation of data
Since the value of R-square is greater than 0.95 hence the curve is consider as a good fit and the value of RMSE is less than 20, hence it is a good curve fit
CONCLUSION:
- Hence from above output we could conclude the value of R-square for 'Cubic' is greater than that of the 'Linear' fit. Hence the Cubic fit is more accurate.
- The value of RMSE for Cubic fir is less than the RMSE for Linear Fit.
- We also conclude that the accuracy of the fit could be increased by dividing the data into more and more data-sets.