How do I find the uncertainties on a fit with correlated parameters in python?

93 views Asked by At

I have found the parameters that get the best fit to the data using chi squared and the scipy fmin function. I am trying to get the uncertainties on these parameters by finding the values on the chi squared = chi squared min + 1 contour, and I know how to do this for uncorrelated parameters. I have an idea of how to do it for correlated parameters but it seems like it will take a lot of code, so I was wondering if there was something simple that I'm missing?

def polynomial(x_value, parameters):
    a = parameters[0]
    b = parameters[1]
    return (a + b) * x_value**2 + (a - b) * x_value - 2.6

def calculate_chi_squared(data, prediction):
    return np.sum((prediction - data[:, 1])**2 / data[:, 2]**2)

data = np.genfromtxt('polynomial_data_2.csv', delimiter=',')

chi_squared = lambda parameters: calculate_chi_squared(data, polynomial_2(data[:, 0], parameters))
result = optimize.fmin(chi_squared, INITIAL_GUESS_2, full_output=True)
optimised_parameters = result[0]
1

There are 1 answers

0
jlandercy On

If you have two variables x, y and uncertainty s on y you can directly perform the operation with curve_fit:

import numpy as np
from scipy import optimize

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

Create synthetic dataset:

np.random.seed(12345)
x = np.linspace(-1, 1, 30)
p0 = np.array([3, 2])
y = model(x, *p0)
s = 0.1 * np.ones_like(y)
n = s * np.random.normal(size=y.size)
yn = y + n

Fit parameters and get correct parameters Covariance matrix:

popt, pcov = optimize.curve_fit(model, x, yn, sigma=s, absolute_sigma=True)
# (array([3.02853144, 2.02814927]),
#  array([[0.00059905, 0.00013131],
#         [0.00013131, 0.00059905]]))

You can found details in documentation for sigma and absolute_sigma switches.