SciPy - Curve Fitting - GeeksforGeeks

Download as pdf or txt
Download as pdf or txt
You are on page 1of 11

8/18/23, 3:31 AM SciPy | Curve Fitting - GeeksforGeeks

Inicia sesión en GeeksforGeeks con


Google

SciPy | Curve Fitting Julio José Balbín Arias


balbin.julio@pucp.edu.pe

A ArijitGayen julio jose balbin arias


dylantrat@gmail.com

Read Discuss Courses Practice


4 cuentas más

Given a Dataset comprising of a group of points, find the best fit representing the Data.
We often have a dataset comprising of data following a general path, but each data has a
standard deviation which makes them scattered across the line of best fit. We can get a
single line using curve-fit() function.
Using SciPy :
Scipy is the scientific computing module of Python providing in-built functions on a lot of
well-known Mathematical functions. The scipy.optimize package equips us with multiple
optimization procedures. A detailed list of all functionalities of Optimize can be found on
typing the following in the iPython console:

help(scipy.optimize)

Among the most used are Least-Square minimization, curve-fitting, minimization of


multivariate scalar functions etc.
Curve Fitting Examples –
Input :

We use cookies to ensure you have the best browsing experience on our website. By using our site,
Got It !
you acknowledge that you have read and understood our Cookie Policy & Privacy Policy

https://www.geeksforgeeks.org/scipy-curve-fitting/ 1/11
8/18/23, 3:31 AM SciPy | Curve Fitting - GeeksforGeeks

Output :

We use cookies to ensure you have the best browsing experience on our website. By using our site,
you acknowledge that you have read and understood our Cookie Policy & Privacy Policy

https://www.geeksforgeeks.org/scipy-curve-fitting/ 2/11
8/18/23, 3:31 AM SciPy | Curve Fitting - GeeksforGeeks

Input :

ICR: Where practical meets possible.

Output :

We use cookies to ensure you have the best browsing experience on our website. By using our site,
you acknowledge that you have read and understood our Cookie Policy & Privacy Policy

https://www.geeksforgeeks.org/scipy-curve-fitting/ 3/11
8/18/23, 3:31 AM SciPy | Curve Fitting - GeeksforGeeks

As seen in the input, the Dataset seems to be scattered across a sine function in the first
case and an exponential function in the second case, Curve-Fit gives legitimacy to the
functions and determines the coefficients to provide the line of best fit.

Code showing the generation of the first example –

Python3

import numpy as np
Trending Now Data Structures Algorithms Topic-wise Practice Python Machine Learning Data Science J
# curve-fit() function imported from scipy
from scipy.optimize import curve_fit

from matplotlib import pyplot as plt

# numpy.linspace with the given arguments


# produce an array of 40 numbers between 0
# and 10, both inclusive
x = np.linspace(0, 10, num = 40)

# y is another array which stores 3.45 times


# the sine of (values in x) * 1.334.
# The random.normal() draws random sample
# from normal (Gaussian) distribution to make
# them scatter across the base line
y = 3.45 * np.sin(1.334 * x) + np.random.normal(size = 40)

# Test function with coefficients as parameters


def test(x, a, b):
return a * np.sin(b * x)

# curve_fit() function takes the test-function


# x-data and y-data as argument and returns
# the coefficients a and b in param and
# the estimated covariance of param in param_cov
param, param_cov = curve_fit(test, x, y)

print("Sine function coefficients:")


print(param)
print("Covariance of coefficients:")
print(param_cov)

# ans stores the new y-data according to


# the coefficients given by curve-fit() function
ans = cookies
We use (param[0]*(np.sin(param[1]*x)))
to ensure you have the best browsing experience on our website. By using our site,
you acknowledge that you have read and understood our Cookie Policy & Privacy Policy

https://www.geeksforgeeks.org/scipy-curve-fitting/ 4/11
8/18/23, 3:31 AM SciPy | Curve Fitting - GeeksforGeeks

'''Below 4 lines can be un-commented for plotting results


using matplotlib as shown in the first example. '''

# plt.plot(x, y, 'o', color ='red', label ="data")


