Project

curve fitting script using python

OBJECTIVE

The objective of this program is to get the best fit from the equation of linear and cubic for the curve by calculating the error values. hence the curve is plotted using the data given.

PROGRAM

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


# equation
def func_cubic(x,a,b,c,d):
	return 	((a*x**3)+(b*x**2)+(c*x)+d)
def func_linear(x,a,b):
	return (a*x)+b

def rd_f():
	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
#using the linear equation
temp,cp=rd_f()
fcp=[]
popt,pcov=curve_fit(func_linear,temp,cp)
fit_cp=func_linear(np.array(temp),*popt)

                                          #fit curve using cubic equation
popt,pcov=curve_fit(func_cubic,temp,cp)
fitfit_cp=func_cubic(np.array(temp),*popt)
q=[] 
ql=[]                                      # ssr final array values
ssr=np.zeros(len(fitfit_cp))               #zeros in the numpy module makes the array defined with 0 as element in it
sse=np.zeros(len(fitfit_cp))
ssrl=np.zeros(len(fit_cp))
ssel=np.zeros(len(fit_cp))
data=tuple(zip(temp,cp,fit_cp,fitfit_cp))
mean_value=(np.mean(cp))
for i in range(0,len(data)):
	error=(data[i][1]-data[i][3])
	sse[i]=(error)**2
	ssr[i]=(data[i][3]-mean_value)
	#print(data[i][1])
	#print(np.mean(data[1]))
	Q=(ssr[i])**2
	q.append(Q)
	error_l=(data[i][1]-data[i][2])
	ssel[i]=(error_l)**2
	ssrl[i]=(data[i][2]-mean_value)
	Ql=(ssrl[i])**2
	ql.append(Ql)

#print(data[1])
SSR=sum(q)
SSRL=sum(ql)
SSEL=sum(ssel)
SSE=sum(sse)
SST=(SSR+SSE)
SSTL=(SSRL+SSEL)
R_c=((SSR/SST)*100)
R_l=((SSRL/SSTL)*100)
print (\'the error of cubic function:\',\'\\n\', \'SSE\',SSE,\'\\n\',\'SSR\',SSR,\'\\n\',\'SST\',SST,\'\\n\',\'R_c\',R_c)
print(\'the error of linear function:\',\'\\n\', \'SSE\',SSEL,\'\\n\',\'SSR\',SSRL,\'\\n\',\'SST\',SSTL,\'\\n\',\'R_l\',R_l)
plt.plot(temp,cp,\'b\')
plt.plot(temp,fit_cp,\'r\')
plt.plot(temp,fitfit_cp,\'g--\')
plt.xlabel(\'temperature\')
plt.ylabel(\'cp\')
plt.legend([\'actual_data\',\'linear_fit\',\'cubic_fit\'])
plt.show()

OUTPUT

By the output for the given data the curve fit is having the best fit with cubic function and the error percentage is which is the best fit with curvefit is cubic and the percentage of the cubic function is 99.67%.

\"\"

COMMANDS USED

  • matplotlib -> matplotlib is an amazing visualization library in python for 2D plots of arrays. This command is used to plot graphs using the code.
  • math -> This library is used when we use the trigonometric functions.
  • def () -> This keyword is used to define function along with all suitable parameters related to the problem.
  • return() -> The return statement is used when a function is ready to return a value to its caller.
  • numpy -> This module is used for assigning n values in between two values with the same common difference.
  • append() -> This function is used to append the calculated values in an empty array
  • plt.figure() -> This command is used to display the multiple graphs at a time side by side to compare results.
  • plt.plot() -> This command is used to draw graphs according to their assigned values
  • plt.label() -> This command is used to label the axis to differentiate the values on the curves.
  • plt.show() -> This command is used to display the results graphs on the screen as output.
  • plt.savefig() -> This command is used to save the output images in particular folder.
  • plt.title() -> This command is used to give title for the drawn graph.
  • plt.legend() -> This command is used to label inside the graph .
  • scipy -> This library is used to get access to the function with which we plot graph for given data points.
  • curve_fit() -> This function is used for fitting the curve according to the given data.
  • func() -> This function is used to define a function for drawing a curve.
  • open() -> This is used to open a file and read the data.
  • line.split() -> This function is used to split data into to arrays.
  • popt -> This function gives the values .
  • pcov -> This function gives the covariance matrix.

THINGS TO KNOW ABOUT

  1. popt and pcov:
  • popt -> The popt argument is the best-fit parameters for a and b.This argument helps in finding the approximate values for a and b and close to the solution. Optimal values for the parameters so that the sum of the squared residuals for the function is minimized.
  • pcov -> The pcov that fit curve returns are the covariance matrix for the estimated parameters. The diagonal elements are the variances. They tell us how likely the parameter is to vary, or how confident we are in the estimate. A large variance basically means we don\'t know very much about the parameter; the value returned in popt is the most likely value, but even far-away values are also very likely. The off-diagonal elements are the covariances. Their meaning is actually hidden in the name: co-variance; how variables vary together
  • * in *popt: The * notation will expand a list of values into the arguments of the function. This is useful if your function has more than one or two parameters.

CONCLUSION

Hence the program scripted above is as belongs and completes the challenge that helps to know which function is the best fit for the given data parameters.

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.