How to get the "in-sample" predicted values (y hat) in statsmodel ols?

Viewed 824

Here is the code:

from   statsmodels.formula.api import ols
import io
import requests

url = "https://raw.githubusercontent.com/RInterested/datasets/gh-pages/mtcars.csv"
contents = requests.get(url).content
mtcars = pd.read_csv(io.StringIO(contents.decode('utf-8')))
print(mtcars.describe())
reg = ols('mpg ~ C(cyl) + wt', data=mtcars).fit() 
print(reg.summary())

This seems to return an intercept for the model, and the syntax is very similar to R, which I like. There is a reg.predict and a reg.get_predict within the print(dir(reg)), but neither one of them return the predicted values for each example (case or subject) in the dataset. It seems as though it may be waiting for an "out-of-sample" array to spit out these predicted values.

I would like to get the predicted mpg for the examples in the actual dataset plotted as points of a different color to the actual data cloud, and superimposed on the regression line:

enter image description here

1 Answers

The in-sample predictions are available as reg.fittedvalues attribute on the results instance, and when calling predict without arguments, reg.predict().

When the predict method has additional options, then those can be computed for in-sample observations by not specifying a new set of explanatory variables, exog.

Related