Challenge

PYTHON - Curve fitting

AIM:

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

INTRODUCTION:

What is curve fitting?

Creating a curve (by creating curve equation using mathematical functions) that closely resembles the curve plotted using original set of datas.

Why do we need it?

i) To get functional relationship between original data set and parameters.

ii) To get accurate value of point inbetween two points of given data(interpolation).

iii) To find accurate extrapolated values (for eg. to find the future weather data based on current and previous datas)

CODE WITH EXPLANATIONS:

Linear equation Curve fit

  1. Import modules (math-Mathematical functons like sin, cos etc; matplotlib.pyplot-plots; numpy-linspace; curve_fit from scipy for performing curve fitting)
  2. Define a function for linear equation that returns the value of linear equation.
  3. Define a function to read the givn file. Use for loop to read line by line and store temperature and Cp values from them and retuen them.
  4. Use variables temp,cp to store returned values from readfile() function
  5. Use variables popt, pcov to store the answers (coefficients and covariance of coefficients respectively) by calling function curve_fit which takes arguments: function defining equation, 2 parameters i.e., here temperature and Cp.
  6. Use fit_cp to store the of new Cp returned by calling the first function by passing arguments (temp [no.array(temp) will used to send temp variables one b one an thus making fit_cp as array,*popt to send coefficients found as whole(not a and b seperately)])
  7. Plot 2 curves, old Cp vs temperature and new Cp vs temperature withh appropriate labels, title and legend.
  8. Save the plot and display.

CODE with necessary explanations in comments

#LINEAR CURVE FIT

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

#Function for linear equation
def func(t,a,b):
	return (a*t) + b
#Function for reading file and returning temperature and Cp
def read_file():
	temp=[]
	cp=[]
	for line in open('data','r'):
		#Splitting Line by ',' and store them as string 2D array in values
		values=line.split(',')
		#float here used to convert string typr to float type
		temp.append(float(values[0]))
		cp.append(float(values[1]))
	return [temp,cp]

#Storing temperature and Cp value by calling read_file() function
temp,cp=read_file()
#Finding coefficents and covariance of coefficients by using curve_fit function
popt,pcov=curve_fit(func,temp,cp)
#Predicting Cp value using new coefficents; '*' used to send the all arguments, here a,b which was found
fit_cp=func(np.array(temp),*popt)

#Plotting begins
plt.plot(temp,cp,color="blue",linewidth=3)
plt.plot(temp,fit_cp,color="red",linewidth=3)
#Labelling axes
plt.xlabel('Temperature (K)')
plt.ylabel('Cp')
#Specifying Legend
plt.legend(['Actual Data','Curve Fit'])
#Giving title
plt.title('Linear Curve Fit')
#Saving plot
plt.savefig('Linear_curve_fit.png')
#Displaying plot
plt.show()

Cubic equation Curve fit

  • Import modules (math-Mathematical functons like sin, cos etc; matplotlib.pyplot-plots; numpy-linspace; curve_fit from scipy for performing curve fitting)
  • Define a function for cubic equation that returns the value of cubic equation.
  • Define a function to read the givn file. Use for loop to read line by line and store temperature and Cp values from them and return them.
  • Use variables temp,cp to store returned values from readfile() function
  • Use variables popt, pcov to store the answers (coefficients and covariance of coefficients respectively) by calling function curve_fit which takes arguments: function defining equation, 2 parameters i.e., here temperature and Cp.
  • Use fit_cp to store the of new Cp returned by calling the first function by passing arguments (temp [no.array(temp) will used to send temp variables one b one an thus making fit_cp as array,*popt to send coefficients found as whole(not a,b, and d seperately)])
  • Plot 2 curves, old Cp vs temperature and new Cp vs temperature withh appropriate labels, title and legend.
  • Save the plot and display.

CODE with necessary explanations in comments

#CUBIC CURVE FIT

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

#Function for cubic equation
def func(t,a,b,c,d):
	return ((a*pow(t,3)) + (b*pow(t,2)) + (c*t) + d)

#Function for reading file and returning temperature and Cp
def read_file():
	temp=[]
	cp=[]
	for line in open('data','r'):
		#Splitting Line by ',' and store them as string 2D array in values
		values=line.split(',')
		#float here used to convert string typr to float type
		temp.append(float(values[0]))
		cp.append(float(values[1]))
	return [temp,cp]

#Storing temperature and Cp value by calling read_file() function
temp,cp=read_file()
#Finding coefficents and covariance of coefficients by using curve_fit function
popt,pcov=curve_fit(func,temp,cp)
#Predicting Cp value using new coefficents; '*' used to send the all arguments, here a,b,c,d which was found
fit_cp=func(np.array(temp),*popt)

#Plotting begins
plt.plot(temp,cp,color="blue",linewidth=3)
plt.plot(temp,fit_cp,color="red",linewidth=3)
#Labelling axes
plt.xlabel('Temperature (K)')
plt.ylabel('Cp')
#Specifying Legend
plt.legend(['Actual Data','Curve Fit'])
#Giving title
plt.title('Cubic Curve Fit')
#Saving plot
plt.savefig('cubic_curve_fit.png')
#Displaying plot
plt.show()

RESULTS:

Linear equation curve fit:

Cubic equation curve fit:

CONCLUSIONS:

DISCUSSIONS

From the plots it is clear that cubic equations resembles more with original data than that of linear equation.

Also as temperature increases specificheat at constant pressure aso increases.

1. What does popt and pcov mean?

popt is the values of coefficients of the equation of the function passed.

pcov is the estimated covariance of popt i.e., cofficients. The diagonals provide the variance of the coefficients estimate. From them we can determine the standard deviations of the coefficients.

2. What does np.array(temperature) do?

Here, it will send temperature values as arrays to function so that Cp will also becomes array of type(2d,3d) temp

3. What does the * in *popt mean?

It expands the popt array, so each coefficients become the second,third....... arguments to the function that defines equation.

4. Explain if your results are good or bad.

For linear equation, results are not great as it is not resembling original curve most parts

Wheras cubic equations, comparitively resembles more with original data's curve but still not perfectly mathching.

5. What needs to be done in order to make the curve fit perfect?

Order of polynomial equation should be increased.

Region wise giving optimsed order of polynomial equation can be used (i.e, spliting curves and for each segment, sepearte, optimised order of polynomial equation can be used)

Parameters used to measure the goodness of fit:

  1. The sum of squares due to error (SSE):summation(from i=1 to n) of (y(i)-f(x(i)))^2
  2. R-square: R^2=(SSR/SST) where SST=SSR+SST; SSR=summation(from i=1 to n) of (f(x(i))-mean)^2;SSE=summation(from i=1 to n) of (y(i)-mean)^2;
  3. Adjusted R-square-used when there are variables that unaffect functions but still affect R^2.
  4. Root mean squared error (RMSE)- sqrt(SSE/n) - Estimation of standard deviation of random component in data set.
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.