All Courses
All Courses
Courses by Software
Courses by Semester
Courses by Domain
Tool-focused Courses
Machine learning
POPULAR COURSES
Success Stories
AIM: CURVE FITTING USING PYTHON OBJECTIVE: Linear and cubic polynomial curve fitting to a set of data points. Plotting predicted curves against raw data points. Studding parameters that measure the goodness of a fit. THEORY: Curve fitting is the process of constructing a curve or mathematical function,…
NAVEEN SWAMI
updated on 22 May 2020
AIM: CURVE FITTING USING PYTHON
OBJECTIVE:
THEORY:
Curve fitting is the process of constructing a curve or mathematical function, that has the best fit to a series of data points. Fitted curves can be used as an aid for data visualization, to infer values of a function where no data are available, and to summarize the relationships among two or more variables. By curve fitting, we can capture the trend in the data and make predictions of how the data series will behave in the future.
Types of curve fitting include:
Linear and Polynomial Curve Fitting:
Linear curve fitting, or linear regression, is when the data is fit to a straight line. A straight line provides a reasonable enough fit to make predictions.
Since the equation of a generic straight line is always given by,
f(x)= a x + b, equation for linear curve fitting
The goal is to identify the coefficients ‘a’ and ‘b’ such that f(x) ‘fits’ the data well.
How to find coefficients for best fit?
Considering the vertical distance from each point to a prospective line as an error, and summing them up over our range, gives us a concrete number that expresses how far from ‘best’ the prospective line is. A line that provides a minimum error can be considered the best straight line.
Since it’s the distance from our points to the line we’re interested in—whether it is positive or negative distance is not relevant—we square the distance in our error calculations. This also allows us to weight greater errors more heavily. So this method is called the least-squares approach.
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.
GOODNESS OF FIT:
There are four quantities that help us measure the goodness of fit or how well the predicted curve is representing the raw data points:
Assume data points (x1,y1),(x2,y2)………(xn,yn) and assume curve fit for these data points to be y=f(x),
when we differentiate the SSE with each and every coefficient of f(x) and equate to zero, we find the values of coefficients
This method is known as LEAST SQUARE METHOD.
R-square is the square of the correlation between the response values and the predicted values.
Adjusted R-square is a normalizing variation of R-square which neglects the variation of R-square due to insignificant independent variable.
n = no. of data points
PROGRAM:
import numpy as np
import matplotlib.pyplot as plt
import math
from scipy.optimize import curve_fit
def func_linear(t,a,b):
return a*t + b
def func_cubic(t,a,b,c,d):
return a*pow(t,3) + b*pow(t,2) + c*t + d
#reading data file
def read_file():
temp=[]
cp=[]
for line in open('data','r'):
line=line.split(',')
t=float(line[0])
temp.append(t)
s=float(line[1])
cp.append(s)
return [temp,cp]
#CURVE FITTING Linear
[temp,cp]=read_file()
popt, pcov = curve_fit(func_linear,temp,cp)
fit_cp= func_linear(np.array(temp),*popt)
#calculating goodness of linear fit
#SSE
sse=0
for i in range(0,np.size(cp)):
sse=sse + pow(cp[i]-fit_cp[i],2)
print('FOR LINEAR CURVE FITTING')
print('SSE:', sse)
#R_sqaure
mean=np.sum(cp)/np.size(cp)
ssr=0
for i in range(0,np.size(cp)):
ssr= ssr + pow(fit_cp[i] - mean,2)
sst=ssr+sse
R_sqaure=ssr/sst
print('R_sqaure:',R_sqaure)
#RMSE
rmse=pow(sse/np.size(cp),0.5)
print('RMSE:', rmse)
#plotting linear curve fit
plt.figure(1)
plt.plot(temp,cp,label= 'orginal data')
plt.plot(temp,fit_cp,label='linear curve fit')
plt.legend()
plt.xlabel('Temperature (K)')
plt.ylabel('Specific Heat (KJ/K)')
plt.title('Linear Curve Fitting')
plt.grid()
plt.savefig('linear curve fitting')
plt.show()
#cubic curve fitting
popt, pcov = curve_fit(func_cubic,temp,cp)
fit_cp= func_cubic(np.array(temp),*popt)
#calculating goodness of cubic fit
#SSE
sse=0
for i in range(0,np.size(cp)):
sse=sse + pow(cp[i]-fit_cp[i],2)
print(' ')
print('FOR CUBIC CURVE FITTING')
print('SSE:', sse)
#R_sqaure
mean=np.sum(cp)/np.size(cp)
ssr=0
for i in range(0,np.size(cp)):
ssr= ssr + pow(fit_cp[i] - mean,2)
sst=ssr+sse
R_sqaure=ssr/sst
print('R_sqaure:',R_sqaure)
#RMSE
rmse=pow(sse/np.size(cp),0.5)
print('RMSE:', rmse)
#plotting cubic curve fit
plt.figure(2)
plt.plot(temp,cp,label='orginal data')
plt.plot(temp,fit_cp,label='cubic curve fit')
plt.legend()
plt.xlabel('Temperature (K)')
plt.ylabel('Specific Heat (KJ/K)')
plt.title('Cubic Curve Fitting')
plt.grid()
plt.savefig('cubic curve fitting')
plt.show()
STEPS:
ERRORS: No error encountered
OUTPUT:
Command window output:
ANSWERS:
1. What does popt and pcov mean?
popt gives an array which contains the coefficients of the fitting function. These coefficients are optimized by minimizing the Sum of Squared Errors.
pcov: gives 2d array
It is 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))
.
2. What does np.array(temperature) do?
This command converts the temperature values into an array and stores them into it.
3. What does the * in *popt mean?
* refers to each element of popt array. It gives us all the elements which are stored in popt.
4. Write code to fit a linear and cubic polynomial for the Cp data. Explain if your results are good or bad.
We can compare the value of R-square in linear and cubic curve fitting. R-square value of Cubic fitting is closer to 1. but still there is some error in both curve fitting i.e. the fit in both linear and cubic fit is not perfect.
5. What needs to be done in order to make the curve fit perfect?
By minimizing the SSE we can make a curve to perfectly fit data points. With a high degree of the polynomial we get less value off SSE and more value of R-square(closer to 1), this results in high accuracy of curve fitting.
Also to perfectly fit cubic polynomial in data points, we can split the data points and perform cubic curve fitting in two separate regions. this will give us more accuracy in curve fitting.
REFERENCE:
https://projects.skill-lync.com/projects/Curve-Fitting-and-criterion-to-choose-best-fit-41860
https://www.iiserpune.ac.in/~bhasbapat/phy221_files/curvefitting.pdf
https://en.wikipedia.org/wiki/Curve_fitting
Leave a comment
Thanks for choosing to leave a comment. Please keep in mind that all the comments are moderated as per our comment policy, and your email will not be published for privacy reasons. Please leave a personal & meaningful conversation.
Other comments...
MBD Simulation on IC Engine Valve Train
AIM: MOTION ANALYSIS OF IC ENGINE VALVE TRAIN MECHANISM THEORY: Valve Train is a mechanical system in an IC engine that is responsible for controlling the intake and the exhaust of the combustion process. During the intake process, the intake valve opens to let air enter the combustion chamber and during the exhaust process,…
21 Jun 2020 08:00 AM IST
MOTION ANALYSIS OF IC ENGINE PISTON ASSEMBLY MECHANISM
AIM: MOTION ANALYSIS OF IC ENGINE PISTON ASSEMBLY MECHANISM. THEORY: In IC Engine, the combustion is driven by Slider Crank Mechanism. Inside the cylinder, the piston performs reciprocating motion which results in compression and expansion of gas inside the cylinder. This motion of the piston is guided by the Slider Crank…
18 Jun 2020 06:12 AM IST
MOTION ANALYSIS OF PLANETARY GEAR SYSTEM
AIM: MOTION ANALYSIS OF PLANETARY GEAR SYSTEM THEORY: A planetary gear mechanism also is known as Epicyclic Gear Train, is a gear mechanism consisting of 4 components, namely, sun gear A, several planet gears B, internal gear(ring gear) C and carrier D that connects planet gears as seen in the image below. It has a very…
11 Jun 2020 11:28 AM IST
MULTI-BODY DYNAMICS SIMULATION OF INTERNAL GENEVA MECHANISM IN SOLIDWORKS
AIM: MULTI-BODY DYNAMICS SIMULATION OF INTERNAL GENEVA MECHANISM IN SOLIDWORKS. THEORY: Geneva mechanism is the mechanism through which continuous rotation motion is converted into intermittent rotation motion. In this, the driver wheel rotates continuously and the driven wheel has rotation in regular intervals not continuously.…
02 Jun 2020 09:49 AM IST
Related Courses
Skill-Lync offers industry relevant advanced engineering courses for engineering students by partnering with industry experts.
© 2025 Skill-Lync Inc. All Rights Reserved.