 # Curve Fitting With Python

Curve fitting is a type of optimization that finds an optimal set of parameters for a defined function that best fits a given set of observations.

Unlike supervised learning, curve fitting requires that you define the function that maps examples of inputs to outputs.

The mapping function, also called the basis function can have any form you like, including a straight line (linear regression), a curved line (polynomial regression), and much more. This provides the flexibility and control to define the form of the curve, where an optimization process is used to find the specific optimal parameters of the function.

In this tutorial, you will discover how to perform curve fitting in Python.

After completing this tutorial, you will know:

• Curve fitting involves finding the optimal parameters to a function that maps examples of inputs to outputs.
• The SciPy Python library provides an API to fit a curve to a dataset.
• How to use curve fitting in SciPy to fit a range of different curves to a set of observations.

Let’s get started. Curve Fitting With Python
Photo by Gael Varoquaux, some rights reserved.

## Tutorial Overview

This tutorial is divided into three parts; they are:

1. Curve Fitting
2. Curve Fitting Python API
3. Curve Fitting Worked Example

## Curve Fitting

Curve fitting is an optimization problem that finds a line that best fits a collection of observations.

It is easiest to think about curve fitting in two dimensions, such as a graph.

Consider that we have collected examples of data from the problem domain with inputs and outputs.

The x-axis is the independent variable or the input to the function. The y-axis is the dependent variable or the output of the function. We don’t know the form of the function that maps examples of inputs to outputs, but we suspect that we can approximate the function with a standard function form.

Curve fitting involves first defining the functional form of the mapping function (also called the basis function or objective function), then searching for the parameters to the function that result in the minimum error.

Error is calculated by using the observations from the domain and passing the inputs to our candidate mapping function and calculating the output, then comparing the calculated output to the observed output.

Once fit, we can use the mapping function to interpolate or extrapolate new points in the domain. It is common to run a sequence of input values through the mapping function to calculate a sequence of outputs, then create a line plot of the result to show how output varies with input and how well the line fits the observed points.

The key to curve fitting is the form of the mapping function.

A straight line between inputs and outputs can be defined as follows:

• y = a * x + b

Where y is the calculated output, x is the input, and a and b are parameters of the mapping function found using an optimization algorithm.

This is called a linear equation because it is a weighted sum of the inputs.

In a linear regression model, these parameters are referred to as coefficients; in a neural network, they are referred to as weights.

This equation can be generalized to any number of inputs, meaning that the notion of curve fitting is not limited to two-dimensions (one input and one output), but could have many input variables.

For example, a line mapping function for two input variables may look as follows:

• y = a1 * x1 + a2 * x2 + b

The equation does not have to be a straight line.

We can add curves in the mapping function by adding exponents. For example, we can add a squared version of the input weighted by another parameter:

• y = a * x + b * x^2 + c

This is called polynomial regression, and the squared term means it is a second-degree polynomial.

So far, linear equations of this type can be fit by minimizing least squares and can be calculated analytically. This means we can find the optimal values of the parameters using a little linear algebra.

We might also want to add other mathematical functions to the equation, such as sine, cosine, and more. Each term is weighted with a parameter and added to the whole to give the output; for example:

• y = a * sin(b * x) + c

Adding arbitrary mathematical functions to our mapping function generally means we cannot calculate the parameters analytically, and instead, we will need to use an iterative optimization algorithm.

This is called nonlinear least squares, as the objective function is no longer convex (it’s nonlinear) and not as easy to solve.

Now that we are familiar with curve fitting, let’s look at how we might perform curve fitting in Python.

## Curve Fitting Python API

We can perform curve fitting for our dataset in Python.

The SciPy open source library provides the curve_fit() function for curve fitting via nonlinear least squares.

The function takes the same input and output data as arguments, as well as the name of the mapping function to use.

The mapping function must take examples of input data and some number of arguments. These remaining arguments will be the coefficients or weight constants that will be optimized by a nonlinear least squares optimization process.

For example, we may have some observations from our domain loaded as input variables x and output variables y.

