Data fitting with fit uncertainties

This started out as a way to make sure I understood the numpy array slicing methods, and builds on my previous post about using scipy to fit data. I define a 3 parameter exponential decay

    \[\mathrm{func}(x, a, b, c) = a e^{-b x} + c\]

add some gaussian noise, and then use scipy to get the best fit as well as the covariance matrix. My understanding is that the square root of the diagonal elements gives me the 1 \sigma uncertainty on the corresponding fit parameter. So I then use the uncertainties on a, b, c to compute all 8 possible effective parameter values and their corresponding fit arrays.

I then use numpy to find the standard deviation of the 8 different fit values at each x, and use this as the 1\;\sigma uncertainty on the fit at a given x. Once I have this array of fit uncertainties, I plot the best fit curve, the fit+ 1\sigma curve, the fit - 1\sigma curve, and use the matplotlib plot.bar( ) function to plot the \pm 3\sigma bars.

In any case, here is the script: CurveFitting.py , and here is an iPythonNotebook with some exposition: CurveFitWith1SigmaBand.ipynb .

Here is the final plot: (click on plot to see .pdf version)

About PaulNakroshis

Professor of Physics at the University of Southern Maine.
This entry was posted in curve fitting, data analysis, error bars, iPython, Matplotlib, Plotting. Bookmark the permalink.

4 Responses to Data fitting with fit uncertainties

  1. Justin says:

    Hello, I would like to know if i can use this image in teaching material to discuss scatter graphs and best fitting?

  2. Dhuicque says:

    Hello,

    I would like to adapt your code for my data. I have measured data, I fit my curve with fit_curve in Python. I have the best fitting curve at the end of my code. And I calculate sigma that is the standard deviation. But I don’t know if in order to have the +1sigma curve I have to add this sigma to the measured curve or to the best fitting curve. Can you help with this ?

    Best

    • PaulNakroshis says:

      I would take the sigma values you obtain for each fit parameter and plot two extra curves:
      One where you add or subtract (as needed) the sigma values to their related best fit values to get the largest value to plot, and
      Another where you do the opposite. For example, if you fit y = a*x – b/x) to some data and determine best fit values for a and b, then
      I’d plot the best fit curve along with two others: (1) (a+da)*x – (b-db)/x and (2) (a-da)*x – (b+db)/x
      In general, this can get complicated, so another method would be to use transparency and plot all possible combination of fit parameters as error margin curves.

Leave a Reply

Your email address will not be published. Required fields are marked *

*

This site uses Akismet to reduce spam. Learn how your comment data is processed.