Skip to content

ENH/Design: support for spline-dummy interaction in penalized/GAM #5332

Open

Description

@josef-pkt

R mgcv has a by option for the interaction effect of penalized splines and a categorical variables.

I don't know yet how we will support this. patsy can create the interaction term using its splines.

two cases (that I can think of)

  • spline has full support for each categorical level
  • categorical level partitions the support of the explanatory variable in the spline, e.g. regression continuity design.

I think the former should be easy using standard interaction (like kronecker product for unbalanced dummies).
The latter will be more difficult because the spline cannot be estimated in the unobserved part.
I have a simple example without penalization in the causal impact, synthetic control PR #3647, or in one of the related experimental notebooks.

Activity

  1. added this to the 0.11 milestone on Oct 20, 2018
  2. josef-pkt commented on Nov 14, 2018

    @josef-pkt
    MemberAuthor

    (random thoughts)

    using interaction effect with dummy directly, i.e. we create two variables
    z1 = dummy * x and z0 = (1 - dummy) * x

    this means part of the new variable will be zeros. We cannot include those zeros when we create the spline basis, i.e. we would need to have a ignore_zeros option.

    We can do it if we use the spline basis for the x, in that case we just compute a usual interaction variable on parts of exog.

    The two cases above would need 2 options for knot selection when creating the spline basis

    • common knots: impose similar spline structure or identical basis functions (although evaluated at different points) for all by categorical subsets.
    • separate knots: choose knots separately as if the non-zero observations were the entire series represent different variables, e.g. each subset has separate restriction on boundary knots as for example
      the natural spline restrictions of zero second derivative at the end knots.
    • variation on separate knots: we could choose separate spline basis but impose additional restrictions on the join or jump point, for example identical first and second derivatives.

    The second two might be applicable to regression continuity design and structural change with jump points.

    A corresponding option is on penalization or smoothing parameter choice

    • common alpha/penalization weight: we impose equal penalization to avoid divergent smoothness across categorical variable interaction
    • separate, independent alpha: subsets can have different smoothness, i.e. penalization adapts to subset.

    mgcv allows the common alpha case in the options for GAM, i.e. add an index that maps from alpha list to the list of smooth terms.

    related: varying coefficient models which are essentially also just interaction effects. I have not looked at those yet.

    two possible example:

    • growth curves by gender with common support in age variable
    • structural break at known strict threshold value of the explanatory variable: e.g. intervention analysis (e.g. ENH: causal impact, synthetic control #3647 causal impact and synthetic control) or regression continuity design.

    one alternative in the structural change, regression discontinuity case:
    We could add only a mean shift dummy. If we use a local spline basis like B-splines with drop one basis column for removing intercept, then the shape of the curves (including the mean shift variable) in the two segments would be mostly independent of each other, i.e. restricted to common penalization and spill over across knots in transition segment.

  3. josef-pkt commented on Feb 9, 2019

    @josef-pkt
    MemberAuthor

    just another example: cyclical time series, e.g.

    • El Nino dataset with annual seasonal pattern, each year is a spline

    • within day, e.g. hourly, data with weekly cyclical pattern, each day is a spline

    • pooled model; every cycle is the same, i.e. every year or every day has same pattern
      this is currently possible

    • separate model: e.g. estimate each year separately, or estimate data for all weeks for each weekday separately
      currently possible but no commonality across separate regression

    • interaction model: each year or each weekday is a separate spline, and eg. parametric intercept or trend common to all sub splines.
      problems with zeros in dummy/period and spline interaction, we need spline bases that don't include the zero (not it interval) as a value, i.e. the spline basis at zero should be zero.

    Our current implementation cannot construct spline bases ignoring some of the observations, e.g. the zero observation.
    Our current implementation cannot reuse and shift splines, e.g. with equal time interval the time variable is the same for all subunits and we could just shift and transpose it instead of constructing in each time separately (scipy.signal did and maybe still does that)

    ideas

    • add a mask to indicate which subset of observation the spline basis should be constructed for.
    • reusable spline basis for common (affine transformed) exog:
      • construct canonical spline basis and project actual values like trend/period into that interval.
  4. modified the milestones: 0.11, josef on Oct 5, 2019
  5. david-waterworth commented on Jan 10, 2025

    @david-waterworth

    @josef-pkt I assume this hasn't progressed, I'm wondering if you can suggest a good reference on how to implement a design matrix for the "interaction model" case - i.e. I have energy consumption data by period and want to model E = s(T, by="d") - I've naively generated a single matrix for each level of d, zero'd out the rows where the level of d isn't applicable but my understanding is this isn't how mgcv does it.

  6. josef-pkt commented on Jan 13, 2025

    @josef-pkt
    MemberAuthor

    I have not gone back to this in some time and don't remember enough details.
    Also, I never worked on finding a working solution or prototype for interaction effects.
    So, unfortunately I cannot help here before I go back to work on this.

    AFAIU, you have a continuous variables T modeled by spline but interacted with a discrete variable d, i.e. separate spline coefficients for each level. Is that correct?

    Do you know what patsy is doing with categorical-spline interaction?

    two ways I can think of:

    • separately compute spline basis function for each subset of continuous x
    • compute spline basis function for all x values and then interact basis function with the categorical (i.e. zero out the observations that have different levels)

    version 2 sounds better because we have the same spline across levels of categorical which makes it easier to compare across levels.
    The disadvantage is that we might not have enough/any observations for some spline basis functions, e.g. if there is not enough overlap in the continuous exog by groups x * d_i. (e.g. patsy requires boundary of spline knots at observed max and min of x).

    (For penalization splines, i.e. penalization on diff params, we could get penalized params even at empty set which would be completely determined by penalization between neighboring params. I'm not sure what happens in the standard second derivative penalization if a spline basis function is "empty".
    )

  7. david-waterworth commented on Jan 15, 2025

    @david-waterworth

    Yeah I'm trying to model the response of energy consumption to temperature, which changes over seasons (i.e. in general high or low temperature results in higher energy consumption compared to average temperature - kind of a V or U shaped response - but in summer we also tend to observe higher energy consumption at the same temperature than in winter (maybe higher solar irradiance, or maybe tenants are changing energy setpoints with seasons, or some a/c is locked out in winter etc)

    Playing around with patsy, what I observe is energy ~ bs(temperature, df=3, degree=1, include_intercept=True):C(month) results in 3 terms for each level, and the basis is constructed from knots derived from the min(temperature) / max(temperature) over the entire dataset. So some of the segments probably don't have observations for temperature:month in the dataset (not many 40 degree days in winter in Sydney)

    Still this seems to work ok in this application- i.e. roughly if the response simply shifts up/down with the level of the categorical, or the steepness changes but the general shape remains the same. Where I guess it fails is if the shape stays consistent but it's location shifts left/right on the x-axis - since the knots don't move.

    I implemented your first version manually (but I used formulaic and get a different basis for the same expression so I need to look into that) because I realised that I also want to ignore one of the levels (I'm using two categorical, on which represents on/off so Izero out any temperature contribution in the "off" state - although ignoring this doesn't break anything as far as I can see.

  8. josef-pkt commented on Jan 15, 2025

    @josef-pkt
    MemberAuthor

    Thanks for looking at this.
    If you have enough observation, a relative smooth nonlinearity, than using fewer knots would not require penalization.
    (I compared penalized and non-penalized splines in several examples and the non-penalized results look fine in those cases.)

    another idea for "empty cells or columns":

    If we use the same knots and therefore meaning of params across categorical levels, then we could penalize the parameter for a basis function to the mean (or simila) of the parameter across levels.
    Then we would have double penalization across knots and across levels. We would need two penalization weights to control the two penalization terms separately.

    We would have to use the penalized mixin directly or add an extra penalization option to GLMGAM.

    (Aside: do we already have a penalization to mean contrast/constraint?)

    Another thought:
    AFAIU/IIRC penalization is not invariant to linear transformation of the basis functions if we don't make a equivalent linear transformation of the penalty terms, specifically the interaction should not be invariant to the encoding of the categorical variable.
    For example using a main effect and pure interaction effect could have lower penalization on the main effect, and interaction effects would be just the diff with higher penalization that can force more smoothness or smaller params if there is little information about the diff.
    Cell mean (no main effect) parameterization, would penalize each spline by categorical levels separately and each would have the reduced information.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions