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
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.
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?
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.
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?
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.
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?
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).
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.
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!
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.
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 :).
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.
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.
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.
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.
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.
AFAICU DEFAULT_FORMULA_ENGINE is the initial value for statsmodels.formula.formula_options.engine.
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.
I think [1] should go inside the formulaic try/except block.
Activity
[-]Consider moving from patsy to formulaic[/-][+]ENH: Replace patsy with formulaic[/+]ChadFulton commentedon Jul 7, 2020
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.
josef-pkt commentedon Jul 7, 2020
It would be great to have an alternative to patsy especially one that avoids
evaland where formula information can be pickled.rluedde commentedon Jul 7, 2020
@josef-pkt This Stack Overflow Post describes pickling as
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?
josef-pkt commentedon Jul 7, 2020
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.
rluedde commentedon Jul 7, 2020
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:
Why are Wilkinson formulas preferred? Is the alternative to use features as
*argsand formulas are more explicit?josef-pkt commentedon Jul 7, 2020
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.
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.
rluedde commentedon Jul 7, 2020
So are patsy/formulaic libraries that translate formulas into instructions for building design matrices?
Is this a choice made by statsmodels or is it due to limitations of patsy?
josef-pkt commentedon Jul 7, 2020
Yes, and build the design matrix, and provide information about the design matrix that we can use for example for hypothesis tests.
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).
rluedde commentedon Jul 7, 2020
Gotcha.
@josef-pkt @bashtage You both have been very helpful to me, so thank you guys.
bashtage commentedon Jul 7, 2020
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
where the
[ ]formula indicates that endogenous variables and instruments and the remaining variables are exogenous.In panel models I use keywords like
where
EntityEffectstells me that the model should include an entity (fixed) effects.rluedde commentedon Jul 8, 2020
@bashtage Why is linearmodels seperate from statsmodels? Is linearmodels more specifically for finance?
bashtage commentedon Jul 8, 2020
statsmodels base structure is too rigid to reliably accommodate data structures that do not resemble a single series.
15 remaining items
matthewwardrop commentedon Apr 28, 2023
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
formulaicsometime 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.
Formulaic also implements linear constraint matrices, though this has so far evaded the documentation. This was initially requested by
linearmodels.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.
Appending a
+0or-1to any incoming formula should guarantee this. Will investigate why/if this is the case here.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.This is technically straightforward if a bit of a chore, but we could definitely add some helper methods to simplify things.
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.
This is about to be added. Turned out to be pretty straightforward.
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.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!
josef-pkt commentedon Apr 28, 2023
comment to just one item
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.
matthewwardrop commentedon Apr 29, 2023
Ah... yes, Formulaic will do that too by default. Will see what can be done when we get to that chunk of code :).
josef-pkt commentedon Apr 29, 2023
one more issue that I had forgotten
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.
mgorny commentedon Nov 30, 2023
At this point, Patsy seems to be broken with Python 3.12.
matthewwardrop commentedon Dec 25, 2023
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.
josef-pkt commentedon Nov 14, 2024
@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].matrixI 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.
matthewwardrop commentedon Nov 16, 2024
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
ModelSpecis supposed to be as light as possible while still encoding all choices), but I'll make it possible to easily generate them.matthewwardrop commentedon Nov 18, 2024
@josef-pkt This is now fixed in matthewwardrop/formulaic#204 .
For example:
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.
memeplex commentedon Jul 8, 2026
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 settingstatsmodels.formula.formula_options.engine? I wasn't able to find any documentation.bashtage commentedon Jul 8, 2026
That's correct. There is also an environmental variable. We really need a release with release notes.
memeplex commentedon Jul 8, 2026
Looking at the
DEFAULT_FORMULA_ENGINEsetting code:AFAICU
DEFAULT_FORMULA_ENGINEis the initial value forstatsmodels.formula.formula_options.engine.patsyis a dependence ofstatsmodelsonly by explicitly removing it afterstatsmodelsinstallation mayformulaicbe selected as default.formulaictry/except block.bashtage commentedon Jul 30, 2026
@memeplex Took a while but I see the point of your comment and this has been corrected.