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 不适用于成反比的数据?


基础教程推荐
- Python,确定字符串是否应转换为 Int 或 Float 2022-01-01
- 比较两个文本文件以找出差异并将它们输出到新的文本文件 2022-01-01
- 究竟什么是“容器"?在蟒蛇?(以及所有的 python 容器类型是什么?) 2022-01-01
- 对多索引数据帧的列进行排序 2022-01-01
- Python 中是否有任何支持将长字符串转储为块文字或折叠块的 yaml 库? 2022-01-01
- matplotlib 设置 yaxis 标签大小 2022-01-01
- kivy 应用程序中的一个简单网页作为小部件 2022-01-01
- Kivy 使用 opencv.调整图像大小 2022-01-01
- 在 Python 中将货币解析为数字 2022-01-01
- 在 Django Admin 中使用内联 OneToOneField 2022-01-01