Covariance matrix from np.polyfit() has negative diagonal?

陌路散爱 提交于 2019-12-04 22:25:45

It looks like it's related to your x values: they have a total range of about 3, with an offset of about 1.5 billion.

In your code

np.asarray(x)

converts the x values in a ndarray of float64. While this is fine to correctly represent the x values themselves, it might not be enough to carry on the required computations to get the covariance matrix.

np.asarray(x, dtype=np.float128)

would solve the problem, but polyfit can't work with float128 :(

TypeError: array type float128 is unsupported in linalg

As a workaround, you can subtract the offset from x and then using polyfit. This produces a covariance matrix with positive diagonal:

x1 = x - np.mean(x)
z1, cov1 = np.polyfit(np.asarray(x1), np.asarray(y), 1, cov=True)
std1 = np.sqrt(np.diag(cov1))

print z1    # prints: array([  1.56607841e+03,   6.31224162e+06])
print cov1  # prints: array([[  4.56066546e+00,  -2.90980285e-07],
            #                [ -2.90980285e-07,   3.36480951e+00]])
print std1  # prints: array([ 2.13557146,  1.83434171])

You'll have to rescale the results accordingly.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!