Project

Curve fit using Python

CURVE FITIING

Objective: In this challenge, we will be writing codes to perform curve fitting.

Introduction: Curve fitting is one of the most powerful and most widely used analysis tools in Origin. Curve fitting examines the relationship between one or more predictors (independent variables) and a response variable (dependent variable), with the goal of defining a \"best fit\" model of the relationship.

1.Popt is an array of Optimal values for the parameters so that the sum of the squared residuals can be minimized.

pcov is an array That has estimated covariance of popt. The diagonals provide the variance of the parameter estimate.

Covariance is a measure of how changes in one variable are associated with changes in a second variable. Specifically, covariance measures the degree to which two variables are linearly associated.

2. np.array(temperature): A numpy array is a grid of values, all of the same type, and is indexed by a record of nonnegative integers. The number of dimensions is the rank of the array; the shape of an array is a record of integers giving the size of the array along each dimension. It turns the list of the temperature values into an array and will have indices for each value which would help in direct access of the value of temperature without doing any sequential operation as in list.

3. * in *popt means that reference commond or operator or symbol to the coefficients present in the popt. eg: values of a,b,c

4. Code to fit a linear and cubic polynomial for the Cp data.

Basic module that are requried for the curve fit are to be imported. they are numpy, matplotlib.pyplot, statistics, math, from scipy.optimize import curve_fit.

A data file is provided which contains list of values of temperature and specific heat.

def read_file(): Inorder to import the values from the data file we have to create a function that can read values in the data file and assign them accordingly.

def func(t,a,b): This is the curve fitting fuction which takes temperature values as input and get the values for the co-efficients such as a,b,c.

popt, pcov = curve_fit(func,temperature,cp): popt and pcov has the values of coefficients and there respective covariences. curve_fit has three inputs which has functionthat defines the degree of details, independent variable \'temperature\' and dependent variable\'cp\'.

fit_cp = func(np.array(temperature),*popt): cp values placed in the y-coordinate. curve fit changes cp values of the y coordinate with an error to form a curve.

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

n = 3200 # no of values in data set
# reading thermodynamic file
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]

# linear curve fit function.
def func(t,a,b):
	return a*t+b

