You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
SUMM/DOC/ENH interaction between continuous, categorical exog #5387
general issue: I have no idea how well this works, and AFAIK we don't have an example
How well does patsy handle this? What is the parameterization? Which collinear columns are dropped?
post-estimation support
so far we have nothing, AFAIK
wald tests, nothing specific,
wald_test_terms should work if names or terms have a identifiable structure
premade specific tests for interaction effects, e.g. diff across categorical levels
wald test restriction matrix for diff should be just two calls to np.eye or diag with the right indices
(I'm doing something similar for zero tests in GAM test_significance)
margins, partial predict: nothing yet. We need information about underlying variables
graphics, plots: also nothing yet. We still don't have interaction plots that work for models neither for categorical nor for categorical-continuous interaction.
We might have enough information in the design_info to support this when formulas are used.
interaction exog columns created by statsmodels:
GAM in mgcv has a by option to split estimate and interaction between smooth component and categorical variable ENH/Design: support for spline-dummy interaction in penalized/GAM #5332
I don't know (yet) how we should handle collinear columns in this case, e.g. main effect plus "left-over" interaction effect, or only full interaction effects. : versus * in formulas.
changed the title [-]SUMM/DOC/ENH interaction between continuous and categorical exog[/-][+]SUMM/DOC/ENH interaction between continuous, categorical exog[/+]on Aug 17, 2022
(changed name to make it clearer that this includes continuous-continuous and categorical-categorical interactions)
lsmeans, emmeans, margins in R and margins in Stata handle interaction terms.
Several references for the background for treating interaction terms, TBA.
We still don't have helper code to identify interactions and their type in the design matrix, formula.
supporting code: _wald_nonlinear, and DeltaCov can be used for nonlinear functions, once those are appropriately specified.
bump for adding public get_prediction_nonlinear for user specified functions,
all internal code is available and currently used internally for the nonlinear get_prediction which
in GLM type models, one-parameter LEF with link function including those in discrete.
The formula or user specified nonlinearity or interactions are in the linear predictor. So this part is the same for OLS/WLS as for GLM and discrete models and can share the code.
The marginal effect on predicted mean of endog (conditional expectation) is included in the generic code.
We can use an identity link for linear models or write specific code for the linpred/linear model part.
Multilink models like BetaModel and future multi-link models, will be more difficult to handle (except as very general DeltaCov version) because the marginal effect depends on the exogs of all distribution parameters. Also the nonlinear target function could include common exog across the different linpred, e.g. if mean and variance/precision depend on the same parameter.
Similarly, in hurdle model the current specification requires that the exog in the two submodels are the same.
after playing around a bit using _get_wald_nonlinear:
function and derivatives based on linear predictor are still linear in parameters. That means, we can just use t_test, same as using t_test for prediction. _get_wald_nonlinear and t_test produce the same result in this case.
GLM, discrete models also need to take nonlinear mean function (inverse link) into account
GLM, OLS are missing helper method _derivative_exog to compute margins using get_wald_nonlinear as it is possible with discrete models like poisson.
to 1: Some time ago there was a question on stackoverflow that did this, compute margins with t_test. (I don't find it anymore)
related: one of my answer for discrete change in exog, compare prediction using t_test https://stackoverflow.com/a/30970690/333700
(edit this is a good example because it uses patsy to create the designmatrix from original observations, see later comments)
One question is what tools we can provide to convert derivatives w.r.t. exog to derivatives w.r.t params needed for multi-column margins. In discrete models, I had used _derivative_exog to replicate margins/get_margeff with _get_wald_nonlinear .
Also, from this it looks like we might want to distinguish between linear (t_test) and nonlinear (wald_nonlinear, DeltaCov) versions for this, in analogy to the different base get_prediction methods.
One problem is that it is difficult or impossible to get the information for dx2/dx1 (or similar) from the formula, or more general derivative with respect to original data, linear term x1 might not even be one of the columns, e.g. if we don't include main effect.
linear in parameters
It should still true that margin at mean is the same as mean of margin over sample in cases where margins are linear in parameters. Averaging can be left at the preparation stage, i.e. creating the relevant coefficients for linear in parameter representation.
nonlinear in parameters (e.g. nonlinear link)
Average margin over the sample is not the same as margin at mean. The current get_wald_nonlinear does not do any averaging. Averaging needs to be inside the function provided to wald_nonlinear.
In the current implementation, base get_prediction_delta creates the function for wald_nonlinear that includes averaging of the nonlinear terms if required.
another one: transformed exog, transformed endog, which is nonlinear in x even in OLS.
for example log transformed x = log(z) is captured in margeff by the (semi-)elasticities dyex
This case is still linear in parameters and t_test works for it.
I tried it out for the linear case, and t_test, get_prediction and _get_wald_nonlinear all produce the same result.
from my dev notebook
## x is a transformed variable
suppose x1 = log(z1), no multicolumn effect
We want to know marginal effect of z1 on outcome which is the derivative d E(y | x) / d z1.
dx1 / dz1 = d log(z1) / d z1 = 1 / z1
assume mean function is linear in x, y = a x, then
dy / dx1 = a1
dy / dz1 = a1 * dx1 / dz1 = a1 / z1
This is a linear function in parameter a1 with coefficient 1 / z1.
So, we can use t_test or get_prediction for inference.
We continue with example and assume weight was measured in log units.
We can recover the original units z1 = exp(x1)
We ignore the interaction effect for now.
The index of weight in the design matrix and params is 2. Then we can build a constraint matrix that has the coefficients for marginal effect in column for weight and zeros everywhere else.
another thought (I will not look into this for now)
using patsy's predict transform
When formulas are used, then patsy transforms the orginal data to the design matrix compatible data in predict. This also preserves stateful transforms and consistent coding for categorical variables and interactions.
predict(ex, transform=True) includes a function that maps original data to design data, it's a black box for us and partially for patsy (parts hiding in eval).
We could take a numerical derivative of this and we would get derivative of predicted value with respect to original data.
One problem is that we also need the derivative with respect to params for delta method. That are two numerical derivatives, which I guess is the second cross derivative d^2 predicted / (d exog d params )
maybe that can be implemented
the user needs to provide
exog_original_predict in a pandas dataframe or dict
the key, name of original variable w.r.t. which we want the derivative
then need two derivatives
marginal effect: dy /dz where y is predicted and z is original colum. R -> R
derivative of a function with one outcome w.r.t params, R^k -> R, that can be used for delta method covariance, this is the second cross-derivative
all possibly vectorized over observations or rows
We currently don't have a numdiff function for computing cross-derivatives. also needed for #8421
The main computational issue might be the choice of eps for finite-step approximation of second cross-derivative
update
I guess we can add a method like _deriv_design_data or _deriv_exog_data, and optionally let users provide a function as alternative.
We still need something for categorical variables and interactions.
e.g. _diff_design_data with two arrays for comparing prediction of two exog, predict(x_cat = "a") - predict(x_cat = "b")
It's not actually a diff of exog, we need two exog in nonlinear case, so _diff_design_data is not directly the analogue of _deriv_design_data.
This could also works for numeric data for discrete changes predict(x1 = x1+1) - predict(x1 = x1)
margin w.r.t categorical, dummy including interactions:
we can go through formula to compare two predictions, user needs to specify which exog/original variable to change.
Margin for predict at cat="a" minus predict at cat="b".
This would be similar to current margin for dummy variable which compares dummy=1 with dummy=0.
Current margin for count variable adds 1 to exog for difference in prediction.
Comparing predictions would work generically with _wald_nonlinear as long as we have a function to compute diff of two predictions.
Using formulas, we need to manipulate the original (pandas) data.
aside:
current margeff uses explicit derivative for margins w.r.t dummy variable using _derivative_predict which is essentially the same as _deriv_mean_dparams with additional exog and transform (ey) handling.
With interaction effects and formulas, we cannot use generic analytical derivatives, i.e. we need numdiff.
Activity
[-]SUMM/DOC/ENH interaction between continuous and categorical exog[/-][+]SUMM/DOC/ENH interaction between continuous, categorical exog[/+]josef-pkt commentedon Aug 17, 2022
(changed name to make it clearer that this includes continuous-continuous and categorical-categorical interactions)
lsmeans, emmeans, margins in R and margins in Stata handle interaction terms.
Several references for the background for treating interaction terms, TBA.
We still don't have helper code to identify interactions and their type in the design matrix, formula.
supporting code: _wald_nonlinear, and DeltaCov can be used for nonlinear functions, once those are appropriately specified.
josef-pkt commentedon Oct 10, 2022
another question for marginal effect of a interacted variable
https://stats.stackexchange.com/questions/591541/inference-in-logistic-regression-with-feature-cross-non-linear-terms/591585#591585
similarly, a few days ago for ols
https://stackoverflow.com/questions/73964039/statsmodels-get-margeff-for-ols
bump for adding public get_prediction_nonlinear for user specified functions,
all internal code is available and currently used internally for the nonlinear get_prediction
whichjosef-pkt commentedon Oct 10, 2022
in GLM type models, one-parameter LEF with link function including those in discrete.
The formula or user specified nonlinearity or interactions are in the linear predictor. So this part is the same for OLS/WLS as for GLM and discrete models and can share the code.
The marginal effect on predicted mean of endog (conditional expectation) is included in the generic code.
We can use an identity link for linear models or write specific code for the linpred/linear model part.
Multilink models like BetaModel and future multi-link models, will be more difficult to handle (except as very general DeltaCov version) because the marginal effect depends on the exogs of all distribution parameters. Also the nonlinear target function could include common exog across the different linpred, e.g. if mean and variance/precision depend on the same parameter.
Similarly, in hurdle model the current specification requires that the exog in the two submodels are the same.
josef-pkt commentedon Oct 12, 2022
after playing around a bit using
_get_wald_nonlinear:_get_wald_nonlinearandt_testproduce the same result in this case._derivative_exogto compute margins using get_wald_nonlinear as it is possible with discrete models like poisson.to 1: Some time ago there was a question on stackoverflow that did this, compute margins with t_test. (I don't find it anymore)
related: one of my answer for discrete change in exog, compare prediction using t_test
https://stackoverflow.com/a/30970690/333700
(edit this is a good example because it uses patsy to create the designmatrix from original observations, see later comments)
One question is what tools we can provide to convert derivatives w.r.t. exog to derivatives w.r.t params needed for multi-column margins. In discrete models, I had used
_derivative_exogto replicate margins/get_margeff with_get_wald_nonlinear.Also, from this it looks like we might want to distinguish between linear (t_test) and nonlinear (wald_nonlinear, DeltaCov) versions for this, in analogy to the different base get_prediction methods.
josef-pkt commentedon Oct 12, 2022
(from my current dev notebook:)
edit my notebook seems to have been
try_margin_extended.ipynbmulticolumn margins
suppose variable at index 2 is quadratic of variable at index 1, x2 = x1**2
Let x0 be all other variables, z0 be all variables.
g is mean function (inverse link)
conditional expectation, predicted mean
mism = g(x0 + x1 + x1**2)
dm/dx1 = g'(z0) * (dz/dx1 + dz/dx2 * dx2/dx1)
= g'(z0) * (a1 + a2 * 2 * x1)
in example, we have dy/dx_i = g'(.) * a_i, which is
_derivative_exogin discreteso
dm/dx1 = dy/dx1 + dy/dx2 * dx2/dx1
= dy/dx1 + dy/dx2 * 2 * x1
One problem is that it is difficult or impossible to get the information for dx2/dx1 (or similar) from the formula, or more general derivative with respect to original data, linear term x1 might not even be one of the columns, e.g. if we don't include main effect.
josef-pkt commentedon Oct 12, 2022
aggregation, average=True:
linear in parameters
It should still true that margin at mean is the same as mean of margin over sample in cases where margins are linear in parameters. Averaging can be left at the preparation stage, i.e. creating the relevant coefficients for linear in parameter representation.
nonlinear in parameters (e.g. nonlinear link)
Average margin over the sample is not the same as margin at mean. The current
get_wald_nonlineardoes not do any averaging. Averaging needs to be inside the function provided to wald_nonlinear.In the current implementation, base get_prediction_delta creates the function for wald_nonlinear that includes averaging of the nonlinear terms if required.
josef-pkt commentedon Oct 12, 2022
example for margins with interaction effect of two continuous variables
for linear models or linear predictor in link or single index models
derivative dspeed / d length at grid of weight
josef-pkt commentedon Oct 13, 2022
another one: transformed exog, transformed endog, which is nonlinear in x even in OLS.
for example log transformed x = log(z) is captured in margeff by the (semi-)elasticities dyex
This case is still linear in parameters and t_test works for it.
I tried it out for the linear case, and
t_test,get_predictionand_get_wald_nonlinearall produce the same result.from my dev notebook
josef-pkt commentedon Oct 13, 2022
another thought (I will not look into this for now)
using patsy's
predict transformWhen formulas are used, then patsy
transformsthe orginal data to the design matrix compatible data inpredict. This also preserves stateful transforms and consistent coding for categorical variables and interactions.predict(ex, transform=True)includes a function that maps original data to design data, it's a black box for us and partially for patsy (parts hiding ineval).We could take a numerical derivative of this and we would get derivative of predicted value with respect to original data.
One problem is that we also need the derivative with respect to params for delta method. That are two numerical derivatives, which I guess is the second cross derivative
d^2 predicted / (d exog d params )maybe that can be implemented
the user needs to provide
then need two derivatives
all possibly vectorized over observations or rows
We currently don't have a numdiff function for computing cross-derivatives. also needed for #8421
The main computational issue might be the choice of eps for finite-step approximation of second cross-derivative
josef-pkt commentedon Jan 25, 2023
another stackexchange question
margins for binary treatment effect for linpred of poisson
https://stats.stackexchange.com/questions/602929/computing-the-standard-error-of-a-marginal-effect
josef-pkt commentedon Mar 20, 2023
two references, high number of citations
Ai, Chunrong, and Edward C. Norton. “Interaction Terms in Logit and Probit Models.” Economics Letters 80, no. 1 (July 1, 2003): 123–29. https://doi.org/10.1016/S0165-1765(03)00032-6.
Greene, William. “Testing Hypotheses about Interaction Terms in Nonlinear Models.” Economics Letters 107, no. 2 (May 1, 2010): 291–96. https://doi.org/10.1016/j.econlet.2010.02.014.
josef-pkt commentedon Mar 23, 2023
I just saw that we have a previous issue for linear model
#6479
josef-pkt commentedon Apr 27, 2023
quick try, seems to work
derivative of design_matrix w.r.t a continuous variable (not categorical)
(my notebook is try_deriv_formula.ipynb
update
I guess we can add a method like
_deriv_design_dataor_deriv_exog_data, and optionally let users provide a function as alternative.We still need something for categorical variables and interactions.
e.g.
_diff_design_datawith two arrays for comparing prediction of two exog,predict(x_cat = "a") - predict(x_cat = "b")It's not actually a diff of exog, we need two exog in nonlinear case, so
_diff_design_datais not directly the analogue of_deriv_design_data.This could also works for numeric data for discrete changes
predict(x1 = x1+1) - predict(x1 = x1)josef-pkt commentedon May 18, 2023
margin w.r.t categorical, dummy including interactions:
we can go through formula to compare two predictions, user needs to specify which exog/original variable to change.
Margin for predict at cat="a" minus predict at cat="b".
This would be similar to current margin for dummy variable which compares dummy=1 with dummy=0.
Current margin for count variable adds 1 to exog for difference in prediction.
Comparing predictions would work generically with
_wald_nonlinearas long as we have a function to compute diff of two predictions.Using formulas, we need to manipulate the original (pandas) data.
aside:
current margeff uses explicit derivative for margins w.r.t dummy variable using
_derivative_predictwhich is essentially the same as_deriv_mean_dparamswith additional exog and transform (ey) handling.With interaction effects and formulas, we cannot use generic analytical derivatives, i.e. we need numdiff.
maybe: name
get_margeff_formula