Challenge

Week 5 - Curve fitting

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

Ans:- popt – An array of optimal values for the parameters which minimizes the sum of squares of residual.

pcov – 2D array which contains the estimated covariance of popt. The diagonals provide the variance of the parameter estimate.

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

Ans:- Converts the python list of temperature to a numpy array since operations like pow are allowed on numpy arrays and not python lists.

  1. What does the * in *popt mean?

Ans:- reference to popt – the values are stored in the array popt.

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

Ans:- In order to make perfect fit, we must consider error estimates as well. Perfect fit means Perfect fit can always be a best fit but best fit can not be a perfect fit.

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

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

def linfunc(t,a,b,c):
	return a*t+b

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


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

def fifthfunc(t,a,b,c,d,e,f):
	return a*pow(t,5)+b*pow(t,4)+c*pow(t,3)+d*pow(t,2) +e*t+f


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]

temperature,cp = read_file()

popt,pcov =  curve_fit(linfunc,temperature,cp) #popt -optimum parameters are returned which then can be passed into the function
fit_cp_linear = linfunc(np.array(temperature),*popt)


popt1,pcov1 =  curve_fit(cubicfunc,temperature,cp) 
fit_cp_cubic = cubicfunc(np.array(temperature),*popt1)

popt2,pcov2 =  curve_fit(fourthfunc,temperature,cp) 
fit_cp_fourth = fourthfunc(np.array(temperature),*popt2)


popt3,pcov3 =  curve_fit(fifthfunc,temperature,cp) 
fit_cp_fifth = fifthfunc(np.array(temperature),*popt3)


plt.figure(1)
plt.plot(temperature,cp,linewidth =3 ,color='red')
plt.plot(temperature,fit_cp_linear,linewidth=3, color ='blue')
plt.plot(temperature,fit_cp_cubic,linewidth=3, color ='green')
plt.plot(temperature,fit_cp_fourth,linewidth=3, color ='yellow')
plt.plot(temperature,fit_cp_fifth,linewidth=3, color ='orange')
plt.xlabel('Temperature in K')
plt.ylabel('Specific heat')
plt.legend(['actual fit','quadratic fit','cubic fit','fourth order' ,'fifth order'])
plt.grid()
plt.savefig('quadratic_fit')
plt.show()


plt.figure(2)
plt.plot(temperature,cp,linewidth =3 ,color='red')
plt.plot(temperature,fit_cp_linear,linewidth=3, color ='blue')
plt.xlabel('Temperature in K')
plt.ylabel('Specific heat')
plt.legend(['actual fit','linear fit'])
plt.grid()
plt.savefig('linear fit')
plt.show()


plt.figure(3)
plt.plot(temperature,cp,linewidth =3 ,color='red')
plt.plot(temperature,fit_cp_cubic,linewidth=3, color ='green')
plt.xlabel('Temperature in K')
plt.ylabel('Specific heat')
plt.legend(['actual fit','cubic fit'])
plt.grid()
plt.savefig('cubic_fit')
plt.show()
#Calculation of residuals  r =data -fit
r1 = cp - linfunc(np.array(temperature),*popt)
r2 = cp - cubicfunc(np.array(temperature),*popt1)
r3 = cp - fourthfunc(np.array(temperature),*popt2)
r4 = cp - fifthfunc(np.array(temperature),*popt3)

print('Residual1=',r1)
print('Residual2=',r2)
print('Residual3=',r3)
print('Residual4=',r4)

#Standard deviation error of the co-efficients
per1 = np.sqrt(np.diag(pcov))
per2 = np.sqrt(np.diag(pcov1))
per3 = np.sqrt(np.diag(pcov2))
per4 = np.sqrt(np.diag(pcov3))

print('per1 =' , per1)
print('per2 =' , per2)
print('per3 =' , per3)
print('per4 =' , per4)


#CODE FOR BEST CURVE FIT - SPLIT DATA

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

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

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

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


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

def fifthfunc(t,a,b,c,d,e,f):
	return a*pow(t,5)+b*pow(t,4)+c*pow(t,3)+d*pow(t,2) +e*t+f


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]