Next, we need to design a mapping function to fit a line to the data and implement it as a Python function that takes inputs and the arguments.

It may be a straight line, in which case it would look as follows:

We can then call the curve_fit() function to fit a straight line to the dataset using our defined function.

The function curve_fit() returns the optimal values for the mapping function, e.g, the coefficient values. It also returns a covariance matrix for the estimated parameters, but we can ignore that for now.

Once fit, we can use the optimal parameters and our mapping function objective() to calculate the output for any arbitrary input.

This might include the output for the examples we have already collected from the domain, it might include new values that interpolate observed values, or it might include extrapolated values outside of the limits of what was observed.

Now that we are familiar with using the curve fitting API, let’s look at a worked example.

## Curve Fitting Worked Example

We will develop a curve to fit some real world observations of economic data.

In this example, we will use the so-called “Longley’s Economic Regression” dataset; you can learn more about it here:

We will download the dataset automatically as part of the worked example.

There are seven input variables and 16 rows of data, where each row defines a summary of economic details for a year between 1947 to 1962.

In this example, we will explore fitting a line between population size and the number of people employed for each year.

The example below loads the dataset from the URL, selects the input variable as “population,” and the output variable as “employed” and creates a scatter plot.

Running the example loads the dataset, selects the variables, and creates a scatter plot.

We can see that there is a relationship between the two variables. Specifically, that as the population increases, the total number of employees increases.

It is not unreasonable to think we can fit a line to this data. Scatter Plot of Population vs. Total Employed

First, we will try fitting a straight line to this data, as follows:

We can use curve fitting to find the optimal values of “a” and “b” and summarize the values that were found:

We can then create a scatter plot as before.

On top of the scatter plot, we can draw a line for the function with the optimized parameter values.

This involves first defining a sequence of input values between the minimum and maximum values observed in the dataset (e.g. between about 120 and about 130).

We can then calculate the output value for each input value.

Then create a line plot of the inputs vs. the outputs to see a line:

Tying this together, the example below uses curve fitting to find the parameters of a straight line for our economic data.

Running the example performs curve fitting and finds the optimal parameters to our objective function.

First, the values of the parameters are reported.

Next, a plot is created showing the original data and the line that was fit to the data.

We can see that it is a reasonably good fit. Plot of Straight Line Fit to Economic Dataset

So far, this is not very exciting as we could achieve the same effect by fitting a linear regression model on the dataset.

Let’s try a polynomial regression model by adding squared terms to the objective function.

Tying this together, the complete example is listed below.

First the optimal parameters are reported.

Next, a plot is created showing the line in the context of the observed values from the domain.

We can see that the second-degree polynomial equation that we defined is visually a better fit for the data than the straight line that we tested first. Plot of Second Degree Polynomial Fit to Economic Dataset

We could keep going and add more polynomial terms to the equation to better fit the curve.

For example, below is an example of a fifth-degree polynomial fit to the data.

Running the example fits the curve and plots the result, again capturing slightly more nuance in how the relationship in the data changes over time. Plot of Fifth Degree Polynomial Fit to Economic Dataset

Importantly, we are not limited to linear regression or polynomial regression. We can use any arbitrary basis function.

For example, perhaps we want a line that has wiggles to capture the short-term movement in observation. We could add a sine curve to the equation and find the parameters that best integrate this element in the equation.

For example, an arbitrary function that uses a sine wave and a second degree polynomial is listed below:

The complete example of fitting a curve using this basis function is listed below.

Running the example fits a curve and plots the result.

We can see that adding a sine wave has the desired effect showing a periodic wiggle with an upward trend that provides another way of capturing the relationships in the data. Plot of Sine Wave Fit to Economic Dataset

How do you choose the best fit?

If you want the best fit, you would model the problem as a regression supervised learning problem and test a suite of algorithms in order to discover which is best at minimizing the error.

In this case, curve fitting is appropriate when you want to define the function explicitly, then discover the parameters of your function that best fit a line to the data.

This section provides more resources on the topic if you are looking to go deeper.

## Summary

In this tutorial, you discovered how to perform curve fitting in Python.

Specifically, you learned:

• Curve fitting involves finding the optimal parameters to a function that maps examples of inputs to outputs.
• Unlike supervised learning, curve fitting requires that you define the function that maps examples of inputs to outputs.
• How to use curve fitting in SciPy to fit a range of different curves to a set of observations.

Do you have any questions?

### 46 Responses to Curve Fitting With Python

1. Luiz Germano November 6, 2020 at 8:01 am #

Great Jason!!
As always, very useful.
Thanks for you work.

• Jason Brownlee November 6, 2020 at 10:13 am #

Thanks!

2. Philipe Riskalla Leal November 6, 2020 at 8:33 am #

Dear Jason Brownlee,

thank you for this great post.

I wonder if you could further elaborate how one may interpret and analyze the covariance matrix from the fitting function.

I thank you for your time.

Sincerely,

• Jason Brownlee November 6, 2020 at 10:14 am #

Thanks!

Great suggestion.

3. Pablo Nuñez November 26, 2020 at 7:44 pm #

Fantastic post! Thank you

• Jason Brownlee November 27, 2020 at 6:36 am #

Thank you!

4. Luke December 3, 2020 at 3:55 am #

Great tutorial I’ve done it succesfully!

Only thing I needed to do differently is import numpy and scipy to get it working.

Question: How can I measure or calculate the error of the curve to the real data?

• Jason Brownlee December 3, 2020 at 8:23 am #

You can calculate the error between expected and predicted values, typically MAE or RMSE.

5. Irving December 4, 2020 at 12:22 pm #

I would like to know , if you have your lesson and practices problem in YouTube?

• Jason Brownlee December 4, 2020 at 1:23 pm #

You’re welcome.

Sorry, I don’t have any youtube videos.

I offer self-study ebook courses here:
https://machinelearningmastery.com/products/

6. Stephen December 5, 2020 at 4:24 am #

Thanks for the article! Do you have any good links or tutorials for adding constraints? For example, I am trying to fit the sum of several Gaussians to a set of data. I am playing with adding constraints on:
– the area of each Gaussian
– the center of each Gaussian
– The relative areas of different Gaussians
– etc.

I have been using a penalty method to apply the constraints. Trial and error (playing with the penalty factors) has allowed me to achieve believable results, but I’m wondering if there is a systematic way to find good penalty factors as more constraints are added. The solution becomes a bit unstable as I add more constraints (small changes in penalty factor result in different fits).

• Jason Brownlee December 5, 2020 at 8:10 am #

Interesting project. Sorry, I don’t have good comments off the cuff. Perhaps check a text on multivariate analysis or multivariate stats?

7. Stanly December 21, 2020 at 4:34 am #

Thank you for the good sharing!

I’ve modified your code to read the CSV data file from my local machine. I saved the CSV file and made these changes; but somehow I didn’t get what I want.

import pandas as pd

8. Mike December 29, 2020 at 1:56 pm #

This is great information. One question I have is how to accomplish curve fitting for multiple samples. Say for example we have data points for four independent runs of an experiment representing user 1 – user 4. Ideally I’d like to take these 4 runs and create a curve that “fits” all four runs and presents one equation that is optimal. I’m not clear how to accomplish this with python’s curve fitting function. Can you clarify how this would be accomplished

• Jason Brownlee December 30, 2020 at 6:32 am #

Thanks.

Not really sure I follow – let me try – if you want a curve that generalizes across 4 samples of the population, perhaps combine the 4 samples into one sample and fit a curve to that?

Does that help?

9. Juanma February 26, 2021 at 11:43 pm #

Thanks, you helped me a lot with this post.

• Jason Brownlee February 27, 2021 at 6:04 am #

You’re welcome.

10. Jennifer March 13, 2021 at 6:45 am #

What python package do you recommend for assessing the best fit?

• Jason Brownlee March 13, 2021 at 7:56 am #

Often we use an error metric, like R^2 or MSE.

11. Mason April 17, 2021 at 3:17 am #

Hi, Jason. Thanks for the really useful post.
I have a stupid question because I am a newbie in Python.

# choose the input and output variables
x, y = data[:, 4], data[:, -1]

Why is x=data[:,4] and y=data[:,-1]?

In the dataset in .csv, Population seems in the 5th column and Total Employed in the last column. Then, how the column indices for x and y are corresponding to 4 and -1?

Thanks again.

12. Mason April 17, 2021 at 6:22 am #

Wow, so much flexibility..

• Jason Brownlee April 18, 2021 at 5:50 am #

You’re welcome.

13. Zero April 19, 2021 at 1:30 am #

Man, this is the best article about curve fitting I have came across. Thanks alot.

• Jason Brownlee April 19, 2021 at 5:52 am #

Thanks!

14. Rudolf E Baer May 6, 2021 at 4:39 am #

I have to do a Blackbody fit. The function is

def bb(x, T):
from scipy.constants import h,k,c
x = 1e-6 * x # convert to metres from um
return 2*h*c**2 / (x**5 * (np.exp(h*c / (x*k*T)) – 1))

How do I take care of the input for the Temperature T?

R. Baer

• Jason Brownlee May 6, 2021 at 5:49 am #

I don’t know sorry.

15. YMAlini May 7, 2021 at 10:04 pm #

Hi, I have a problem I’m trying to run some analysis on my data using LRP (Linear Response Plateau) but I’m pretty lost with the broken-line equation and how to insert it into python. Can you help?

• Jason Brownlee May 8, 2021 at 6:35 am #

Sorry, I am not familiar with “LRP” off the cuff.

16. Jillian May 26, 2021 at 11:47 am #

Great tutorial! I am running into an error however:

from scipy.optimize import curve_fit
def objective (qi,a,b):
return qi*n + b

chargedata = loadtxt(“242E1charges.tsv”, float, skiprows = 1)
qi = chargedata[:,:]
n = qi//qs

plot(qi,n, “rd”, label =”data points”)
fit, _ = curve_fit(objective, qi, n)

where I am using qi alternatively to x.
the error that pops up is:
Result from function call is not a proper array of floats.

any ideas on how to fix this? I am somewhat new to python so I apologize if the solution is elementary.

• Jason Brownlee May 27, 2021 at 5:32 am #

No sorry, this looks like custom code.

Perhaps you can post your code, data and error on stackoverflow.com

17. Talat May 27, 2021 at 4:23 pm #

Hi, Any idea on how we can do curve fitting on a time series?
Your tutorials are of great help,Thankyou!

• Jason Brownlee May 28, 2021 at 6:45 am #

Not off hand, perhaps the same methods can be adapted.

18. Talat May 27, 2021 at 9:49 pm #

Hi!
how can we predict using curve fitting?

19. Ajinkya Bankar July 8, 2021 at 10:47 pm #

Hi Jason,
Thanks for sharing the important information.
I have experimental data consisting of inputs and corresponding outputs. I want to find the best model fitting the data. As you said in the last paragraph, use “a regression supervised learning problem.” Can you please elaborate more on this, or can you please give an example with the source code?

20. Donglok Kim July 11, 2021 at 8:49 pm #

Can we do 2D array [x,y] curve fitting where x and y are not monotonic?

• Jason Brownlee July 12, 2021 at 5:48 am #

Perhaps try it and see.

21. Nicolae July 24, 2021 at 8:38 pm #

Thanks, you made it so simple for us!

• Jason Brownlee July 25, 2021 at 5:13 am #

You’re welcome!

22. Sumit August 7, 2021 at 4:01 am #

Thank you for this great post. Helped me a lot.

• Jason Brownlee August 7, 2021 at 5:42 am #

I’m happy to hear that.

23. Nikhil August 31, 2021 at 3:37 pm #

Very nice post. Had a doubt, is it possible to do curve fitting on 3 feature together with 1 target variable ? Like temp, humidity and windspeed with target variable PlantFungusGrowth.
• 