Challenge

Week 5 - Curve fitting

AIM: To write a code to fit a linear and cubic polynomial for the Cp data and to Plot the linear and cubic fit curves along with the raw data points

THEORY: Curve fits are very useful as they help to describe how the data changes Mathematically. We can perform additional Mathematical operation which might not be possible in the initial data set.

Curve fitting is the process of constructing a curve, or Mathematical function that has the best fit to a series of data points possibly subject to constraints. It is highly effective in Mathematical modeling of some natural processes.

The first degree polynomial equation(linear) is a line with slope 'a'. A line will connect any two points, so a first degree polynomial equation is an exact fit through any two points with distinct x coordinates.

The second degree polynomial equation(quadratic) This will exactly fit a simple curve to three points.

The third degree polynomial equation(Cubic) This will exactly fit the curve to four points.

General approaches followed for curve fitting

1] Least square regression: Data exhibit the significant degree of scatter. The main aim is to derive the curve that represent the general trend of data.

2] Interpolation: The main aim is to pass the curve or a series of curve through each of the points. The data is very precise.

The goodness of the fit can be evaluated by Statistical parameters as mentioned below

1) Sum of squares due to error(SSE) 2) R-square 3) Adjusted R-square 4) Root mean Squared error

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

popt gives the values of coefficients a,b,c in the equation, It stores the values of coefficients in the form of an array.

pcov means its a covariance matrix. It has the estimated values of the covariance parameters of popt, which is used to find the deviation parameters from the mean value.

2]. What does np.array(temperature) do?

The function np.array is used to perform Mathematical and logical operations to each values in the array.

3]. What does the * in *popt mean?

The * in the *popt is used to unpack all the values in popt in order to pass multiple variables in to function

4]. Write code to fit a linear and cubic polynomial for the Cp data. Explain if your results are good or bad.

a)Linear polynomial Fit

# Python program to fit linear polynomial 
import numpy as np 
import matplotlib.pyplot as plt 
from scipy.optimize import curve_fit

# curve fit function 

def linear(t ,a ,b):
	return a*t + b

# 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_1, pcov_1 = curve_fit(linear, temperature, cp)
fit_cp_1 = linear(np.array(temperature), *popt_1)

plt.plot(temperature, cp,color = "blue", linewidth = 3)
plt.plot(temperature, fit_cp_1,color ="red", linewidth = 3 )
plt.legend(['Actual data','Curve fit'])
plt.xlabel('temperature [K]')
plt.ylabel('cp')
plt.title("Curve fit for linear polynomial")
plt.grid()
plt.show()

b)Cubic Polynomial fit

# Python program to fit cubic polynomial 
import numpy as np 
import matplotlib.pyplot as plt 
from scipy.optimize import curve_fit

# curve fit function 

def cubic(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_1, pcov_1 = curve_fit(cubic, temperature, cp)
fit_cp_1 = cubic(np.array(temperature), *popt_1)

plt.plot(temperature, cp,color = "blue", linewidth = 3)
plt.plot(temperature, fit_cp_1,color ="red", linewidth = 3 )
plt.legend(['Actual data','Curve fit'])
plt.xlabel('temperature [K]')
plt.ylabel('cp')
plt.title("Curve fit for cubic polynomial")
plt.grid()
plt.show()

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

The curve can be made to fit perfectly by following ways

a] By increasing the order of polynomial.

b] By using cross validation techniques where data is fit in to n folds. The stepwise fold is used to validate the model then choose a lower error.

c] By increasing the centre and scaling the curve.

1] For obtaining the best fit of the curve it should have least sum of square of numbers various methods are there to reduce the error

In the case of R square method if R^2 is greater than 0.95, the curve is said to be best fit that is R^2>0.95 for best fit.

2] The cubic fit can be improved in following ways

a] By using the split wise method to solve the curve

b] By increasing the order of Polynomial or normalizing the given polynomial.

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.