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 编写 Fortran 无格式文件 2022-01-01
- Discord.py 缺少必需的参数 2022-01-01
- 将 x 轴刻度更改为自定义字符串 2022-01-01
- numpy float:比算术运算中内置的慢 10 倍? 2022-01-01
- pyserial - 可以从线程 a 写入串行端口,是否阻塞从线程 b 读取? 2022-01-01
- 与常规 dict 相比,Python manager.dict() 非常慢 2022-01-01
- 由Python将MP3转换为MIDI(类型错误:无法加载插件:mtg-Melodia:Melodia) 2022-01-01
- 尝试制作WhatsApp机器人 2022-01-01
- 在 Celery 工作人员中捕获 Heroku SIGTERM 以优雅地关 2022-01-01
- 使用生成器和迭代器时 Python 多循环失败 2022-01-01
