TExcelTAD
Home › SciPy › SciPy Curve Fitting

SciPy Curve Fitting

You have measurements and a model — a formula with a few unknown parameters, like y = a·e^(−b·t) + c. Curve fitting finds the parameter values that make the model match the data as closely as possible. SciPy's workhorse for this is scipy.optimize.curve_fit(), which uses non-linear least squares: it minimises the sum of squared differences between the model and the data.

Your first fit

Write the model as a Python function whose first argument is the independent variable, followed by the parameters. Then pass it to curve_fit with the data:

python · try it yourself
import numpy as np
from scipy.optimize import curve_fit

def model(t, a, b, c):
    return a * np.exp(-b * t) + c

# Temperature of a cooling drink, measured every 2 minutes (with sensor noise)
rng = np.random.default_rng(0)
t = np.arange(0, 30, 2.0)
temp = model(t, 60, 0.15, 22) + rng.normal(0, 0.8, t.size)

params, cov = curve_fit(model, t, temp, p0=[50, 0.1, 20])
a, b, c = params
print(f"a = {a:.3f}, b = {b:.4f}, c = {c:.3f}")
print(f"room temperature estimate: {c:.1f} C")
a = 60.813, b = 0.1430, c = 21.002
room temperature estimate: 21.0 C

curve_fit returns two things:

Return value Meaning
popt (here params) Best-fit parameter values, in the order of your function's arguments
pcov (here cov) Covariance matrix of the estimates; the square roots of its diagonal are the standard errors

The starting guess p0 matters for non-linear models. Without it every parameter starts at 1, which may be far from the truth and lead to a poor or failed fit.

Uncertainty of the parameters

A fit isn't complete without error bars. Take the square root of the covariance diagonal:

python · try it yourself
import numpy as np
from scipy.optimize import curve_fit

def model(t, a, b, c):
    return a * np.exp(-b * t) + c

rng = np.random.default_rng(0)
t = np.arange(0, 30, 2.0)
temp = model(t, 60, 0.15, 22) + rng.normal(0, 0.8, t.size)

params, cov = curve_fit(model, t, temp, p0=[50, 0.1, 20])
errors = np.sqrt(np.diag(cov))
for name, value, err in zip("abc", params, errors):
    print(f"{name} = {value:8.4f} +/- {err:.4f}")

residuals = temp - model(t, *params)
print(f"RMS of residuals: {np.sqrt(np.mean(residuals ** 2)):.3f}")
a =  60.8129 +/- 0.5970
b =   0.1430 +/- 0.0036
c =  21.0023 +/- 0.4012
RMS of residuals: 0.596

The residual spread is of the same size as the noise we added (standard deviation 0.8), a good sign that the model captures everything except the random noise.

Plotting the fit

python · try it yourself
import numpy as np
import matplotlib.pyplot as plt
from scipy.optimize import curve_fit

def model(t, a, b, c):
    return a * np.exp(-b * t) + c

rng = np.random.default_rng(0)
t = np.arange(0, 30, 2.0)
temp = model(t, 60, 0.15, 22) + rng.normal(0, 0.8, t.size)
params, _ = curve_fit(model, t, temp, p0=[50, 0.1, 20])

smooth_t = np.linspace(0, 30, 200)
plt.plot(t, temp, "o", label="measurements")
plt.plot(smooth_t, model(smooth_t, *params), "-", label="fitted model")
plt.axhline(params[2], color="gray", ls=":", label="room temperature")
plt.xlabel("time (min)")
plt.ylabel("temperature (C)")
plt.legend()
plt.show()
print(f"Plotted the data and the fitted curve (b = {params[1]:.4f} per minute).")
Plotted the data and the fitted curve (b = 0.1430 per minute).

Bounds and weights

Physical parameters often can't be negative. Use bounds=(lower, upper) to restrict them. If some points are less reliable than others, pass their standard deviations as sigma= so they count less:

python · try it yourself
import numpy as np
from scipy.optimize import curve_fit

def logistic(x, k, x0, top):
    return top / (1 + np.exp(-k * (x - x0)))

# Share of users who adopted a new app feature, by week
week = np.arange(0, 12)
share = np.array([1, 2, 3, 6, 11, 19, 30, 42, 52, 58, 61, 63], dtype=float)
uncertainty = np.where(week < 3, 3.0, 1.0)     # early weeks were noisy

params, cov = curve_fit(logistic, week, share, p0=[1, 6, 60], sigma=uncertainty,
                        bounds=([0, 0, 0], [5, 20, 100]))
k, x0, top = params
print(f"growth rate k = {k:.3f}")
print(f"midpoint week = {x0:.2f}")
print(f"saturation    = {top:.1f}%")
growth rate k = 0.741
midpoint week = 6.17
saturation    = 64.9%

Polynomial fits

For a polynomial the problem is linear in its coefficients, so you don't need curve_fit — np.polyfit solves it directly. Compare a straight line with a quadratic:

python · try it yourself
import numpy as np

speed = np.array([20, 30, 40, 50, 60, 70, 80, 90])          # km/h
stopping = np.array([8.5, 15.2, 23.9, 34.0, 46.1, 60.3, 75.8, 93.0])  # m

for degree in (1, 2):
    coeffs = np.polyfit(speed, stopping, degree)
    predicted = np.polyval(coeffs, speed)
    sse = np.sum((stopping - predicted) ** 2)
    print(f"degree {degree}: coefficients {np.round(coeffs, 4)}, SSE = {sse:.2f}")
degree 1: coefficients [  1.2093 -21.9107], SSE = 131.20
degree 2: coefficients [0.0088 0.2376 0.1726], SSE = 0.11

The quadratic fits far better, which matches the physics: braking distance grows with the square of speed.

Tip: More parameters always reduce the error on the data you fitted, but can make predictions worse (overfitting). Choose the simplest model that explains the data, ideally one with a physical meaning.

Test yourself

What must the first argument of the model function passed to curve_fit be?

  1. The first parameter
  2. The independent variable (x)
  3. The covariance matrix
  4. The initial guess

How do you get the standard errors of fitted parameters from pcov?

  1. pcov.sum()
  2. np.sqrt(np.diag(pcov))
  3. pcov[0]
  4. 1 / pcov

Why provide p0 to curve_fit?

  1. It is required for linear models
  2. A good starting guess helps the non-linear optimizer converge to the right answer
  3. It sets the noise level
  4. It fixes the parameters