Is it possible to get the cor-variance matrix or std of fitting parameters?

Hi All,

I tried to use the astropy.modeling package for data fitting. I want to get the cor-variance matrix and standard deviation of fitted parameters.

I have been searching for a while but failed to get any progress. The FittableModel class (which is a derived class of astropy.modeling.Model) does have the attribute named as “cov_matrix”. I am not sure if this is the cor-variance matrix I want to get. But when I check this attribute after the fitting, it is always the value “None”.

Even though, the only explanation I can find about this attribute is “Fitter should set covariance matrix, if available”. I really don’t understand what the “if available” means. From my understanding, any fitting using the Least-Square should always have the cor-variance matrix for those fitted parameters if succeed.

Does anybody know how this attribute should be used? Thanks a lot !

Thanks @XingZhe, this might actually a good question to raise as an Issues · astropy/astropy · GitHub.

Before sending you down that route, could you run the following snippet and reply with the output.

import platform; print(platform.platform())
import sys; print("Python", sys.version)
import numpy; print("Numpy", numpy.__version__)
import erfa; print("pyerfa", erfa.__version__)
import astropy; print("astropy", astropy.__version__)
import scipy; print("Scipy", scipy.__version__)
import matplotlib; print("Matplotlib", matplotlib.__version__)

Also, do you have a Minimum Working Example you could share?

What do yo mean by cor-variance matrix ?

Some of the astropy fitters (LinearLSQFitter, LevMarLSQFitter) should indeed provide a cov_matrix attribute, and the error on each parameter should be available as model.param.std. I tested recently and it worked, though it’s an undocumented feature.

Oh I guess I know why you get None. The fitter must be initialized with calc_uncertainties=True, e.g. with the example from the documentation main page:

In [  ]: import numpy as np
    ...: import matplotlib.pyplot as plt
    ...: from astropy.modeling import models, fitting
    ...: 
    ...: # define a model for a line
    ...: line_orig = models.Linear1D(slope=1.0, intercept=0.5)
    ...: 
    ...: # generate x, y data non-uniformly spaced in x
    ...: # add noise to y measurements
    ...: npts = 30
    ...: np.random.seed(10)
    ...: x = np.random.uniform(0.0, 10.0, npts)
    ...: y = line_orig(x)
    ...: y += np.random.normal(0.0, 1.5, npts)
    ...: 
    ...: # initialize a linear fitter
    ...: fit = fitting.LinearLSQFitter(calc_uncertainties=True)
    ...: 
    ...: # initialize a linear model
    ...: line_init = models.Linear1D()
    ...: 
    ...: # fit the data with the fitter
    ...: fitted_line = fit(line_init, x, y)

In [16]: fitted_line.cov_matrix
Out[16]: 
parameter variances / covariances 
slope    | 0.004
intercept| -0.018,  0.117

In [17]: fitted_line.slope.std
Out[17]: 0.059648658135164186