statsmodels的OLS为何不适用于反比例数据?

0 投票
1 回答
821 浏览
提问于 2025-04-18 13:08

我正在尝试用普通最小二乘法回归一些成反比例的数据,但好像得到的结果不太对?

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()

plot

1 个回答

1

你没有按照文档的建议添加一个常数,所以它试图把整个公式拟合成 y = m x。最后你得到的 m 大约是 0.5,因为在这种情况下,它尽力而为,考虑到你在 0 的时候结果也必须是 0,等等。

下面的代码(注意导入部分的变化)

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")

会产生

plot showing the match

其系数为 [ 100. -1.]

撰写回答