Challenge

Week 5 - Curve fitting

AIM:-

To write a python code to fit a linear and cubic polynomial for the Cp data and plot linear and cubic fit curves.

THEORY :-

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 modeling of some natural processes.

How to choose the 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,

  1. The sum of squares due to error (SSE)
  2. R-square
  3. Adjusted R-square
  4. Root mean squared error (RMSE)

PROGRAM:-

"""
Curve Fitting using Python
Program by Saurabh Kshirsagar
"""
import math
import matplotlib.pyplot as plt 
import numpy as np 
from scipy.optimize import curve_fit

#Linear curve fit function
def func_1(t,a,b):
	return a*t + b

#Cubic curve fit function
def func_2(t,a,b,c,d):
	return a*pow(t,3) + b*pow(t,2) + c*t + d

#Reading thermodynamic data 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()

popt, pcov = curve_fit(func_1, temperature, cp)
fit_cp_1 = func_1(np.array(temperature), *popt)
plt.figure(1)
plt.plot(temperature,cp,color="blue")
plt.plot(temperature,fit_cp_1,color="red")
plt.legend(['Actual Data','Curve Fit'])
plt.xlabel('Temperature (K)')
plt.ylabel('Cp (KJ/kg*K)')
plt.title('Linear Curve Fitting')
plt.savefig('Linear Curve Fitting')
plt.show()

popt, pcov = curve_fit(func_2, temperature, cp)
fit_cp_2 = func_2(np.array(temperature), *popt)
plt.figure(2)
plt.plot(temperature,cp,color="blue")
plt.plot(temperature,fit_cp_2,color="red")
plt.legend(['Actual Data','Curve Fit'])
plt.xlabel('Temperature (K)')
plt.ylabel('Cp (KJ/kg*K)')
plt.title('Cubic Curve Fitting')
plt.savefig('Cubic Curve Fitting')
plt.show()

#Measuring parameters for fitness characteristics of curve and finding mean of Cp
l = np.size(cp)
s = np.sum(cp)
m = s/l

#For linear curve fitting
linear_SSE = 0
linear_SSR = 0
for i in range(l):
	linear_error = abs((np.sum((cp[i]-fit_cp_1[i]))))
	linear_SSE = linear_SSE + pow(linear_error,2)
	linear_SSR = linear_SSR + np.sum(pow((fit_cp_1[i]-m),2))

print('\nFitness Characteristic of Linear Fit\n\nSSE for linear : ',linear_SSE)
linear_SST = linear_SSE +linear_SSR
linaer_Rsquare = linear_SSR/linear_SST
print('Rsquare for linear : ',linaer_Rsquare)
Linear_RMSE = pow((linear_SSE/l),0.5)
print('RMSE for linear : ',Linear_RMSE)

#For cubic curve fitting
cubic_SSE = 0
cubic_SSR = 0
for j in range(l):
	cubic_error = abs((np.sum((cp[j]-fit_cp_2[j]))))
	cubic_SSE = cubic_SSE + pow(cubic_error,2)
	cubic_SSR = cubic_SSR + np.sum(pow((fit_cp_2[j]-m),2))

print('\nFitness Characteristic of Cubic Fit\n\nSSE for cubic : ',cubic_SSE)
cubic_SST = cubic_SSE + cubic_SSR
cubic_Rsquare = cubic_SSR/cubic_SST
print('Rsquare for cubic : ',cubic_Rsquare)
cubic_RMSE = pow((cubic_SSE/l),0.5)
print('RMSE for cubic : ',cubic_RMSE)

EXPLANATION:-

  • We import math, matplotlib, numpy, and scipy module to solve this program.
  • We define func_1 to solve linear polynomial.
  • We define func_2 to solve cubic polynomial.
  • We open the data file using for loop and append the required data in empty arrays.
  • We plot the required data using matplotlib.
  • We find the fitness characteristics using following formulas:
  • Finally we type the command to print all required values.

OUTPUT:-

1. Linear curve fitting plot

2. Cubic curve fitting plot

3. Fitness characteristics of cubic and linear fit.

CONCLUSION:-

To make curve fit good Rsquare must be equal to 1.

From the above results, Rsquare for linear curve fit is approxx equal to 0.92 and for cubic curve fit it is 0.99.

Hence, cubic polynomial fit is better than linear polynomial.

QUESTION AND ANSWERS:-

Q.1:- What does popt and pcov mean?

Answer:- popt means it is the array which contain the optimum values of coefficients for the polynomial and pocv means it is the 2D array which contain the estimated covarience of parameter in popt.

Q.2:- What does np.array(temperature) do?

Answer:- The command 'np.array(temperature)' is used for accessing the individual elements of the temperature array with the help of numpy module. Numpy module/library is imported as 'np' and used to perform mathematical operations like addition, subtraction, multiplication, division, etc. on each element of an array or between the arrays.

Q.3:- What does the * in *popt mean?

Answer:- “ * ” is along with the popt option which is used to provide the values of coefficient to expand the data of values stored in the ‘popt’ array to perform the operation of the function. If we will not use * then it will not take the values of coefficient.

Q.4:- What needs to be done in order to make the curve fit perfect?

Answer:- In order to make perfect fit, we must consider error estimates as well. Perfect fit means, the curve should fit the original curve without showing any errors (such as centering and scaling erros) in that perticular degree of polynomial.

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.