Skip to content

ENH: Replace patsy with formulaic #6858

Closed

Description

@bashtage

Formulaic is a rewrite of patsy that has been designed for more extensibility. It already has features that patsy doesn't such as sparse array support. Should consider moving to this when it is a bit more mature.

https://github.com/matthewwardrop/formulaic

Activity

  1. changed the title [-]Consider moving from patsy to formulaic[/-] [+]ENH: Replace patsy with formulaic[/+] on Jul 6, 2020
  2. ChadFulton commented on Jul 7, 2020

    @ChadFulton
    Member

    I don't use these features much, but I think it's great that there's a new project that might push formulas forward a bit more.

  3. josef-pkt commented on Jul 7, 2020

    @josef-pkt
    Member

    It would be great to have an alternative to patsy especially one that avoids eval and where formula information can be pickled.

  4. rluedde commented on Jul 7, 2020

    @rluedde

    @josef-pkt This Stack Overflow Post describes pickling as

    the process whereby a Python object hierarchy is converted into a byte stream

    What is the purpose of pickling a formula in the case of statsmodels? It seems similar to how custom Javscript objects can simply be represented in JSON. Is that a fair comparison?

  5. josef-pkt commented on Jul 7, 2020

    @josef-pkt
    Member

    Pickling is the simplest way to store python objects in a file or to transmit python objects between threads or processes.

    The main use case for statsmodels users is to store a model so it can later be used for prediction. This works with arrays and dataframes but not when patsy formulas are used. As a workaround we are rebuilding the design matrix, exog, from the formula.
    e.g. #2469

    Prediction, when formulas are used, needs to go through patsy to create the design matrix for the prediction exog from data in the original format.

  6. rluedde commented on Jul 7, 2020

    @rluedde

    Why can't you simply write a formula out as a string? Is a formula in this sense something along the lines of y ~ x1 + x2? Or does a formula encompass all weights/coefficients/betas etc after fitting/training?

    @josef-pkt What did you mean by this:

    We "fixed" the formula pickling by rebuilding from the model (exog) from the original dataframe.

    Why are Wilkinson formulas preferred? Is the alternative to use features as *args and formulas are more explicit?

  7. josef-pkt commented on Jul 7, 2020

    @josef-pkt
    Member

    It's not the formula itself that cannot be pickled, It's all the information associate with the formula information about how the design matrix was built, and how new design matrices with the same structure can be built.

    Why are Wilkinson formulas preferred? Is the alternative to use features as *args and formulas are more explicit?

    I never really looked at the details. The main point is that formulas are a short hand notation for defining a model. All other options require the user to specify a lot more explicitly.

    Statsmodels uses a more limited set of formula features compared to R, e.g. our Mixed Models don't put the random effects specification inside the formula as R does, and we don't use multi-part formulas.

  8. rluedde commented on Jul 7, 2020

    @rluedde

    So are patsy/formulaic libraries that translate formulas into instructions for building design matrices?

    Statsmodels uses a more limited set of formula features compared to R, e.g. our Mixed Models don't put the random effects specification inside the formula as R does, and we don't use multi-part formulas.

    Is this a choice made by statsmodels or is it due to limitations of patsy?

  9. josef-pkt commented on Jul 7, 2020

    @josef-pkt
    Member

    So are patsy/formulaic libraries that translate formulas into instructions for building design matrices?

    Yes, and build the design matrix, and provide information about the design matrix that we can use for example for hypothesis tests.

    Is this a choice made by statsmodels or is it due to limitations of patsy?

    Mostly our choice. Beyond the basic formulas, formulas start to become cryptic. Being more explicit in those cases, makes it easier to understand if you are not a formula expert.
    (There are many cases where I don't know what an R formula actually means and does.)

    Partially it's also that we have more control over parts that don't go through patsy. Especially because we don't have a maintainer anymore that also contributes to patsy (or whose work on patsy is getting merged).

  10. rluedde commented on Jul 7, 2020

    @rluedde

    Gotcha.

    @josef-pkt @bashtage You both have been very helpful to me, so thank you guys.

  11. bashtage commented on Jul 7, 2020

    @bashtage
    MemberAuthor

    Is this a choice made by statsmodels or is it due to limitations of patsy?

    In linearmodels I use some custom specifications that go beyond Patsy. I manually parse these. It would be nice to ultimately have a more integrated approach. For example, in instrumental variable models, which are estimated using 2 regressions, I use a formula like

    y ~ 1 + x1 + x2 + x3 + [x4 + x5 ~ z1 + z2 + z3]
    

    where the [ ] formula indicates that endogenous variables and instruments and the remaining variables are exogenous.

    In panel models I use keywords like

    y ~ x1 + EntityEffects
    

    where EntityEffects tells me that the model should include an entity (fixed) effects.

  12. rluedde commented on Jul 8, 2020

    @rluedde

    @bashtage Why is linearmodels seperate from statsmodels? Is linearmodels more specifically for finance?

  13. bashtage commented on Jul 8, 2020

    @bashtage
    MemberAuthor

    statsmodels base structure is too rigid to reliably accommodate data structures that do not resemble a single series.

  14. 15 remaining items

  15. matthewwardrop commented on Apr 28, 2023

    @matthewwardrop

    Thanks for your reply, and for calling out the various interesting pieces. I'll set about putting up a PR that adds optional support for formulaic sometime between now and shortly after formulaic 1.0.0 is released. I can't guarantee any timelines (I have four kids, and life is busy at work too), but I will do it.

    I've left a few notes about various things inline below. When we get closer / during the PR I may have other questions/comments, but we can deal with that then.

    * `t_test`, `wald_test` require building linear constraint matrices (does not use formula information, and so works as long as patsy is installed)
    

    Formulaic also implements linear constraint matrices, though this has so far evaded the documentation. This was initially requested by linearmodels.

    * missing handling in `from_formula` and `predict` includes several workarounds for patsy's automatic dropping of rows with missing/nan values.
    

    This is customizable in formulaic, you can optionally drop nan rows (the default), raise exceptions, or ignore and propagate them. Will have to see if those modes are sufficient.

    * dropping intercept: we have two models, OrderedModel and ???, that cannot have an explicit or implicit intercept. We drop an explicit intercept and, AFAIR, update the formula info (design_info)
    

    Appending a +0 or -1 to any incoming formula should guarantee this. Will investigate why/if this is the case here.

    I think we will not be able to drop patsy anytime soon, both for backwards compatibility and for missing features in formulaic like splines.

    Is the set of required functionality from patsy unit tested? Formulaic is highly compatible with patsy, and only misses from patsy the natural and cyclic cubic spline implementations, and tensor smoothing. Orthogonal polynomial bases (not implemented by patsy) and basis splines are supported. None of the missing transforms are challenging to add if they are blockers. But I agree that some amount of transition period would like be required.

    * updating formula if we need to drop a term, e.g. dropping intercept, empty cell column,
    

    This is technically straightforward if a bit of a chore, but we could definitely add some helper methods to simplify things.

    * bonus: dropping a term would be nice for some use cases (but I don't remember where I wanted this). Currently, we don't provide or update formula info if we have to change the model matrix internally.
    

    This should be easier in Formulaic since the formula is a first class entity that is designed to be mutated. But... we shall see if it caters to your use-cases.

    * a list of column names in the original dataframe of variables actually used in creating the design matrix (exog).  (I guess, this might not be available in all cases if user uses functions in the formula that are `eval`ed.)
    

    This is about to be added. Turned out to be pretty straightforward.

    The derivative of the formula transform from original data to design/model matrix would be very useful, but difficult to get. My latest attempt was to use the transform as black box and use numerical derivatives #5387 (comment)

    Interesting. I also added to formulaic symbolic differentiation of model matrices using sympy. I also intended to add finite differencing support... but since then I have become less convinced of the approach and utility (internally at work we marginalise over the delta of model matrices explicitly, which works fine if being slightly less computationally efficient than computing the categorical delta during factor evaluation). I'd be curious to see if either or both of these would be helpful to statsmodels.

    (*) e.g. #7609 We currently do not have any code to automatically create penalization for terms specified in a formula. It's impossible or difficult to get the relevant information from the formula/design info. GAM implements penalization for a term that is defined outside of the formula. Additionally, our spline code, initially copied from patsy, includes additional methods to compute the penalization terms.

    Definitely curious about this one. I have in mind to add support for transforms that extended terms and/or formulae with metadata that can be used during modelling... but I will dig into this use-cases a bit more before over-promising! It's definitely a possibility!

  16. josef-pkt commented on Apr 28, 2023

    @josef-pkt
    Member

    comment to just one item

    • dropping intercept: we have two models, OrderedModel and ???, that cannot have an explicit or implicit intercept. We drop an explicit intercept and, AFAIR, update the formula info (design_info)

    Appending a +0 or -1 to any incoming formula should guarantee this. Will investigate why/if this is the case here.

    The problem for this in patsy is that if there are categorical variables, then -1 adds the implicit intercept to the categorical encoding, e.g. does not drop any reference level.
    This is even worse for us because we can remove an explicit constant but not an implicit constant.

  17. matthewwardrop commented on Apr 29, 2023

    @matthewwardrop

    The problem for this in patsy is that if there are categorical variables, then -1 adds the implicit intercept to the categorical encoding, e.g. does not drop any reference level.
    This is even worse for us because we can remove an explicit constant but not an implicit constant.

    Ah... yes, Formulaic will do that too by default. Will see what can be done when we get to that chunk of code :).

  18. josef-pkt commented on Apr 29, 2023

    @josef-pkt
    Member

    one more issue that I had forgotten

    • pickle support for models: because patsy's design_info cannot be pickled, we have to rebuild it from the original formula and data during unpickling of a model. The tricky part was getting the evalenv level.

    I guess it will be a lot of work to fully switch to formulaic.
    However, we can take time for the transition, as long as users have the option to use patsy instead of formulaic.
    I will be glad once we have the core support for formulaic, so we can gain some experience with it.

    And then we can start using features that formulaic has but patsy does not, like supporting sparse design matrices.

  19. mgorny commented on Nov 30, 2023

    @mgorny
    Contributor

    At this point, Patsy seems to be broken with Python 3.12.

  20. matthewwardrop commented on Dec 25, 2023

    @matthewwardrop

    Hi all! Circling back around to this now that Formulaic 1.0.0 has been published. Hopefully I can put up an initial PR soon.

  21. josef-pkt commented on Nov 14, 2024

    @josef-pkt
    Member

    @matthewwardrop

    I was looking at our t_test_pairwise again that computes all pairwise hypothesis tests for one factor in a design matrix.
    This needs to know the encoding contrast matrix that was used in the formula.
    I'm not able to find that information in the formulaic ModelSpec.
    Is this somewhere available and accessible?

    current code for patsy
    cm = desinfo.term_codings[term][0].contrast_matrices[factor].matrix
    I had to drill through patsy design_info attributes to find this.
    The contrast matrix is used to build the all pairs constraints for any constrast that was used for the one factor in the formula.

  22. matthewwardrop commented on Nov 16, 2024

    @matthewwardrop

    Hi @josef-pkt !

    No, currently Formulaic does not persist the model matrices used during encoding for categorical factor terms. You could re-evaluate the encoder, but then you'd need to pass around the original data vectors, which isn't ideal. I'll update formulaic (hopefully this weekend) to store the metadata required to surface these more conveniently. I won't store the matrices themselves (since ModelSpec is supposed to be as light as possible while still encoding all choices), but I'll make it possible to easily generate them.

  23. matthewwardrop commented on Nov 18, 2024

    @matthewwardrop

    @josef-pkt This is now fixed in matthewwardrop/formulaic#204 .

    For example:

    model_spec.factor_contrasts["<factor str repr>"].get_coding_matrix()
    

    Note that this does not track whether the factor was actually rendered in reduced or full-rank form, since that is ambiguous even within a single term. I presume this is equivalent to patsy, since patsy pioneered the methodology that formulaic also leverages regarding whether to encode the factor with reduced rank or not.

    Let me know if you need anything else; but the above will be released as part of Formulaic 1.1 shortly.

  24. memeplex commented on Jul 8, 2026

    @memeplex

    I see a lot of formulaic related stuff in statsmodels.formula._manager. Perhaps it's already supported, isn't it? In that case it's not clear to me how to use it, maybe setting statsmodels.formula.formula_options.engine? I wasn't able to find any documentation.

  25. bashtage commented on Jul 8, 2026

    @bashtage
    MemberAuthor

    That's correct. There is also an environmental variable. We really need a release with release notes.

  26. memeplex commented on Jul 8, 2026

    @memeplex

    Looking at the DEFAULT_FORMULA_ENGINE setting code:

    try:
        import patsy
        DEFAULT_FORMULA_ENGINE = DEFAULT_FORMULA_ENGINE or "patsy"
        ...
    except ImportError:
        DEFAULT_FORMULA_ENGINE = DEFAULT_FORMULA_ENGINE or "formulaic"    [1]
    
    try:
        import formulaic
         <---- [1]
        ...
    except ImportError:
        pass

    AFAICU DEFAULT_FORMULA_ENGINE is the initial value for statsmodels.formula.formula_options.engine.

    1. Probably by design, but since patsy is a dependence of statsmodels only by explicitly removing it after statsmodels installation may formulaic be selected as default.
    2. I think [1] should go inside the formulaic try/except block.
  27. bashtage commented on Jul 30, 2026

    @bashtage
    MemberAuthor

    @memeplex Took a while but I see the point of your comment and this has been corrected.

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