I have a dataframe df
with the following fields: weight
, length
, and animal
. The first 2 are continuous variables, while animal
is a categorical variable with the values cat
, dog
, and snake
.
I'd like to estimate a relationship between weight and length, but this needs to be conditioned on the type of animal, so I interact the length variable with the animal
categorical variable.
model = ols(formula='weight ~ length * animal', data=df)
results = model.fit()
How can I programmatically extract the slope of the relationship between weight and length for e.g. snakes? I understand how to do this manually: add the coefficient for length
to the coefficient for animal[T.snake]:length
. But this is somewhat cumbersome and manual, and requires me to handle the base case specially, so I'd like to extract this information automatically.
Furthermore, I'd like to estimate the error on this slope. I believe I understand how to calculate this by combining the standard errors and covariances (more precisely, performing the calculation here). But this is even more cumbersome than the above, and I'm similarly wondering if there's a shortcut to extract this information.
My manual method to calculate these follows.
EDIT (06/22/2015): there seems to be an error in my original code below for calculating errors. The standard errors as calculated in user333700's answer are different from the ones I calculate, but I haven't invested any time in figuring out why.
def get_contained_animal(animals, p):
# This relies on parameters of the form animal[T.snake]:length.
for a in animals:
if a in p:
return a
return None
animals = ['cat', 'dog', 'snake']
slopes = {}
errors = {}
for animal in animals:
slope = 0.
params = []
# If this param is related to the length variable and
# the animal in question, add it to the slope.
for param, val in results.params.iteritems():
ac = get_contained_animal(animals, param)
if (param == 'length' or
('length' in param and
ac is None or ac == animal)):
params.append(param)
slope += val
# Calculate the overall error by adding standard errors and
# covariances.
tot_err = 0.
for i, p1 in enumerate(params):
tot_err += results.bse[p1]*results.bse[p1]
for j, p2 in enumerate(params[i:]):
# add covariance of these parameters
tot_err += 2*results.cov_params()[p1][p2]
slopes[animal] = slope
errors[animal] = tot_err**0.5
This code might seem like overkill, but in my real-world use case I have a continuous variable interacting with two separate categorical variables, each with a large number of categories (along with other terms in the model that I need to ignore for these purposes).
Very brief background:
The general question for this is how does the prediction change if we change on of the explanatory variables, holding other explanatory variables fixed or averaging over those.
In the nonlinear discrete models, there is a special Margins method that calculates this, although it is not implemented for changes in categorical variables.
In the linear model, the prediction and change in prediction is just a linear function of the estimated parameters, and we can (mis)use
t_test
to calculate the effect, its standard error and confidence interval for us.(Aside: There are more helper methods in the works for statsmodels to make prediction and margin calculations like this easier and will be available most likely later in the year.)
As brief explanation of the following code:
Finally, I compare with the result from predict to check that I didn't make any obvious mistakes. (I assume this is correct but I had written it pretty fast.)
The result of the last print is
We can verify the results by using predict and compare the difference in predicted weight if the length for a given animal type increases from 1 to 2:
Note: I forgot to add a seed for the random numbers and the numbers cannot be replicated.