Project

Performing Curve Fitting using Python

Objective: Writing a code for curve fitting using Python for given data, also explain various points mentioned in challange.

Summary: Curve fitting is a method of constructing a curve, or mathematical function, that has the best fit to a series of data points, possibly subject to constraints. We often have a dataset comprising of data following a general path, but each data has a standard deviation which makes them scattered across the line of best fit. We can get a single line using curve-fit() function.

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

#Curve fir function (Linear)
def func(t, a, b,):
	return a*t + b

#Reading file
def read_file():
	temperature = []
	#cp = specific heat
	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, temperature, cp)
fit_cp = func(np.array(temperature), *popt)
print(popt)

plt.plot(temperature, cp, color=\"blue\", linewidth=\"5\")
plt.plot(temperature, fit_cp, color=\"red\", linewidth=\"5\")
plt.legend([\'Actual Data\', \'Linear Curve Fit\'])
plt.xlabel(\'Temperature[K]\')
plt.ylabel(\'Specific Heat(Cp)\')
plt.savefig(\'Linear Curve Fit\')
plt.show()


#Curve fir function (Cubic)
def func(t, a, b, c, d):
	return a*pow(t,3) + b*pow(t,2) + c*t + d

#Main Program
temperature, cp = read_file()
popt, pcov = curve_fit(func, temperature, cp)
fit_cp = func(np.array(temperature), *popt)
print(popt)
plt.plot(temperature, cp, color=\"blue\", linewidth=\"5\")
plt.plot(temperature, fit_cp, color=\"red\", linewidth=\"5\")
plt.legend([\'Actual Data\', \'Cubic Curve Fit\'])
plt.xlabel(\'Temperature[K]\')
plt.ylabel(\'Specific Heat(Cp)\')
plt.savefig(\'Cubic Curve Fit\')
plt.show()

#end

\"\"

\"Cubic

Explanation:

  • Started of with importing required libraries for the code i.e. matplotlib, numpy and curve_fit from Scipy module.
  • Defined the Linear order equation for the first part of the code.
  • Entered function read_file() which will read the file on which we need to work on.
  • Created an empty array for temperature and Cp(specific heat), using these values we will create the curve.
  • Using code for line in open (\'data\', \'r\'): we define the file name passed the command to read the content of the data.
  • By the line values = line.split(\',\') we commanded to divide the data where “,” is provided.
  • As the data given in string in order to convert to float thus Python can execute we used the command “float”, we added append command to add the data in empty arrays.
  • Using the “curve_fit” library and providing our linear order, temperature and Cp we can get the output,
  • Once we get the output as popt using the same as co-efficient we will derive the values of fit_cp, we passed the values of temperature in data as numpy array so that it can be executed.
  • Once done we plotted the outputs derived, naming the given data as Actual Data and derived output as Linear Curve Fir for this case.
  • Similarly for Cubic Polynomial curve we defined the function as cubic order equation and rest of the steps are same as above.

Below are answers of the questions regarding to Curve Fitting which are part of the challenge.

What is pop and pcov?

Here ‘popt’ gives optimized curve for the given function, it gives best-fit parameter. The ‘popt’ is the co-efficient of values of a, b, c, d. While ‘pcov’ is a 2d array, it contains true variance and covariance of the parameter, it shows the error. From ‘pcov’ we can determine standard deviation of the parameter.

What does np.array(temperature) do?

By passing the temperature as array we get all values of temperature from the data as numpy function which makes it viable as the operations cannot be done from.

What does the * in *popt mean?

The reason to provide ‘*popt’ is it unpacks ‘popt’ and thus we are able to pass multiple variables to a function. In our case second and third array i.e. a, b, c (d in case of cubic curve fit)

Whether the results are good or bad.

As we can see in the graph of linear function the curve is not accurate the actual data and curve do not match, thus we cannot say that it desired result. However, in cubic curve fit curve we can see that curves are lot similar, hence we can say that the second result as ‘GOOD’.

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

As the results suggests that as we use the bigger function the more accurate graph is obtained, hence In order to get more accurate result we need to use bigger however, this is not feasible every time thus we can use order accordingly to get the desired result,

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.