Chi square numpy.polyfit (numpy)

Can someone explain how to get Chi ^ 2 / doF using numpy.polyfit?

+7
source share
2 answers

Suppose you have some data points

x = numpy.array([0.0, 1.0, 2.0, 3.0]) y = numpy.array([3.6, 1.3, 0.2, 0.9]) 

To set the parabola to these points, use numpy.polyfit() :

 p = numpy.polyfit(x, y, 2) 

To get the chi-squared value for this fit, evaluate the polynomial in the x values ​​of your data points, subtract the y , square and sum values:

 chi_squared = numpy.sum((numpy.polyval(p, x) - y) ** 2) 

You can divide this number by the number of degrees of freedom if you want.

+15
source

Numpy polyfit has, at least since version 1.3, the supported parameter full . If this parameter is set to True , polyfit will return a few more values, including the square of residuals. This is a chi-square (not normalized by degrees of freedom).

So a simple example:

 p, residuals, _, _, _ = numpy.polyfit(x, y, 2, full=True) chisq_dof = residuals / (len(x) - 3) 

I have not tried this myself with weights, but I assume that polyfit does the right thing here (since numpy 1.7, polyfit accepts the w parameter to provide the weight to fit).

0
source

All Articles