#main program
temperature, cp = read_file()
popt, pcov = curve_fit(func,temperature,cp)
fit_cp = func(np.array(temperature),*popt)
print(temperature)
print(np.array(temperature))
plt.figure(1)
plt.plot(temperature,cp,color = \"blue\",linewidth = 3)
plt.plot(temperature,fit_cp,color = \"red\",linewidth = 3)
plt.legend([\'Actual data\', \'curve_fit\'])
plt.xlabel(\'temperature[k]\')
plt.ylabel(\'cp\')
plt.show()

mean_cp = statistics.mean(cp)
error_1 = cp-fit_cp
sse_1 = sum(error_1**2)
x1 = [cp - mean_cp for cp in cp]
y1 = np.square(x1)
ssr_1 = sum(y1)
sst_1 = sse_1+ssr_1
rsquare_1 = ssr_1/sst_1
rms_1 = math.sqrt(sse_1/n)

print(\" The rsquare value of quadratic fit it\", rsquare_1)
print(\"The RMS value is quadratic fit is\",rms_1)

# Quadratic curve fit function.
def func(t,a,b,c):
	return a*pow(t,2)+b*t+c
# Cubic curve fit function.
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)

plt.figure(2)
plt.plot(temperature,cp,color = \"blue\",linewidth = 3)
plt.plot(temperature,fit_cp,color = \"red\",linewidth = 3)
plt.legend([\'Actual data\', \'curve_fit\'])
plt.xlabel(\'temperature[k]\')
plt.ylabel(\'cp\')
plt.show()

mean_cp = statistics.mean(cp)
error_2 = cp-fit_cp
sse_2 = sum(error_2**2)
x2 = [cp - mean_cp for cp in cp]
y2 = np.square(x2)
ssr_2 = sum(y2)
sst_2 = sse_2+ssr_2
rsquare_2 = ssr_2/sst_2
rms_2 = math.sqrt(sse_2/n)

print(\" The rsquare value of quadratic fit it\", rsquare_2)
print(\"The RMS value is quadratic fit is\",rms_2)

# Cubic curve fit function.
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)

plt.figure(3)
plt.plot(temperature,cp,color = \"blue\",linewidth = 3)
plt.plot(temperature,fit_cp,color = \"red\",linewidth = 3)
plt.legend([\'Actual data\', \'curve_fit\'])
plt.xlabel(\'temperature[k]\')
plt.ylabel(\'cp\')
plt.show()

mean_cp = statistics.mean(cp)
error_3 = cp-fit_cp
sse_3 = sum(error_3**2)
x3 = [cp - mean_cp for cp in cp]
y3 = np.square(x2)
ssr_3 = sum(y2)
sst_3 = sse_3+ssr_3
rsquare_3 = ssr_3/sst_3
rms_3 = math.sqrt(sse_3/n)

print(\" The rsquare value of quadratic fit it\", rsquare_3)
print(\"The RMS value is quadratic fit is\",rms_3)


# 4th order curve fit function.
def func(t,a,b,c,d,e):
	return a*pow(t,4)+b*pow(t,3)+c*pow(t,2)+d*t+e

#main program
temperature, cp = read_file()
popt, pcov = curve_fit(func,temperature,cp)
fit_cp = func(np.array(temperature),*popt)

plt.figure(4)
plt.plot(temperature,cp,color = \"blue\",linewidth = 3)
plt.plot(temperature,fit_cp,color = \"red\",linewidth = 3)
plt.legend([\'Actual data\', \'curve_fit\'])
plt.xlabel(\'temperature[k]\')
plt.ylabel(\'cp\')
plt.show()

mean_cp = statistics.mean(cp)
error_4 = cp-fit_cp
sse_4 = sum(error_4**2)
x4 = [cp - mean_cp for cp in cp]
y4 = np.square(x4)
ssr_4 = sum(y4)
sst_4 = sse_4+ssr_4
rsquare_4 = ssr_4/sst_4
rms_4 = math.sqrt(sse_4/n)

print(\" The rsquare value of quadratic fit it\", rsquare_4)
print(\"The RMS value is quadratic fit is\",rms_4)

Sum of Squares Error. SSE is the sum of the squared differences between each observation and its group\'s mean. It can be used as a measure of variation within a cluster. If all cases within a cluster are identical the SSE would then be equal to 0.

SSR means sum of squares due to regression which is basically the square of the difference between the value of the fitting function at a given and the value of the arithamatic mean of the data set.

SST means tota sum of the squares is a quantity that appears as part of a standard way of presenting results of such analyses. It is defined as being the sum, over all observations, of the squared differences between the observations and their overall mean.

R-squared (R2) is a statistical measure that represents the proportion of the variance for a dependent variable that\'s explained by an independent variable or variables in a regression model.

Root Mean Square Error (RMSE) is the standard deviation of the residuals (prediction errors). Residuals are a measure of how far from the regression line data points are; RMSE is a measure of how spread out these residuals are. In other words, it tells you how concentrated the data is around the line of best fit.

This is the plot of linear curve fit function. It can be observed that the error values is a bit higher because of the degree of the curve fit function.

\"\"

Plot of quadratic curve fit function. curve seems to be better than that of the linear function curve as the degree increased.

\"\"

Plot of cubic curve fit function. curve is almost representing the actual data but still there is an error.

\"\"

This plot represents the 4th order curve fit function which has very less error compared to other functions and the curve has almost perfect alinment with the actual data.

\"\"

5. In order to make the curve fit perfect we have to increase the degree of the function which will decrease the error vaiue between the actual data and curve fit data.

\"\"

From the above picture, we can understand that as the degree of the function increases the rsquare value increased and RMS value decreased which means the accuracy has increased and error has decreased.

Conclusion:

  • curve fit perfection increase with the degree of the function which will decrease the error vaiue between the actual data and curve fit data.

  • Eventhought error value decreases with the degree of function, one need to consider the computational time as well for the optimum performance.
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.