Skip to main content

Tools to get prediction intervals when using scipy's least_squares minimizer

Project description

fittingtools

Some tools built upon scipy's least squares fitting.

Installation

pip install fittingtools

Basic usage: exponential model

import fittingtools as fls

Define the exponential model:

import numpy as np
from numpy.random import default_rng
from scipy.optimize import least_squares
rng = default_rng()

def model(t, b):
    return b[0] + b[1] * np.exp(b[2] * t)

Generate noisy data

def gen_data(t, a, b, c, noise=0., n_outliers=0, seed=None):
    rng = default_rng(seed)

    y = a + b * np.exp(t * c)

    error = noise * rng.standard_normal(t.size)
    outliers = rng.integers(0, t.size, n_outliers)
    error[outliers] *= 10

    return y + error

a = 0.5
b = 2.0
c = -1
t_min = 0
t_max = 10
n_points = 15

t_train = np.linspace(t_min, t_max, n_points)
y_train = gen_data(t_train, a, b, c, noise=0.1, n_outliers=3)

Define the residuals

def res(b, t, y):
    return model(t, b) - y

Optional:

Define the jacobian for the model

def jac(b, t, y):
    n, p = len(t), len(b)
    j = np.empty((n, p), dtype=np.float64)
    j[:, 0] = np.ones(n, dtype=np.float64)
    e = np.exp(b[2] * t)
    j[:, 1] = e
    j[:, 2] = b[1] * t * e
    return j

Fit the data using scipy.optimize.least_squares:

x0 = np.array([1.0, 1.0, 0.0])
res_lsq = least_squares(res, x0, args=(t_train, y_train), loss='cauchy', f_scale=0.1, jac=jac)

Get the confidence intervals for the optimzied parameters:

popt = res_lsq.x
parameters_ci = fls.confidence_interval(ls_res=res_lsq, level=0.95)
for i, p, lci, uci in zip(range(len(popt)), popt, parameters_ci[:,0], parameters_ci[:,1]):
  print(f'beta[{i}]: {p:>7.3f}, 95% CI: [{lci:>7.3f}, {uci:>7.3f}]')
beta[0]:   0.492, 95% CI: [  0.344,   0.640]
beta[1]:   2.096, 95% CI: [  1.829,   2.364]
beta[2]:  -1.039, 95% CI: [ -1.391,  -0.686]

Generate the prediction intervals for the fit (95% confidence level)

t_test = np.linspace(t_min, t_max, n_points * 10)
y_true = gen_data(t_test, a, b, c)

y_pred, delta = fls.prediction_intervals(
    model=model, x_pred=t_test, ls_res=res_lsq, jac=jac
)

Plot the data

import matplotlib.pyplot as plt

fig, ax = plt.subplots(1, 1, constrained_layout=True)
ax.plot(t_train, y_train, 'o')
ax.fill_between(t_test, y_pred - delta, y_pred + delta, color='C0', alpha=0.5, label='95% intervals')
ax.plot(t_test, y_true, 'k', linewidth=2, label='true')
ax.plot(t_test, y_pred, linewidth=2, label='cauchy')

ax.set_xlabel('x')
ax.set_ylabel('y')
ax.legend(loc='best', frameon=True)
plt.show()

Example prediction intervals exponential fit (cauchy)

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

fittingtools-0.1.5.tar.gz (32.1 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

fittingtools-0.1.5-py3-none-any.whl (6.1 kB view details)

Uploaded Python 3

File details

Details for the file fittingtools-0.1.5.tar.gz.

File metadata

  • Download URL: fittingtools-0.1.5.tar.gz
  • Upload date:
  • Size: 32.1 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.1.0 CPython/3.11.11

File hashes

Hashes for fittingtools-0.1.5.tar.gz
Algorithm Hash digest
SHA256 0fffb8ba0268c691f7305ea6aaf5410e41358bc6ada0bbde8cc0d26a5fd4431a
MD5 8cdf4028a8127b4747d40bf5c0449570
BLAKE2b-256 3917d2ac2a384e3ec9e16d6cf4abfc090bb26cb6130e3982192b974e1c9fad2d

See more details on using hashes here.

File details

Details for the file fittingtools-0.1.5-py3-none-any.whl.

File metadata

  • Download URL: fittingtools-0.1.5-py3-none-any.whl
  • Upload date:
  • Size: 6.1 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.1.0 CPython/3.11.11

File hashes

Hashes for fittingtools-0.1.5-py3-none-any.whl
Algorithm Hash digest
SHA256 84c1361e91a12fbdf3d1503d1b9b48999a7b997cc7b68639d5b0ba3095ad52e2
MD5 286afa2c8832d604ba6158b082c3e6d0
BLAKE2b-256 7e2a46fead54ba049edee5c14ca33be7e3ea2cd5dea26032a7b175f577661f9c

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page