OLS of statsmodels does not work with inversely proportional data?(statsmodels 的 OLS 不适用于成反比的数据?)
问题描述
我正在尝试使用一些成反比的数据执行普通最小二乘回归,但似乎拟合结果是错误的?
I'm trying to perform a Ordinary Least Squares Regression with some inversely proportional data, but seems like the fitting result is wrong?
import statsmodels.formula.api as sm
import numpy as np
import matplotlib.pyplot as plt
y = np.arange(100, 0, -1)
x = np.arange(0, 100)
result = sm.OLS(y, x).fit()
fig, ax = plt.subplots(nrows=1, ncols=1, figsize=(20, 4), sharey=True)
ax.plot(x, result.fittedvalues, 'r-')
ax.plot(x, y, 'x')
fig.show()
推荐答案
您没有添加常量作为 文档建议,因此它试图将整个内容设为 y = mx
.您最终会得到一个 m
大约为 0.5,因为它正在尽其所能,因为您必须在 0 处为 0,等等.
You're not adding a constant as the documentation suggests, so it's trying to fit the whole thing as y = m x
. You wind up with an m
which is roughly 0.5 because it's doing the best it can, given that you have to be 0 at 0, etc.
以下代码(注意导入的变化)
The following code (note the change in import as well)
import statsmodels.api as sm
import numpy as np
import matplotlib.pyplot as plt
y = np.arange(100, 0, -1)
x = np.arange(0, 100)
x = sm.add_constant(x)
result = sm.OLS(y, x).fit()
fig, ax = plt.subplots(nrows=1, ncols=1, figsize=(10, 8), sharey=True)
ax.plot(x[:,1], result.fittedvalues, 'r-')
ax.plot(x[:,1], y, 'x')
plt.savefig("out.png")
生产
系数为 [ 100. -1.]
.
这篇关于statsmodels 的 OLS 不适用于成反比的数据?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:statsmodels 的 OLS 不适用于成反比的数据?


基础教程推荐
- Plotly:如何设置绘图图形的样式,使其不显示缺失日期的间隙? 2022-01-01
- 求两个直方图的卷积 2022-01-01
- 使用大型矩阵时禁止 Pycharm 输出中的自动换行符 2022-01-01
- PermissionError: pip 从 8.1.1 升级到 8.1.2 2022-01-01
- PANDA VALUE_COUNTS包含GROUP BY之前的所有值 2022-01-01
- 在同一图形上绘制Bokeh的烛台和音量条 2022-01-01
- 在Python中从Azure BLOB存储中读取文件 2022-01-01
- 无法导入 Pytorch [WinError 126] 找不到指定的模块 2022-01-01
- 包装空间模型 2022-01-01
- 修改列表中的数据帧不起作用 2022-01-01