Challenge

Week 5 - Curve fitting

AIM:

To write codes in python to perform curve fitting.

OBJECTIVE:

  1. To write codes to fit a linear and cubic polynomial for the Cp data.
  2. To plot the linear and cubic fit curve along with the raw data points.
  3. Tp measure the fitness characteristics for both the curves

THEORY:

Curve fitting is the way we model or represent data by assigning the best fit function(curve) along with the entire range. ideally, it will capture the trend in the data series that will behave in the future.

Type of curve fitting including:

  • Interpolation, Where you discover a function that is exact to the data points. Since this assumes no measurement error, it has limited application to real-life scenarios.
  • Smoothing is when we find a function that is an approximate fit to the data points, but we give room for error and we allow our actual points to be near, but not necessarily on the line; given the error is minimized overall.

Linear and Polynomial Curve fitting

* Linear curve fitting, or linear regression, is when the data is fit to a straight line. Although there might be some curve to your data, a sr=tring line provides a reasonable enough fit to make predictions.

* Polynomial curve fitting is when we fit our data to the graph of a polynomial function. the same least-squares method can be used to find the polynomial, of a given degree, that has a minimum total error.

OLUTION STEPS :
1. At first, necessary modules such as math,matplotlib,Numpy,scipy are imported to perform their respective functions.
2. Two functions are defined which return linear and cubic equations.
3. The following data is loaded into Python by placing it in the right directory and a function read_file is created. For loop is used to run each line by using 'open' command with 'r' to read it.
4. From the data obtained, two individual column matrices of temperature and specific heat are derived.
5. For curve fitting, 'popt' and 'pcov' are used as output fostoring parameters obtained by 'curve_fit' command which takes input as the required function(linear or cubic) , temperature, and Cp. Now, another variable named 'fit_cp' stores the new values of Cp calculated by using temperature array.
6. Plots of both raw dataset and predicted dataset are made and compared to find fitness characteristics for both the curves for both linear and cubic polynomial.

PYTHON CODE :

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

# curve fit funtion
# linear funtion
def function_0(t,a,b):
return a*t + t

# cubic funtion
def function_1(t,a,b,c,d):
return a*pow(t,3) + b*pow(t,2) + c*t + d

# reading thermodinamic data files
def read_file():
tempreature = []
cp = []
for line in open('data','r'):
value = line.split(',')
tempreature.append(float(value[0]))
cp.append(float(value[1]))
return [tempreature,cp]

# main program
#linear curve fitting
tempreature,cp = read_file()

popt,pcov = curve_fit(function_0,tempreature,cp)
fit_cp_l = function_0(np.array(tempreature),*popt)
plt.figure(1)
plt.plot(tempreature,cp,'k--')
plt.plot(tempreature,fit_cp_l,color='red',linewidth=1)
plt.legend(['Actual data','curve fit'])
plt.xlabel('tempreature(k)')
plt.ylabel('cp')
plt.title('linear curve fitting')
plt.show()

#cubic curve fitting
popt,pcov = curve_fit(function_1,tempreature,cp)
fit_cp_c = function_1(np.array(tempreature),*popt)
plt.figure(2)
plt.plot(tempreature,cp,'k--')
plt.plot(tempreature,fit_cp_c,color='red',linewidth=1)
plt.legend(['Actual data','curve fit'])
plt.xlabel('tempreature(k)')
plt.ylabel('cp')
plt.title('cubic curve fitting')
plt.show()
"""
messure the fitness chareacteristics of the curves

SSE (Sum of error squared)
SSR (Sum of erroe squaired)
SST (sum of the squared total)
RMSE (Root mean squired error)

SST = SSR/SST
RMSE = (SSE/1)^0.5

Find mean of cp data
mean = (sum of all elements)/(total number of element)
"""
s = np.sum(cp)
l = np.size(cp)
m = s/l
print('mean of all cp:',m)
print('')

# For Linear curve fit
linear_ssr =0
linear_sse =0
for i in range(l):
linear_error = abs((np.sum((cp[i] - fit_cp_l[i]))))
linear_sse = linear_sse + pow(linear_error,2)
linear_ssr = linear_ssr + np.sum(pow((fit_cp_l[1] - m),2))
linear_sst = linear_sse + linear_ssr
print('linear_sst:',linear_sst)
linear_R2 = linear_ssr/linear_sst
print('linear_R2:',linear_R2)
linear_rmse = pow((linear_sse/l),0.5)
print('linear_RMSE:',linear_rmse)
print('')

# For cubic fit
cubic_ssr =0
cubic_sse =0
for j in range(l):
cubic_error = abs((np.sum((cp[i] - fit_cp_c[i]))))
cubic_sse = cubic_sse + pow(cubic_error,2)
cubic_ssr = cubic_ssr + np.sum(pow((fit_cp_l[1] - m),2))
cubic_sst = cubic_sse + cubic_ssr
print('cubic_sst:',cubic_sst)
cubic_R2 = cubic_ssr/cubic_sst
print('cubic_R2:',cubic_R2)
cubic_rmse = pow((cubic_sse/l),0.5)
print('cubic_RMSE:',cubic_rmse)
print('')

RESULTS :


The following are the output of the above program-

For Linear Curve fitting the plot obtained is-

For Cubic Curve fitting the plot obtained is-

Q. What do popt and pcov mean?
Ans. 'popt' represents the matrix that stores and extracts the coefficients for the fitting functions according to the general equations defined.

popt : array, Optimal values for the parameters so that the sum of the squared residuals of f(xdata, *popt) - ydata is minimized 'pcov' represents the square matrix which stores the estimated values of covariance of the coefficients of the above. The diagonal elements of this square matrix also represent the variance of these coefficients

pcov : 2d array
The estimated covariance of popt. The diagonals provide the variance of the parameter estimate. To compute one standard deviation errors on the parameters use perr = np.sqrt(np.diag(pcov)).How the sigma parameter affects the estimated covariance depends on absolute_sigma argument, as if True, sigma is used in an absolute sense and the estimated parameter covariance pcov reflects these absolute values. If False, only the relative magnitudes of the sigma values matter. The returned parameter covariance matrix pcov is based on scaling sigma by a constant factor.

Q. What does np.array(temperature) do?
Ans This command converts each value of temperature in the data file into an array using the NumPy module.
Q. What does the * in *popt mean?
Ans '*' , '*popt' indicates and returns each coefficient stored in popt array.
Q. What needs to be done in order to make the curve fit perfectly?
Ans If we increase the order of the polynomial, the error produced will be less and curve fit perfectly. On increasing the order of the polynomial the value of will be close to 1 and is assumed to a perfect fit.

https://drive.google.com/drive/folders/18RaGQvnEt7i11iFeBRn9_n--spe4hIaU?usp=sharing

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.