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

from src 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.4.tar.gz (31.7 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.4-py3-none-any.whl (6.1 kB view details)

Uploaded Python 3

File details

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

File metadata

  • Download URL: fittingtools-0.1.4.tar.gz
  • Upload date:
  • Size: 31.7 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.4.tar.gz
Algorithm Hash digest
SHA256 67b3eead30cbdf6d51a8184d45fe9b66f36908740fcb2d1c667a732c0369499b
MD5 386c5ec84f54a2a15e59b7cecfea0f7a
BLAKE2b-256 5de4588b4a59fc7eb1d41eb8a4bfd8b108fb9a96a9168afd7040603917e7eb71

See more details on using hashes here.

File details

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

File metadata

  • Download URL: fittingtools-0.1.4-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.4-py3-none-any.whl
Algorithm Hash digest
SHA256 ad8b6ba2967f23e57271744e6ad101268a62f41dddcb3820d2e512f2f2c63556
MD5 9e6037935a20be4c7d28f641f5c82c82
BLAKE2b-256 3e8b454f758438e42b6ca44aefa21999279a4d612004c05c44c42bbeea51b811

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