Challenge

Week 5 - Curve fitting

AIM: To perform curve fitting on Temperature Vs Cp file and determining the goodness of the fit.

THEORY:

1)Understanding popt & popt.

popt
Optimal values for the parameters so that the sum of the squared residuals of f(xdata, *popt) - ydata is minimized.

pcov
The estimated covariance of popt.

2)np.array(temperature) creates an array with the values present in temperature variable [ ].

3)* in *popt is used to store all the values from the popt array as it is multi dimensional.

CODE:

Writing a code to fit a linear, quadratic and cubic polynomial for Cp data.

import numpy as np 
import matplotlib.pyplot as plt 
from scipy.optimize import curve_fit
from statistics import mean

# Defining Functions for Quadratic and Cubic Curve Fit

def func_linear(e,f,g):
	return f*e + g


def func_quadratic(x,m,n,o,p):
	return m*pow(x,2) + n*x + o

def func_cubic(t,a,b,c,d):
	return a*pow(t,3) + b*pow(t,2) + c*t + d

#Reading Thermodynamic data file

def read_file():
	temp = []
	cp = []
	for line in open('data','r'):
		values = line.split(',')
		temp.append(float(values[0]))
		cp.append(float(values[1]))
	return [temp,cp]

#Main Program


#1 Using curve_fit command to calculalte the Coefficients for the Quadratic Function
temp,cp = read_file()
popt1,pcov1 = curve_fit(func_quadratic, temp,cp)
fit_cp_quadratic = func_quadratic(np.array(temp), *popt1)

#2 Using curve_fit command to calculalte the Coefficients for the cubic Function

temp,cp = read_file()
popt2,pcov2 = curve_fit(func_cubic, temp,cp)
fit_cp_cubic = func_cubic(np.array(temp), *popt2)

#3 Using curve_fit command to calculalte the Coefficients for the linear Function

temp,cp = read_file()
popt3,pcov3 = curve_fit(func_linear, temp,cp)
fit_cp_linear = func_linear(np.array(temp), *popt3)







# Plotting the curves using Curve Fit data


plt.plot(temp,cp,color="blue",linewidth=2)
plt.plot(temp,fit_cp_quadratic,color="red",linewidth=2)
plt.plot(temp,fit_cp_cubic,color="green",linewidth=2)
plt.plot(temp,fit_cp_linear,color="yellow",linewidth=2)
plt.legend(['Actual data','Quadratic curve fit','Cubic Curve Fit','Linear Curve Fit'])
plt.xlabel('Temperature [K]')
plt.ylabel('Cp')
plt.show()

# Calculating R-square to identify the goodness of fit

n = len(temp)


def R_square(temp,cp,fit_cp):
	for i in range(0,len(temp)):
		Mean = mean(cp)
		SSR = np.sum(pow((fit_cp[i]-Mean),2))
		SSE = np.sum(pow((cp[i]-fit_cp[i]),2))
		SST = SSR+SSE
		R_2 = SSR/SST
		
	return R_2


# Calculating RMSE For goodness of the Fit


def RMSE(temp,cp,fit_cp):
	for i in range(0,len(temp)):

		SSE = np.sum(pow((cp[i]-fit_cp[i]),2))
		RMSE = pow(SSE/n,0.5)
		
	return RMSE

#Finding R-Square and RMSE(Root mean squared error ) to determine the goodness of the fit

R2_linear = R_square(temp,cp,fit_cp_linear)
R2_cubic = R_square(temp,cp,fit_cp_cubic)
R2_quadratic = R_square(temp,cp,fit_cp_quadratic)

RMSE_linear = RMSE(temp,cp,fit_cp_linear)
RMSE_cubic = RMSE(temp,cp,fit_cp_cubic)
RMSE_quadratic = RMSE(temp,cp,fit_cp_quadratic)


# Printing The values for R-sqaure and RMSE

print("The R-Square value for Linear Curve is " + str(R2_linear))
print("The R-Square value for Quadratic Curve is " + str(R2_quadratic))
print("The R-Square value for Cubic Curve is " + str(R2_cubic))
print("The RMSE value for Linear Curve is " + str(R2_linear))
print("The RMSE value for Quadratic Curve is " + str(RMSE_quadratic))
print("The RMSE value for Cubic Curve is " + str(RMSE_cubic))

GOODNESS OF THE FIT:

To check how good the curve fit given by the program is, values Root Mean Square Error(`RMSE`) and `R^2` were calculated.

`RMSE` is a measure of the average deviation of the Cp from the data file values.

The `R^2` value indicates the percentage of variability in Cp that is explained by the model.

The formulas to calculate these values are as follows:

  • `RMSE = sqrt((SSE)/n` where 'SSE' is the sum of squared errors and 'n' is the number of data points
  • `R^2 = (SSR)/(SST)`where 'SSR' is the sum of squares of regression and SST=SSR+SSE

RESULTS:

Three Curves (linear,quadratic and cubic) were plotted against the original curve for comparison.

From the results, we can conclude that polynomials with higher degree will result in accurate curve fit.

The values of `RMSE` and `R^2` were calculated for all the curves.

`RMSE` was lowest for cubic curve followed by quadratic curve and linear line had highest `RMSE`.

`R^2` was highest for cubic curve followed by quadratic curve and then linear.

Your portfolio, next

Ship work like this
in your own course.

Talk to a career counsellor

Free 20-minute call. We'll map the right course to where you want to work.

By submitting you agree to our Terms and Privacy Policy.

Talk to a career counsellor

Free 20-minute call. We'll map the right course to where you want to work.

By submitting you agree to our Terms and Privacy Policy.