gpt4 book ai didi

python - 使用 numpy lstsq 计算残差

转载 作者:行者123 更新时间:2023-12-01 04:52:20 26 4
gpt4 key购买 nike

我有 x,y 数据:

import numpy as np
x = np.array([ 2.5, 1.25, 0.625, 0.3125, 0.15625, 0.078125])
y = np.array([ 2448636.,1232116.,617889.,310678.,154454.,78338.])

X = np.vstack((x, np.zeros(len(x))))
popt,res,rank,val = np.linalg.lstsq(X.T,y)
popt,res,rank,val

给我:

(array([ 981270.29919414,       0.        ]),
array([], dtype=float64),
1,
array([ 2.88639894, 0. ]))

为什么残差为零?如果我添加 1 而不是零,则计算残差:

X = np.vstack((x, np.ones(len(x)))) # added ones instead of zeros
popt,res,rank,val = np.linalg.lstsq(X.T,y)
popt,res,rank,val

(array([ 978897.28500355, 4016.82089552]),
array([ 42727293.12864216]),
2,
array([ 3.49623683, 1.45176681]))

此外,如果我在 Excel 中计算残差平方和,如果截距设置为零,则得到 9261214;如果将截距设置为 x,则得到 5478137

最佳答案

lstsq 将很难适应该零列:相应参数的任何值(大概是截距)都可以。

要将截距固定为 0,如果您需要这样做,只需发送 x 数组,但要确保它是 lstsq 的正确形状:

In [214]: popt,res,rank,val = np.linalg.lstsq(np.atleast_2d(x).T,y)
In [215]: popt
Out[215]: array([ 981270.29919414])
In [216]: res
Out[216]: array([ 92621214.2278382])

关于python - 使用 numpy lstsq 计算残差,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28155829/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com