python - 如何在python中线性回归等于零的条件下求解最后一个x值
问题描述
假设我有一些数据,我可以用 scipy.stats.linregress 计算斜率,例如:
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]
如您所见,我可以得到线性回归的斜率;但我想将 ax 值附加到数据以使斜率等于零我如何解决这个 x ?谢谢
解决方案
我从这里得到了我的斜率数学 - https://www.statisticshowto.datasciencecentral.com/probability-and-statistics/regression-analysis/find-a-linear-regression-equation/#FindaLinear
假设您打算执行以下操作:
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
) 并执行以下操作:
- 替换
n
为(n+1)
- 添加
(n+1)
到sum(x)
- 将未知变量添加
i
到sum(y)
- 添加
(n+1)i
到sum(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
推荐阅读
- react-native - 如何使用 yup 验证 useRef 对象?
- ios - 在 React Native(iOS)中从 LTR 更改为 RTL 后,抽屉滑轨不起作用
- optimization - 如何使用遗传算法优化模糊逻辑控制器的参数?
- java - JavaMailSender:身份验证失败
- python - 在带有 PyQt5 的 qml 中使用 ApplicationWindow 会导致空白窗口,但没有它的相同代码不会
- .net-assembly - 程序集引用与找到的程序集定义不匹配 - 对于 System.Threading.Tasks.Extensions,版本 = 4.2.0.0
- javascript - 数据存储在 My Sql 数据库中,但对密码进行哈希处理时出错
- oracle-sqldeveloper - 未在 oracle Sql 开发人员中与 group by 一起使用
- java - 收集 WeakHashMap 的条目时,如何对值进行一些清理?
- cryptography - 我为 DigiByte 生成了一对密钥,公钥与 DogeCoin 钱包的公钥匹配。那是问题吗?