Skip to content

SUMM/DOC/ENH interaction between continuous, categorical exog #5387

Open

Description

@josef-pkt

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.

Activity

  1. changed the title [-]SUMM/DOC/ENH interaction between continuous and categorical exog[/-] [+]SUMM/DOC/ENH interaction between continuous, categorical exog[/+] on Aug 17, 2022
  2. josef-pkt commented on Aug 17, 2022

    @josef-pkt
    MemberAuthor

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

  3. josef-pkt commented on Oct 10, 2022

    @josef-pkt
    MemberAuthor

    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 which

  4. josef-pkt commented on Oct 10, 2022

    @josef-pkt
    MemberAuthor

    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.

  5. josef-pkt commented on Oct 12, 2022

    @josef-pkt
    MemberAuthor

    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.

  6. josef-pkt commented on Oct 12, 2022

    @josef-pkt
    MemberAuthor

    (from my current dev notebook:)
    edit my notebook seems to have been try_margin_extended.ipynb

    multicolumn 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 m is

    m = 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_exog in discrete
    so

    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.

  7. josef-pkt commented on Oct 12, 2022

    @josef-pkt
    MemberAuthor

    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_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.

  8. josef-pkt commented on Oct 12, 2022

    @josef-pkt
    MemberAuthor

    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

    res = OLS.from_formula("speed ~ length * weight", data).fit()
    
    dfwgrid = pd.DataFrame({"weight": np.linspace(0, 2, 5)})
    ​
    def f2inter(p):
        """
        
        c0: just param 1, effect dy/dx1
        c1: effect of partial derivatives dy/dx1 + dy/dx2 (just for checking)
        c2: effect of total derivative dy/dx1, interaction effect x3 = x1*x2, x2 is 'weight'
        """
    ​
        c0 = np.atleast_1d(p[1])
        c1 = np.atleast_1d(p[1] + p[2])
        c2 = np.atleast_1d(p[1] + p[3] * np.asarray(dfwgrid["weight"]))
        eff = np.concatenate([c0, c1, c2], axis=0)
        return eff
    ​
    marg = res._get_wald_nonlinear(f2inter)
    print(marg.summary())
                                 Test for Constraints                             
    ==============================================================================
                     coef    std err          z      P>|z|      [0.025      0.975]
    ------------------------------------------------------------------------------
    c0             1.0171      0.023     44.721      0.000       0.973       1.062
    c1             2.0514      0.043     48.244      0.000       1.968       2.135
    c2             1.0171      0.023     44.721      0.000       0.973       1.062
    c3             1.2536      0.015     85.525      0.000       1.225       1.282
    c4             1.4901      0.011    137.509      0.000       1.469       1.511
    c5             1.7265      0.015    115.098      0.000       1.697       1.756
    c6             1.9630      0.023     84.660      0.000       1.918       2.008
    ==============================================================================
    
    # using t_test
    constr = np.zeros((7, len(res.params)))
    constr[:, 1] = 1
    constr[1, 2] = 1
    constr[2:, 3] = np.asarray(dfwgrid["weight"])
    ​
    res.t_test(constr)
    <class 'statsmodels.stats.contrast.ContrastResults'>
                                 Test for Constraints                             
    ==============================================================================
                     coef    std err          t      P>|t|      [0.025      0.975]
    ------------------------------------------------------------------------------
    c0             1.0171      0.023     44.721      0.000       0.972       1.062
    c1             2.0514      0.043     48.244      0.000       1.967       2.136
    c2             1.0171      0.023     44.721      0.000       0.972       1.062
    c3             1.2536      0.015     85.525      0.000       1.225       1.283
    c4             1.4901      0.011    137.509      0.000       1.469       1.512
    c5             1.7265      0.015    115.098      0.000       1.697       1.756
    c6             1.9630      0.023     84.660      0.000       1.917       2.009
    ==============================================================================
    
  9. josef-pkt commented on Oct 13, 2022

    @josef-pkt
    MemberAuthor

    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.
    
  10. josef-pkt commented on Oct 13, 2022

    @josef-pkt
    MemberAuthor

    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

  11. josef-pkt commented on Jan 25, 2023

    @josef-pkt
    MemberAuthor
  12. josef-pkt commented on Mar 20, 2023

    @josef-pkt
    MemberAuthor

    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.

  13. josef-pkt commented on Mar 23, 2023

    @josef-pkt
    MemberAuthor

    I just saw that we have a previous issue for linear model
    #6479

  14. josef-pkt commented on Apr 27, 2023

    @josef-pkt
    MemberAuthor

    quick try, seems to work

    derivative of design_matrix w.r.t a continuous variable (not categorical)
    (my notebook is try_deriv_formula.ipynb

    def derive_formula(df, column):
        xx = df.copy()
        
        def transform(xi):
            xx.loc[:, column] = xi
            return res._transform_predict_exog(xx, transform=True)[0].T
    
        x0 = xx.loc[:, column].to_numpy()
        return smnd._approx_fprime_scalar(x0, transform).T
    

    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)

  15. josef-pkt commented on May 18, 2023

    @josef-pkt
    MemberAuthor

    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.

    maybe: name get_margeff_formula

  16. added
    topic-post_estim
    on Jun 9, 2023
  17. added this to the 0.16 milestone on Jan 24, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    comp-basedesigntopic-post_estimtype-enh

    Type

    No type

    Projects

    No projects

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions