0
0
SciPydata~5 mins

Fitting custom models in SciPy

Choose your learning style9 modes available
Introduction

We fit custom models to find the best parameters that explain our data. This helps us understand patterns and make predictions.

You have data points and want to find a curve that best matches them.
You want to estimate parameters of a model that describes your experiment.
You need to predict future values based on a custom formula.
You want to compare how well different models fit your data.
You want to automate finding the best fit without guessing parameters.
Syntax
SciPy
from scipy.optimize import curve_fit

def model(x, a, b):
    return a * x + b

params, covariance = curve_fit(model, xdata, ydata, p0=[1, 0])

curve_fit finds the best parameters for your model function.

p0 is the initial guess for parameters; it helps the fitting start.

Examples
Fit a straight line to data points without initial guess.
SciPy
from scipy.optimize import curve_fit
import numpy as np

def linear_model(x, m, c):
    return m * x + c

xdata = np.array([1, 2, 3, 4, 5])
ydata = np.array([2.1, 4.1, 6.0, 8.1, 10.2])

params, _ = curve_fit(linear_model, xdata, ydata)
print(params)
Fit a quadratic curve with an initial guess for parameters.
SciPy
from scipy.optimize import curve_fit
import numpy as np

def quadratic_model(x, a, b, c):
    return a * x**2 + b * x + c

xdata = np.linspace(-5, 5, 11)
ydata = 2 * xdata**2 + 3 * xdata + 1 + np.random.normal(0, 1, len(xdata))

params, _ = curve_fit(quadratic_model, xdata, ydata, p0=[1, 1, 1])
print(params)
Sample Program

This program fits an exponential curve to noisy data. It prints the best parameters and shows a plot with data points and the fitted curve.

SciPy
from scipy.optimize import curve_fit
import numpy as np
import matplotlib.pyplot as plt

def exponential_model(x, a, b):
    return a * np.exp(b * x)

# Create sample data with noise
xdata = np.linspace(0, 4, 50)
ydata = 2.5 * np.exp(1.3 * xdata) + np.random.normal(0, 0.2, xdata.size)

# Fit the model to data
params, covariance = curve_fit(exponential_model, xdata, ydata, p0=[1, 1])

# Print fitted parameters
a_fit, b_fit = params
print(f"Fitted parameters: a = {a_fit:.3f}, b = {b_fit:.3f}")

# Plot data and fitted curve
plt.scatter(xdata, ydata, label='Data')
plt.plot(xdata, exponential_model(xdata, *params), color='red', label='Fitted model')
plt.legend()
plt.xlabel('x')
plt.ylabel('y')
plt.title('Fitting custom exponential model')
plt.show()
OutputSuccess
Important Notes

Always provide a reasonable initial guess p0 to help the fitting process.

Check the covariance matrix to understand parameter uncertainty.

Plot your data and fitted curve to visually check the fit quality.

Summary

Use curve_fit to find best parameters for your custom model function.

Provide data and a model function that returns predicted values.

Check results by printing parameters and plotting the fit.