简体   繁体   中英

OLS of statsmodels does not work with inversely proportional data?

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

情节

You're not adding a constant as the documentation suggests , so it's trying to fit the whole thing as y = mx . 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")

produces

显示比赛的情节

with coefficients of [ 100. -1.] .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM