Challenge

Curve fitting using PYTHON

AIM:

To write a code to perform curve fitting, solve the following problem-

1. What do "popt" and "pcov" mean? (Watch the video to get some context)

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

3. What does the * in *popt mean?

4. Write code to fit a linear and cubic polynomial for the Cp data. Explain if your results are good or bad.

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

THEORY:

Curve fitting is the process of constructing a curve or mathematical function, that has the best fit to a series of data points, possibly subject to constraints. Curve fitting can involve either interpolation, where an exact fit to the data is required, or smoothing, in which a smooth function is constructed that approximately fits the data. A related topic is regression analysis, which focuses more on questions of statistical interference such as how much uncertainty is present in a curve that is fit to data observed with random errors. Fitted curves can be used as an aid for data visualization, to infer values of a function where no data are available, and to summarize the relationships among two or more variables.

QUESTIONS:

Ques 1. What do "popt" and "pcov" mean? (Watch the video to get some context)

Answer: "popt": It is the optimal value of the parameters so that the sum of square residuals is minimized."pcov": The pcov variable contains the covariance matric, which includes the uncertainties and correlations between parameters. This is most useful when the data has uncertainties.

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

Answer: "np.array": np.array is used in the following code so that we can put the values of temperature into an array one by one. ( NumPy module ).

Ques 3. What does the * in *popt mean?

Answer: To unpack all the values stored in popt in order to pass, multiple variables to the function.

Ques 4. Write code to fit a linear and cubic polynomial for the Cp data. Explain if your results are good or bad.

Answer: Python Code to Fit a linear and cubic polynomial for Cp data :

1. LINEAR CURVE FIT:

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

#Curve_fit(f,x,y)

file = open('data','r')
def read_file() :

	temperature = []
	cp =[]

	for line in file :	
		values = line.split(',')
		temperature.append(float(values[0]))
		cp.append(float(values[1]))

	return [temperature,cp]              

	
def func(t,a,b,c):

	return a*pow(t,2)+b*t +c


temperature,cp = read_file()
popt, pcov = curve_fit(func,temperature,cp)             #popt i.e optimum parameters are returned which then can be passed to the funvction
fit_cp = func(np.array(temperature),*popt)

plt.plot(temperature,cp,linewidth = 3 , color = 'red')
plt.plot(temperature,fit_cp,linewidth = 3 , color = 'blue')
plt.xlabel('Temperature [K]')
plt.ylabel('Specific heat [cp]')
plt.legend(['Actual fit','Curve fit'])
plt.grid()
plt.savefig('Linear fit')
plt.show() 

OUTPUT PLOT:

2. CUBIC CURVE FIT:

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

#Curve_fit(f,x,y)

file = open('data','r')

def read_file() :

	temperature = []
	cp =[]

	for line in file :	
		values = line.split(',')
		temperature.append(float(values[0]))
		cp.append(float(values[1]))

	return [temperature,cp]              

	
def func(t,a,b,c,d):

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


temperature,cp = read_file()
popt, pcov = curve_fit(func,temperature,cp)             #popt i.e optimum parameters are returned which then can be passed to the funvction
fit_cp = func(np.array(temperature),*popt)

plt.plot(temperature,cp,linewidth = 3 , color = 'red')
plt.plot(temperature,fit_cp,linewidth = 3 , color = 'blue')
plt.legend(['Actual_fit','Curve fit'])
plt.xlabel('Temperature [K]')
plt.ylabel('Specific heat [cp]')
plt.grid()
plt.savefig('cubic_fit')
plt.show()  

OUTPUT PLOT:

Curve with cubic equation has comparatively less percentage error than linear and quadratic equation as seen in the figure above. Thus, we conclude that with an increase in the order of the polynomial the error percentage decreases.

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

Answer: The accuracy of the curve fit can be improved by increasing the degree of the polynomial. So, a 'Best fit' can be obtained by increasing the degree of the polynomial.

PERFECT FIT: The perfect fit is achieved when the geometric distances from the given points to the fitting curve are zero. This means that the curve fits perfectly on the points. To get a perfect fit we can increase to an order of the polynomials, this method increases the accuracy and reduces errors.

BEST FIT: The best fit is achieved when the geometric distances from the given points to the fitting curve are minimized, in the least-squares sense. Finding the best fit reduces the minimization of the objective function where denotes the fitting curve.

Upon finding a curve that satisfies the data points there are 4 quantities that help us measure the goodness of fit criteria or how well the equation is representing the data points.

  • The sum of squares due to error (SSE)
  • R-square
  • Adjusted R-square
  • Root mean squared error (RMSE)

Source: https://skill-lync.com/projects/Curve-Fitting-and-criterion-to-choose-best-fit-41860

And Python Program to make curve fit perfect:

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

#Curve_fit(f,x,y)

file = open('data','r')

def read_file() :

	temperature = []
	cp =[]

	for line in file :	
		values = line.split(',')
		temperature.append(float(values[0]))
		cp.append(float(values[1]))

	return [temperature,cp]              

	
def func(t,a,b,c,d,e):

	return a*pow(t,4)+b*pow(t,3) +c*pow(t,2)+d*t +e


temperature,cp = read_file()
popt, pcov = curve_fit(func,temperature,cp)             #popt i.e optimum parameters are returned which then can be passed to the funvction
fit_cp = func(np.array(temperature),*popt)

plt.plot(temperature,cp,linewidth = 3 , color = 'red')
plt.plot(temperature,fit_cp,linewidth = 3 , color = 'blue')
plt.legend(['Actual fit','Curve fit'])
plt.xlabel('Temperature [K]')
plt.ylabel('Specific heat [cp]')
plt.grid()  
plt.savefig('poly_fit')
plt.show()

OUTPUT PLOT:

Therefore, Inorder to improve the curve fit , the degree of polynomial must be increased. Higher the degree of polynomial better is the curve fit obtained.

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.