temperature,cp = read_file()
t1= np.array(temperature[0:650])
t2= np.array(temperature[650:800])
t3= np.array(temperature[800:1200])
t4= np.array(temperature[1200:1800])

popt,pcov =  curve_fit(quadfunc,t1,cp[0:650])
popt1,pcov1 =  curve_fit(cubicfunc,t2,cp[650:800]) 
popt2,pcov2 =  curve_fit(fourthfunc,t3,cp[800:1200]) 
popt3,pcov3 =  curve_fit(fifthfunc,t4,cp[1200:1800])  #popt -optimum parameters are returned which then can be passed into the function
fit_cp_quad = quadfunc(np.array(t1),*popt)
fit_cp_cubic = cubicfunc(np.array(t2),*popt1)
fit_cp_fourth = fourthfunc(np.array(t3),*popt2)
fit_cp_fifth = fifthfunc(np.array(t4),*popt3)


plt.figure(1)
plt.plot(temperature,cp,linewidth =3 ,color='red')
plt.plot(t1,fit_cp_quad,linewidth=3, color ='blue')
plt.plot(t2,fit_cp_cubic,linewidth=3, color ='green')
plt.plot(t3,fit_cp_fourth,linewidth=3, color ='yellow')
plt.plot(t4,fit_cp_fifth,linewidth=3, color ='orange')
plt.xlabel('Temperature in K')
plt.ylabel('Specific heat')
plt.legend(['actual fit','quadratic fit','cubic fit','fourth order' ,'fifth order'])
plt.grid()
plt.savefig('quadratic_fit')
plt.show()

#Calculation of residuals  r =data -fit
r1 = cp[0:650] - quadfunc(np.array(t1),*popt)
r2 = cp[650:800] - cubicfunc(np.array(t2),*popt1)
r3 = cp[800:1200] - fourthfunc(np.array(t4),*popt2)
r4 = cp[1200:1800] - fifthfunc(np.array(t4),*popt3)

print('Residual1=',r1)
print('Residual2=',r2)
print('Residual3=',r3)
print('Residual4=',r4)

#Standard deviation error of the co-efficients
per1 = np.sqrt(np.diag(pcov))
per2 = np.sqrt(np.diag(pcov1))
per3 = np.sqrt(np.diag(pcov2))
per4 = np.sqrt(np.diag(pcov3))

print('per1 =' , per1)
print('per2 =' , per2)
print('per3 =' , per3)
print('per4 =' , per4)

result/ output:-

C:\Users\HP\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.7_qbz5n2kfra8p0\LocalCache\local-packages\Python37\site-packages\scipy\optimize\minpack.py:834: OptimizeWarning: Covariance of the parameters could not be estimated
  category=OptimizeWarning)
Residual1= [-84.4621098  -84.38769354 -84.311751   ... -32.46657186 -32.52291584
 -32.57934008]
Residual2= [ -2.9813747   -3.11824598  -3.25334915 ... -13.28230303 -13.36108928
 -13.44007959]
Residual3= [12.26811503 12.03590466 11.80573068 ...  1.77677714  1.79306169
  1.80941048]
Residual4= [13.21450521 12.97341965 12.73440935 ...  0.84809835  0.85554656
  0.86302017]
per1 = [inf inf inf]
per2 = [1.55039520e-10 8.92402787e-07 1.52083070e-03 7.35289822e-01]
per3 = [6.59005116e-14 5.03523738e-10 1.31802827e-06 1.36103269e-03
 4.50309370e-01]
per4 = [8.09960502e-17 7.72011624e-13 2.73762968e-09 4.43388622e-06
 3.20104784e-03 7.99310794e-01]
Traceback (most recent call last):
  File "E:\Desktop\python course\New folder\week5.py", line 171, in <module>
    r3 = cp[800:1200] - fourthfunc(np.array(t4),*popt2)
ValueError: operands could not be broadcast together with shapes (400,) (600,) 
[Finished in 95.4s]
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.