The Wayback Machine - https://web.archive.org/web/20240902154028/https://www.geeksforgeeks.org/scipy-curve-fitting/
Open In App

SciPy | Curve Fitting

Last Updated : 06 Aug, 2022
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

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 : 
 

Output : 
 

Input : 
 

Output : 
 

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
 
# 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 = (param[0]*(np.sin(param[1]*x)))
 
'''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 matplotlib import pyplot as plt
 
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.
 



Similar Reads

How to do exponential and logarithmic curve fitting in Python?
In this article, we will learn how to do exponential and logarithmic curve fitting in Python. Firstly the question comes to our mind What is curve fitting? 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. Logarithmic curve fitting: The l
4 min read
3D Curve Fitting With Python
Curve fitting is a widely used technique in the field of data analysis and mathematical modeling. It involves the process of finding a mathematical function that best approximates a set of data points. In 3D curve fitting, the process is extended to three-dimensional space, where the goal is to find a function that best represents a set of 3D data
7 min read
Fitting Logarithmic Curve in a Dataset in R
Fitting a logarithmic curve to a dataset in R involves finding parameters that best describe the logarithmic relationship between variables. Logarithmic curves are often used to model situations where the growth rate of a variable decreases over time or with increasing values of another variable. Here's a step-by-step guide on how to fit a logarith
4 min read
SciPy - Integration of a Differential Equation for Curve Fit
In Machine Learning, often what we do is gather data, visualize it, then fit a curve in the graph and then predict certain parameters based on the curve fit. If we have some theoretical data we can use curve fitting from the verified dataset to extract the equation and verify it. So to find the equation of a curve of any order be it linear, quadrat
2 min read
How to plot ricker curve using SciPy - Python?
Prerequisites: Mathplotlib, NumPy A Ricker wavelet is a wave-like oscillation with an amplitude that begins at 0, increases, and then decreases back to 0. A Ricker wavelet, also known as the “Mexican hat wavelet”.In this article, we will plot the ricker curve that makes them useful for signal processing. It is the negative normalized second derivat
2 min read
SciPy Linear Algebra - SciPy Linalg
The SciPy package includes the features of the NumPy package in Python. It uses NumPy arrays as the fundamental data structure. It has all the features included in the linear algebra of the NumPy module and some extended functionality. It consists of a linalg submodule, and there is an overlap in the functionality provided by the SciPy and NumPy su
8 min read
Accuracy and Loss Don't Change in CNN. Is It Over-Fitting?
Answer : No, if accuracy and loss don't change, it's more indicative of underfitting or learning issues, not overfitting.When training a Convolutional Neural Network (CNN), encountering a situation where both accuracy and loss remain constant over epochs does not typically suggest overfitting. Instead, this scenario is often indicative of underfitt
2 min read
How to choose Batch Size and Number of Epochs When Fitting a Model?
When developing machine learning models, two of the most critical hyperparameters to fine-tune are batch size and number of epochs. These parameters significantly influence the training process and ultimately the performance of your model. But determining the right values for batch size and number of epochs can be complex and often requires a balan
5 min read
Detecting outliers when fitting data with nonlinear regression
Nonlinear regression is a powerful tool used to model complex relationships between variables. However, the presence of outliers can significantly distort the results, leading to inaccurate parameter estimates and unreliable predictions. Detecting and managing outliers is therefore crucial for robust nonlinear regression analysis. This article delv
7 min read
Predict and Plot After Fitting arima() Model in R
Autoregressive Integrated Moving Average (ARIMA) models are a powerful class of models for forecasting time series data. This article will cover the theoretical foundation of ARIMA models, their components, and a step-by-step guide to fitting, predicting, and plotting results using ARIMA models in R. Components of ARIMAAn ARIMA model is characteriz
3 min read
Plotting the Growth Curve of Coronavirus in various Countries using Python
In this article, we will collect latest updated information about the coronavirus cases across the world and in a particular country. We will plot graphs to visualise the growth of total number of cases and the total deaths for the last 20 days. The latest data is fetched from Our World in Data. Python modules required requests: The requests librar
3 min read
Validation Curve
Model validation is an important part of the data science project since want to select a model which not only performs well on our training dataset but also has good accuracy on the testing dataset. Model validation helps us in finding a model which has low variance. What is Validation Curve A Validation Curve is an important diagnostic tool that s
4 min read
How to Plot a Smooth Curve in Matplotlib?
Prerequisite: Introduction to Matplotlib Many times we have line plots generated from lists of data that are quite scattered which makes graphs seem like straight lines connecting dots or quite dense which leads to the data points being extremely close to each other and hence the plot looks cluttered. The matplotlib.pyplot.plot() function by defaul
4 min read
Probability Calibration Curve in Scikit Learn
Probability Calibration is a technique used to convert the output scores from a binary classifier into probabilities to correlate with the actual probabilities of the target class. In this article, we will discuss probability calibration curves and how to plot them using Scikit-learn. Probability Calibration A probability calibration curve is a plo
6 min read
How to plot ROC curve in Python
The Receiver Operating Characteristic (ROC) curve is a fundamental tool in the field of machine learning for evaluating the performance of classification models. In this context, we'll explore the ROC curve and its associated metrics using the breast cancer dataset, a widely used dataset for binary classification tasks. What is the ROC Curve? The R
7 min read
Learning Curve To Identify Overfit & Underfit
A learning curve is a graphical representation showing how an increase in learning comes from greater experience. It can also reveal if a model is learning well, overfitting, or underfitting. In this article, we'll gain insights on how to identify underfitted and overfitted models using Learning Curve. Table of Content Understanding Learning CurveI
9 min read
Validation Curve using Scikit-learn
Validation curves are essential tools in machine learning for diagnosing model performance and understanding the impact of hyperparameters on model accuracy. This article will delve into the concept of validation curves, their importance, and how to implement them using Scikit-learn in Python. Table of Content What is a Validation Curve?Understandi
7 min read
Precision-Recall Curve | ML
There are numerous ways to evaluate the performance of a classifier. In this article, we introduce the Precision-Recall Curve and further examine the difference between two popular performance reporting methods: Precision-Recall (PR) Curve and Receiver Operating Characteristic (ROC) Curve. ROC Curve is already discussed in the article. Let us brief
10 min read
AUC ROC Curve in Machine Learning
One important aspect of Machine Learning is model evaluation. You need to have some mechanism to evaluate your model. This is where these performance metrics come into the picture they give us a sense of how good a model is. If you are familiar with some of the basics of Machine Learning then you must have come across some of these metrics, like ac
15+ min read
sciPy stats.tsem() function | Python
scipy.stats.tsem(array, limits=None, inclusive=(True, True)) calculates the trimmed standard error of the mean of array elements along the specified axis of the array. Its formula :- Parameters : array: Input array or object having the elements to calculate the trimmed standard error of the mean. axis: Axis along which the trimmed standard error of
2 min read
sciPy stats.tvar() function | Python
scipy.stats.tvar(array, limits=None, inclusive=(1, 1)) function calculates the trimmed variance of the array elements along with ignoring the values lying outside the specified limits. It's formula - Parameters : array: Input array or object having the elements to calculate the trimmed variance. limits: Lower and upper bound of the array to conside
2 min read
sciPy stats.hmean() | Python
scipy.stats.hmean(array, axis=0, dtype=None) calculates the harmonic mean of the array elements along the specified axis of the array (list in python). It's formula - Parameters : array: Input array or object having the elements to calculate the harmonic mean. axis: Axis along which the mean is to be computed. By default axis = 0 dtype: Optional. I
2 min read
scipy stats.tmin() function | Python
scipy.stats.tmin(array, lowerlimit=None, axis=0, inclusive=True) function calculates the trimmed minimum of the array elements along with ignoring the values lying outside the specified limits, along the specified axis. Parameters : array: Input array or object having the elements to calculate the minimum. axis: [Default is zero] Input array or obj
2 min read
sciPy stats.tstd() function | Python
scipy.stats.tstd(array, limits=None, inclusive=(True, True)) calculates the trimmed standard deviation of the array elements along the specified axis of the array. It's formula - Parameters : array: Input array or object having the elements to calculate the trimmed standard deviation. axis: Axis along which the trimmed standard deviation is to be c
2 min read
sciPy stats.tmean() | Python
scipy.stats.tmean(array, limits=None, inclusive=(True, True)) calculates the trimmed mean of the array elements along the specified axis of the array. It's formula - Parameters : array: Input array or object having the elements to calculate the trimmed mean. axis: Axis along which the trimmed mean is to be computed. By default axis = 0. limits: Low
2 min read
sciPy stats.tmax() function | Python
scipy.stats.tmax(array, lowerlimit=None, axis=0, inclusive=True) function calculates the trimmed maximum of the array elements along with ignoring the values lying outside the specified limits, along the specified axis. Parameters : array: Input array or object having the elements to calculate the trimmed maximum. axis: Axis along which the statist
2 min read
sciPy stats.describe() function | Python
scipy.stats.describe(array, axis=0) computes the descriptive statistics of the passed array elements along the specified axis of the array. Parameters : array: Input array or object having the elements to calculate the statistics. axis: Axis along which the statistics is to be computed. By default axis = 0. Returns : Statistics of the array element
2 min read
sciPy stats.mean() function | Python
scipy.stats.mean(array, axis=0) function calculates the arithmetic mean of the array elements along the specified axis of the array (list in python). It's formula - Parameters : array: Input array or object having the elements to calculate the arithmetic mean. axis: Axis along which the mean is to be computed. By default axis = 0 Returns : Arithmet
1 min read
sciPy stats.nanmedian() function | Python
scipy.stats.nanmedian(array, axis=0) function calculates the median by ignoring the Nan (not a number) values of the array elements along the specified axis of the array. Parameters : array : Input array or object having the elements, including Nan values, to calculate the median. axis : Axis along which the median is to be computed. By default axi
2 min read
sciPy stats.nanstd() function | Python
scipy.stats.nanstd(array, axis=0) function calculates the standard deviation by ignoring the Nan (not a number) values of the array elements along the specified axis of the array. It's formula - Parameters : array : Input array or object having the elements, including Nan values, to calculate the standard deviation. axis : Axis along which the stan
2 min read