python中线性回归等于零的情况下,如何求最后一个x值
假设我有一些数据,我可以用scipy.stats.linregresse计算斜率 例如:python中线性回归等于零的情况下,如何求最后一个x值,python,numpy,scipy,Python,Numpy,Scipy,假设我有一些数据,我可以用scipy.stats.linregresse计算斜率 例如: import numpy as np from scipy import stats data = np.array([1, 2, 3, -1, -2, -7, -8, 6, 11]) x = np.arange(len(data)) slope = stats.linregress(x, data)[:1] 如你所见,我可以得到线性回归的斜率; 但是我想给数据加上一个x值,使斜率等于零 我如何解决这个
import numpy as np
from scipy import stats
data = np.array([1, 2, 3, -1, -2, -7, -8, 6, 11])
x = np.arange(len(data))
slope = stats.linregress(x, data)[:1]
如你所见,我可以得到线性回归的斜率;
但是我想给数据加上一个x值,使斜率等于零
我如何解决这个问题?谢谢我从这里得到了坡度的数学- 假设您打算:
import numpy as np
from spicy import stats
y = np.array([1,2,3,-1,-2,-7,-8,6,11])
x = np.array(range(0,len(y)))
slope = stats.linregress(x,y).slope
对于上面的设置,您希望在y
上附加一个值,并将x
修改为新的np.array(range(0,len(y))
,这样回归的新斜率将等于0
。那么,计算附加到y
的额外数字实际上非常简单
使用上面链接中提供的斜率(b
)公式,并执行以下操作:
import numpy as np
from spicy import stats
y = np.array([1,2,3,-1,-2,-7,-8,6,11])
x = np.array(range(0,len(y)))
slope = stats.linregress(x,y).slope
n
替换为(n+1)
(n+1)
添加到总和(x)
i
添加到sum(y)
(n+1)i
添加到总和(x*y)
i
的方程,你就会得到你需要的方程来计算这个值。这就是它的作用:
In [1]: import numpy as np
...: from scipy import stats
In [2]: y = data = np.array([1,2,3,-1,-2,-7,-8,6,11])
In [3]: x = np.array(range(0,len(data)))
In [4]: n = len(data)
In [5]: slope = stats.linregress(x,y).slope
In [6]: slope
Out[6]: 0.4
In [11]: def append_computer(x,y):
...: n = len(x)
...: m = n+1
...: if ((m**2) - sum(x) - m) > 0:
...: num = (-1*m*(sum(x*y))+(sum(x)*sum(y))+m*sum(y))/((m**2) - sum(x) - m)
...: return num
...: else:
...: raise ValueError(f"Solution not possible")
In [12]: stats.linregress(np.append(x,n+1), np.append(y,append_computer(x,y))).slope
Out[12]: 0.0
你的例子毫无意义。你需要一个
x
和一个y
来做线性回归。拦截有什么限制吗?顺便说一句,这更像是一个数学问题,而不是一个编程问题。您的示例出现了一个错误,因为您没有提供任何y数据的scipy.stats.linregresse
。哇~~~~~@Aryan Jain真棒!链接中的公式正是我想要找到的,谢谢