# plt.plot(x, ans, '--', color ='blue', label ="optimized data")
# plt.legend()
# plt.show()

Output:

Sine function coefficients:


[ 3.66474998 1.32876756]
Covariance of coefficients:
[[ 5.43766857e-02 -3.69114170e-05]
[ -3.69114170e-05 1.02824503e-04]]

Second example can be achieved by using the numpy exponential function shown as
follows:

Python3

x = np.linspace(0, 1, num = 40)

y = 3.45 * np.exp(1.334 * x) + np.random.normal(size = 40)

def test(x, a, b):


return a*np.exp(b*x)

param, param_cov = curve_fit(test, x, y)

However, if the coefficients are too large, the curve flattens and fails to provide the best fit.
The following code explains this fact:

Python3

import numpy as np
from scipy.optimize import curve_fit

from
We use matplotlib import
cookies to ensure you havepyplot as pltexperience on our website. By using our site,
the best browsing
you acknowledge that you have read and understood our Cookie Policy & Privacy Policy

https://www.geeksforgeeks.org/scipy-curve-fitting/ 5/11
8/18/23, 3:31 AM SciPy | Curve Fitting - GeeksforGeeks

x = np.linspace(0, 10, num = 40)

# The coefficients are much bigger.


y = 10.45 * np.sin(5.334 * x) + np.random.normal(size = 40)

def test(x, a, b):


return a * np.sin(b * x)

param, param_cov = curve_fit(test, x, y)

print("Sine function coefficients:")


print(param)
print("Covariance of coefficients:")
print(param_cov)

ans = (param[0]*(np.sin(param[1]*x)))

plt.plot(x, y, 'o', color ='red', label ="data")


plt.plot(x, ans, '--', color ='blue', label ="optimized data")
plt.legend()
plt.show()

Output:

Sine function coefficients:


[ 0.70867169 0.7346216 ]
Covariance of coefficients:
[[ 2.87320136 -0.05245869]
[-0.05245869 0.14094361]]

The blue dotted line is undoubtedly the line with best-optimized distances from all points of
the dataset, but it fails to provide a sine function with the best fit.
Curve Fitting should not be confused with Regression. They both involve approximating data
with functions. But the goal of Curve-fitting is to get the values for a Dataset through which
a given set of explanatory variables can actually depict another variable. Regression is a
special case of curve fitting but here you just don’t need a curve that fits the training data in
the best possible way(which may lead to overfitting) but a model which is able to generalize
the learning and thus predict new points efficiently.

We use cookies to ensure you have the best browsing experience on our website. By using our site,
you acknowledge that you have read and understood our Cookie Policy & Privacy Policy

https://www.geeksforgeeks.org/scipy-curve-fitting/ 6/11
8/18/23, 3:31 AM SciPy | Curve Fitting - GeeksforGeeks

Last Updated : 06 Aug, 2022 7

Similar Reads
How to do exponential and 3D Curve Fitting With Python
logarithmic curve fitting in
Python?

SciPy - Integration of a Differential How to plot ricker curve using


Equation for Curve Fit SciPy - Python?

SciPy Linear Algebra - SciPy Linalg Regression Analysis and the Best
Fitting Line using C++

Heighway's Dragon Curve using Koch Curve or Koch Snowflake


Python

Precision-Recall Curve | ML Python - Hilbert Curve using turtle

Related Tutorials
Computer Vision Tutorial Pandas AI: The Generative AI
Python Library

OpenAI Python API - Complete Top Computer Vision Projects


Guide (2023)

Python for Kids - Fun Tutorial to


Learn Python Programming

Previous Next

Article Contributed By :

ArijitGayen
A ArijitGayen
We use cookies to ensure you have the best browsing experience on our website. By using our site,
you acknowledge that you have read and understood our Cookie Policy & Privacy Policy

https://www.geeksforgeeks.org/scipy-curve-fitting/ 7/11
8/18/23, 3:31 AM SciPy | Curve Fitting - GeeksforGeeks

Follow

Vote for difficulty


Current difficulty : Easy

Easy Normal Medium Hard Expert

Improved By : simmytarika5, kk9826225, vinayedula

Article Tags : Python-scipy, Machine Learning, Python

Practice Tags : Machine Learning, python

Improve Article Report Issue

A-143, 9th Floor, Sovereign Corporate


Tower, Sector-136, Noida, Uttar Pradesh -
201305
feedback@geeksforgeeks.org

Company
We use cookies to ensure you have the best browsing experience on our website. By using our site,
you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Explore
https://www.geeksforgeeks.org/scipy-curve-fitting/ 8/11
8/18/23, 3:31 AM SciPy | Curve Fitting - GeeksforGeeks

About Us Job-A-Thon For Freshers


Legal Job-A-Thon For Experienced
Careers GfG Weekly Contest
In Media Offline Classes (Delhi/NCR)
Contact Us DSA in JAVA/C++
Advertise with us Master System Design
Master CP

Languages DSA Concepts


Python Data Structures
Java Arrays
C++ Strings
PHP Linked List
GoLang Algorithms
SQL Searching
R Language Sorting
Android Tutorial Mathematical
Dynamic Programming

DSA Roadmaps Web Development


DSA for Beginners HTML
Basic DSA Coding Problems CSS
Complete Roadmap To Learn DSA JavaScript
DSA for FrontEnd Developers Bootstrap
DSA with JavaScript ReactJS
Top 100 DSA Interview Problems AngularJS
NodeJS

Computer Science Python


GATE CS Notes Python Programming Examples
Operating Systems Django Tutorial
Computer Network Python Projects
Database Management System Python Tkinter
Software Engineering OpenCV Python Tutorial
We use cookies to ensure you have the best browsing experience on our website. By using our site,
you acknowledgeDigital
that youLogic
have Design Python Interview Question
read and understood our Cookie Policy & Privacy Policy

https://www.geeksforgeeks.org/scipy-curve-fitting/ 9/11
8/18/23, 3:31 AM SciPy | Curve Fitting - GeeksforGeeks

Engineering Maths

Data Science & ML DevOps


Data Science With Python Git
Data Science For Beginner AWS
Machine Learning Tutorial Docker
Maths For Machine Learning Kubernetes
Pandas Tutorial Azure
NumPy Tutorial GCP
NLP Tutorial
Deep Learning Tutorial

Competitive Programming System Design


Top DSA for CP What is System Design
Top 50 Tree Problems Monolithic and Distributed SD
Top 50 Graph Problems Scalability in SD
Top 50 Array Problems Databases in SD
Top 50 String Problems High Level Design or HLD
Top 50 DP Problems Low Level Design or LLD
Top 15 Websites for CP Top SD Interview Questions

Interview Corner GfG School


Company Wise Preparation CBSE Notes for Class 8
Preparation for SDE CBSE Notes for Class 9
Experienced Interviews CBSE Notes for Class 10
Internship Interviews CBSE Notes for Class 11
Competitive Programming CBSE Notes for Class 12
Aptitude Preparation English Grammar

Commerce UPSC
Accountancy Polity Notes
Business Studies Geography Notes
Economics History Notes
Management Science and Technology Notes
We use cookies to ensure you have the best browsing experience on our website. By using our site,
you acknowledge thatIncome
you haveTax
read and understood our Cookie Policy & Privacy Policy Economics Notes

https://www.geeksforgeeks.org/scipy-curve-fitting/ 10/11
8/18/23, 3:31 AM SciPy | Curve Fitting - GeeksforGeeks

Finance Important Topics in Ethics


UPSC Previous Year Papers

SSC/ BANKING Write & Earn


SSC CGL Syllabus Write an Article
SBI PO Syllabus Improve an Article
SBI Clerk Syllabus Pick Topics to Write
IBPS PO Syllabus Write Interview Experience
IBPS Clerk Syllabus Internships
Aptitude Questions
SSC CGL Practice Papers

@geeksforgeeks , Some rights reserved

Do Not Sell or Share My Personal Information

We use cookies to ensure you have the best browsing experience on our website. By using our site,
you acknowledge that you have read and understood our Cookie Policy & Privacy Policy

https://www.geeksforgeeks.org/scipy-curve-fitting/ 11/11

You might also like