开发者

Chi square numpy.polyfit (numpy)

开发者 https://www.devze.com 2023-02-20 19:11 出处:网络
Could someone explain how to get Chi^2/doF usin开发者_运维技巧g numpy.polyfit?Assume you have some data points

Could someone explain how to get Chi^2/doF usin开发者_运维技巧g numpy.polyfit?


Assume 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 fit a parabola to those points, use numpy.polyfit():

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

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

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

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


Numpy's polyfit has, at least since release 1.3, supported a full parameter. If that is set to True, polyfit will return a few more values, including the square of the residuals. Which is chi-squared (unnormalized by the degrees of freedom).

So a simple example would be

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 polyfit does the right thing here (since numpy 1.7, polyfit accepts a parameter w to provide weights for the fit).

0

精彩评论

暂无评论...
验证码 换一张
取 消