Challenge

Week 5 - Curve fitting

AIM: To write codes in Python to perform curve fitting.
OBJECTIVE : 
1.	To wite codes to fit a linear and cubic polynomial for the Cp data.
2.	To plot the linear and cubic fit curves along with the raw data points.
3.	To measure the fitness characteristics for both the curves.
4.	To solve with Splitwise method 
THEORY: 
 Curve fit is how we model or represent a distribution of data by assigning a best fit function (curve) to the entire range. Ideally, it will capture trends in the data and allow us to make predictions about how the data series will perform in the future.

Types of curve fitting include:
 Interpolation, where you discover a function that exactly matches the data points. Since it has no measurement error, its applicability to real-world situations is limited. Smoothing is when we find an approximate function that matches the data points, but we allow for error and allow our real points to be close, but not necessarily on the line; because errors are mitigated globally. Linear and polynomial curve fitting:

 (i) Linear curve adjustment, or linear regression, occurs when the data are adjusted for a straight line. Although there may be a curve in your data, a straight line provides a reasonable enough fit to make predictions.
Since the equation of a common line is always given by f(x) = a x + b, the question becomes: which a and b will give us the line that best fits our data?
Taking the vertical distance from each point to a potential line as an error, and adding them to our range, gives us a concrete number representing the distance between the potential line and the "best". ".
A line that provides minimal error can be considered as the best straight line. Since it's the distance between our points and the line we're interested in - whether positive or negative is irrelevant - we square the distance in our error calculations. It also allows us to weigh larger errors more heavily. This method is therefore called the least squares approach.
(ii) Polynomial curve fitting is fitting our data to the graph of a polynomial function. The same method of least squares can be used to find the polynomial with the minimum total error, to a certain extent. To choose the best fit for the curve, the following four parameters help us measure the fit of the fit criteria or how well the equations represent the given data points: 
The sum of squares due to error (SSE),
R-square (R2),
Adjusted R-squrae,
Root mean squared error (RMSE)
GOVERNING EQUATIONS USED :
Error = ∣y(i))−value of f(x)at x(i)∣ = |y(i)−f(x(i))|,
SSE (sum of squared error) = n∑i=1Error(i)2,
SSR (sum of square of regression) = n∑i=1(f(x(i))−Mean)2,
SST (sum of the squared total) = SSE+SSR ,
R2 ( R squared) = SSRSST,
RMSE (root mean squared error) = √SSEn,
          where n is the  total number of datapoints available. 

STEPS FOR A SOLUTION
1.To start, the relevant Python modules are imported, such as math, matplotlib, NumPy, and scipy.
2.There are two defined functions that produce linear and cubic equations.
3.By putting the following data in the appropriate directory, Python will load it, and a function called read file will be created. Each line is ran through a for loop using the 'open' command and the 'r' reading command.
4.Two distinct column matrices of temperature and specific heat are derived from the data obtained.
5.For curve fitting, the commands "curve fit" and "popt" are used as the output for storing the parameters derived from the needed function (linear or cubic), temperature, and Cp. A new variable called "fit cp" is now used to record the updated values of Cp determined by a temperature array. 
6.To determine the fitness features for the curves for both the linear and cubic polynomial, plots of both the original dataset and the predicted dataset are created and compared.
7.SSE, SSR, SST, R2, and RMSE are only a few of the measures that are calculated to assess the fitness qualities of both curves. A good fit is defined as the plot with the highest R2 or one that is closest to 1.
Q. Meaning of popt and pcov
Ans. The matrix known as "popt" stores and extracts the coefficients for the fitting functions in accordance with the established general equations.
popt: array, ideal parameter values to minimise the sum of the squared residuals of f(xdata, *popt) - ydata
The square matrix "pcov" stands for the estimated covariance values of the aforementioned coefficients. The variance of these coefficients is likewise represented by the diagonal components of this square matrix.
2D array, pcov
popt's estimated covariance. The parameter estimate's variance is provided by the diagonals. The sigma parameter's impact on the estimated covariance depends on the absolute sigma argument; if True, sigma is used in an absolute sense, and the estimated parameter covariance pcov reflects these absolute values. To calculate one standard deviation errors on the parameters, use perr = np.sqrt(np.diag(pcov)). Only the relative magnitudes of the sigma values matter if this is False. The parameter covariance matrix pcov that is returned is based on scaling sigma by a fixed amount. 

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 R2 will be close to 1 and is assumed to a perfect fit. 


Conclusion:
THEREFORE, WE CAN DETERMINE THAT R2 SHOULD BE CLOSE TO 1 TO ENSURE A GOOD CURVE FIT. The results show that the R2 for the linear curve fit is roughly 0.93, and the R2 for the cubic curve fit is almost 0.99. Therefore, cubic polynomials match the data better than linear polynomials. The value of R2 will nudge closer to 1 as the polynomial's rank rises, and a good fit will be presumed. 


# A program to measure fitness characteristics for the linear and cubic polynomial for the Cp data:
import math
import matplotlib.pyplot as plt
import numpy as np
from scipy.optimize import curve_fit

# Curve fit function
# Linear function
def function_1(t,a,b):
	return a*t + b 
# Cubic function	
def function_2(t,a,b,c,d):
	return a*pow(t,3) + b*pow(t,2) + c*t +d
	

# Reading thermodynamic data 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]

# Main Program
temperature , cp = read_file()

popt, pcov = curve_fit(function_1,temperature,cp)
fit_cp_l = function_1(np.array(temperature), *popt)
plt.figure(1)
plt.plot(temperature,cp,'k--')
plt.plot(temperature,fit_cp_l,color='red',linewidth = 1)
plt.legend(['Actual data','Curve fit'])
plt.xlabel('Temperature (K)')
plt.ylabel('Cp')
plt.title('Linear Curve fitting')
plt.show()

popt, pcov = curve_fit(function_2,temperature,cp)
fit_cp_c = function_2(np.array(temperature), *popt)
plt.figure(3)
plt.plot(temperature,cp,'k--')
plt.plot(temperature,fit_cp_c,color='red',linewidth = 1)
plt.legend(['Actual data','Curve fit'])
plt.xlabel('Temperature (K)')
plt.ylabel('Cp')
plt.title('Cubic Curve fitting')
plt.show()


''' 
Measuring the fitness characetristics of the curves 

 SSE (sum of error squared)
 SSR (sum of squares of the regression)
 SST = SSE + SSR
 R^2 = SSR/SST
 RMSE = (SSE/l)^0.5

 Finding mean of Cp data
 mean = ( sum of all elements)/(total number of elements)'''

s = np.sum(cp)
l = np.size(cp)
m = s/l
print('Mean of all cp :',m)
print('')
# For Linear curve fit

linear_sse = 0
linear_ssr = 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[i] - 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 curve fit
cubic_sse = 0
cubic_ssr = 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_c[i] - 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)

# splitwise method 
temperature , cp = read_file () 
X= 0
Y= 799 
fit_cp = [] 
for i in range(0,4):
	popt,pcov=curve_fit(function_1,temperature[X:Y+1],cp[X:Y+1])
	fit=function_1(np.array(temperature[X:Y+1]),*popt)
	X= Y+1 
	Y= Y+800
	for z in fit:

		fit_cp.append(z)



#plt.plot(temperature,cp,color='red',linewidth=3)
plt.plot(temperature,fit_cp,color='blue',linewidth=3)
plt.legend(['Actual data',curve_fit])
plt.xlabel('Temperature[K]')
plt.ylabel('CP')
plt.title ('LINEAR CURVE FITTING')
plt.show()
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.