Repository navigation
ENH: Abstract formula engine - #9423
Conversation
|
Nice! Thanks for working on this @bashtage ! A year or more ago I spent a couple of hours starting an abstraction like this, but never got around to finishing it. I'll take a closer look at this shortly, but from a quick pass it all looks great! |
|
Hello @bashtage! Thanks for updating this PR. We checked the lines you've touched for PEP 8 issues, and found:
Comment last updated at 2024-11-13 10:53:05 UTC |
1a37dbc to
eafc4a9
Compare
| """ | ||
| from statsmodels.discrete.diagnostic import ( | ||
| PoissonDiagnostic) | ||
| from statsmodels.discrete.diagnostic import PoissonDiagnostic |
Check notice
Code scanning / CodeQL
Cyclic import
| import pandas as pd | ||
| from scipy import optimize | ||
|
|
||
| from statsmodels.base._penalized import PenalizedMixin |
Check notice
Code scanning / CodeQL
Cyclic import
| import warnings | ||
|
|
||
| import statsmodels.genmod.families.varfuncs as varfuncs | ||
| from statsmodels.genmod.generalized_linear_model import GLM, GLMResults |
Check notice
Code scanning / CodeQL
Cyclic import
| _get_dummy_index, _get_count_index) | ||
| ) | ||
| # used for wrapper: | ||
| import statsmodels.regression.linear_model as lm |
Check notice
Code scanning / CodeQL
Cyclic import
| LC = DesignInfo(names).linear_constraint(['a + b = 0', 'a + 2*c = 1', 'b-a', 'c-a', 'd-a']) | ||
| #LC = DesignInfo(self.model.exog_names).linear_constraint(r_matrix) | ||
| r_matrix, q_matrix = LC.coefs, LC.constants | ||
| lc = mgr.get_linear_constraints('a + b = 0', names) |
Check warning
Code scanning / CodeQL
Variable defined multiple times
| r_matrix, q_matrix = LC.coefs, LC.constants | ||
| lc = mgr.get_linear_constraints('a + b = 0', names) | ||
| lc = mgr.get_linear_constraints(['a + b = 0', 'a + 2*c = 1', 'b-a', 'c-a', 'd-a'], names) | ||
| r_matrix, q_matrix = lc.constraint_matrix, lc.constraint_values |
Check notice
Code scanning / CodeQL
Unused global variable
| r_matrix, q_matrix = LC.coefs, LC.constants | ||
| lc = mgr.get_linear_constraints('a + b = 0', names) | ||
| lc = mgr.get_linear_constraints(['a + b = 0', 'a + 2*c = 1', 'b-a', 'c-a', 'd-a'], names) | ||
| r_matrix, q_matrix = lc.constraint_matrix, lc.constraint_values |
Check notice
Code scanning / CodeQL
Unused global variable
Add patsy and formulaic aware formula engine abstraction
b593018 to
8e2bd64
Compare
a14c4c1 to
27b390d
Compare
| scipy>=1.8,!=1.9.2 # released Feb 2022, 1.9.2 blocked due to bug | ||
| pandas>=1.4,!=2.1.0 # released Feb 2022, 2.1.0 blocked due to bug | ||
| patsy>=0.5.6 # released December 2023 | ||
| formulaic>=1.0.2 # released June 2024 |
There was a problem hiding this comment.
Thanks. All comments and reviewed are appreciated. 👍
matthewwardrop
left a comment
There was a problem hiding this comment.
Hi @bashtage ! Thanks so much for doing this work... it's definitely a heavier lift than I realised it would be, so I'm glad I don't have to do it!
Since this is an unsolicited review, I didn't go into too much depth, but I left a few (hopefully helpful) comments.
| """ | ||
| return cls(lc.coefs, lc.constants, lc.variable_names) | ||
| try: | ||
| return cls(lc.constraint_matrix, lc.constraint_values, lc.variable_names) |
There was a problem hiding this comment.
Is it worth doing explicit type-checks here? If not, probably worth adding some comments as to why this works.
| if _engine == "patsy" and not HAVE_PATSY: | ||
| raise ImportError(f"patsy {msg_base}.") | ||
| elif not HAVE_FORMULAIC: | ||
| raise ImportError(f"formulaic {msg_base}.") |
There was a problem hiding this comment.
Would tell you to install patsy when formulaic is not available. Is that the desired behaviour?
There was a problem hiding this comment.
It should only do this if you request formulaic and it isn't installed. If you request it and have patsy then it should work. I need to write some separate tests for this.
| _ordering = statsmodels.formula.options.ordering | ||
| _formula = formulaic.formula.Formula(formula, _ordering=_ordering) | ||
| output = formulaic.model_matrix(_formula, data, context=eval_env, **kwargs) | ||
| if isinstance(output, formulaic.ModelMatrices): |
There was a problem hiding this comment.
There are other ways that ModelMatrices can be output; for example if multipart formulae are being used. Maybe check explicitly for lhs and rhs being present? And maybe raise an error if ModelMatrices is returned otherwise (until statmodels knows how to handle it)?
There was a problem hiding this comment.
Does Model matrices support len? Might be good to raise for len >2 if it did.
There was a problem hiding this comment.
Yes, it does support len; but there are many ways that it can have length two that might be surprising. For example: x | y would also have length two.
I plan to add a way to restrict the kinds of formulae that can be created in the upcoming Formula 1.1, which may help here.
There was a problem hiding this comment.
| """ | ||
| return self._spec | ||
|
|
||
| def get_arrays( |
There was a problem hiding this comment.
nit: This name feels a bit weird to me, since it implies (to me) that the output would be numpy arrays, when in fact the default output is a pandas dataframe. Perhaps get_matrices?
| ) | ||
| else: # self._engine == "formulaic" | ||
|
|
||
| # Handle list of constraints, which is not supported by formulaic |
There was a problem hiding this comment.
This is an oversight. I'll add support for this in formulaic-next.
| list[Term] | ||
| The terms with the intercept removed, if present. | ||
| """ | ||
| intercept = self.intercept_term |
There was a problem hiding this comment.
question: removing the intercept term does not mean that generated matrices will not span the intercept; both patsy and formulaic will, in the absence of an intercept, expand categorical factors to span the intercept. How is that being handled?
There was a problem hiding this comment.
TBH I'm not that worried about this - it is mostly to deal with code that exists that someone else wrote a long time ago. It is only used in 1 place for anova, and then only to loop over columns that aren't the intercept. It isn't used to construct a model matrix.
There was a problem hiding this comment.
In models where we cannot have an intercept like OrderedModel, we require users when using formulas to use an explicit intercept that we remove internally.
That means that the remaining variables are by construction not spanning the intercept.
(patsy does not have an option to exclude explicit and implicit intercepts)
There was a problem hiding this comment.
(fwiw, if it ever became sufficiently desirous to have this built into a formula parser, I'd be open to considering how best achieve it; but this seems like a reasonable approach for now)
| if self._engine == "patsy": | ||
| return patsy.ModelDesc.from_formula(formula) | ||
| else: | ||
| return formulaic.Formula(formula) |
There was a problem hiding this comment.
if you want to be able to set other parts of the spec, you can also do: ModelSpec(formula=formula).
There was a problem hiding this comment.
I tried this initially but get the somewhat cryptic error
ValueError: Nominated `Formula` instance has structure, which is not permitted when attaching to a `ModelSpec` instance.
There was a problem hiding this comment.
Ah... whoops. To support nested formulae as well you'd want: ModelSpec.from_spec(formula); which then returns a ModelSpecs instance as necessary.
commented
Dec 2, 2024
|
ok, thanks |
commented
Dec 2, 2024
|
I browsed through anova_lm and t_test_pairwise looks great, |
| def missing_mask(self): | ||
| return self._missing_mask | ||
|
|
||
| def _legacy_orderer( |
There was a problem hiding this comment.
- If this is trying to reproduce
patsy's ordering, you should be able to just do:Formula(<formula>).get_model_matrix(data, cluster_by="numerical_factors")
There was a problem hiding this comment.
So far this exactly reproduced patsy's ordering in every specification I have tried. I'll run it through the test suite and see if I can match.
There was a problem hiding this comment.
I gave this a go using
for order in ("none", "sort", "degree"):
formulaic.Formula(formula, _ordering=order).get_model_matrix(data, cluster_by="numerical_factors")
and none were exactly able to match patsy's ordering.
I'm not too surprised given how many hoops I had to jump through to get it to work.
My plan is to move away from legacy order so that "legacy" it will be deprecated as soon as possible so that this code can eventually go away and only be left with the in-built options in formulaic.
| df = getattr(output, key) | ||
| df.index = replacement_index | ||
| if isinstance(output, formulaic.ModelMatrices): | ||
| if ( |
There was a problem hiding this comment.
You can now just do: if not isinstance(SimpleFormula):
There was a problem hiding this comment.
Do you mean isinstance(output.model_spec.formula, SimpleFormula)?
| from formulaic.parser.types.factor import Factor | ||
| from formulaic.parser.types.term import Term | ||
|
|
||
| return Term((Factor("1"),)) |
There was a problem hiding this comment.
Since you are only using this to check for equality, you can actually just return "1" here.
| else: | ||
| cat = self.get_factor_categories(factor, model_spec) | ||
| reduced_rank = True | ||
| for ts in model_spec.structure: |
There was a problem hiding this comment.
This won't work in general; since a term may consist of the product of than one categorical variable.
In the past I toyed with the notion of adding a helper method for this, but looking at this code maybe I should have just done it. I could add a method model_spec.get_factor_contrasts_for_term(....); the final code could then be: model_spec.get_factor_contrasts_for_term(term)[factor].get_coding_matrix()... but there's a problem with this ...
Suppose you have a formula: 1 + A:B, with A and B being categorical variables. Under the hood (in both patsy and formulaic), this will be cast into: 1 + A- + A:B- (with the minus indicating reduced rankness). So the "term" A:B expands into two terms B- and A-:B, in which B is encoded differently. Therefore there is in general no single encoding of categorical factors per term. The algorithm used above for patsy is therefore "wrong", since it assumes reduced rank even where it is not universally true.
If you want to ignore this wrinkle, adding a method like that above is pretty trivial; since we store the scoping of factors in these expanded forms; e.g.:
import formulaic
import pandas
mm = formulaic.model_matrix("1 + A:B", pandas.DataFrame({"A": list("abc"), "B": list("def")}))
mm.model_spec.structure[1]
This outputs:
EncodedTermStructure(term=A:B, scoped_terms=[B-, A-:B], columns=['B[T.e]', 'B[T.f]', 'A[T.b]:B[d]', 'A[T.c]:B[d]', 'A[T.b]:B[e]', 'A[T.c]:B[e]', 'A[T.b]:B[f]', 'A[T.c]:B[f]'])
where term is the original term, scoped_terms describes how it is expanded, and columns indicates the set of columns resulting from these scoped terms.
I'm not exactly sure what to do with this. Perhaps @josef-pkt has thoughts?
There was a problem hiding this comment.
The problem is that I don't know what to do with interaction terms.
I have several open issues to support both categorical-categorical and categorical-continuous interactions, e.g.
For t_test_pairwise, predict and marginal/predicitive effects, one requirement for categorical-categorical interaction would be to get all cell means, e.g. partial exog for the columns with possibly setting other columns to prespecified values.
One option I thought about is to automatically create artificial datasets, but I never tried to figure out how to do this with patsy, e.g. #8439 #7071 #8746 and more
There are several post-estimation results that need more information about the structure of terms in the design matrix. But those are currently not supported.
Currently only anova_lm and t_test_pairwise use term information, and t_test_pairwise is restricted to a single factor.
commented
Dec 3, 2024
|
@bashtage Once you've got this ready to your satisfaction, let me know... and I'll take a closer look (likely mainly at the |
0aaed55 to
0525943
Compare
0525943 to
0094813
Compare
| """ | ||
| types = ["None", "NaN"] if types is _NoDefault else types | ||
| if self._using_patsy: | ||
| return NAAction(on_NA=action, NA_types=types) |
Check failure
Code scanning / CodeQL
Wrong name for an argument in a class instantiation
3ae9a5e to
1af1160
Compare
| f""" | ||
| Get the model matrices or design matrices from a formula and data. | ||
|
|
||
| Parameters | ||
| ---------- | ||
| formula : str, Formula | ||
| The formula to use. | ||
| data : DataFrame, dict, list, recarray | ||
| The data to use when evaluating the formula. | ||
| eval_env : {int, dict} | ||
| Additional context to use when evaluating the formula. | ||
| pandas : bool | ||
| Return a DataFrame if true, otherwise return a numpy array. | ||
| na_action : {NAAction, str} | ||
| The action to take on missing values. | ||
| prediction : bool | ||
| True if using the formula for prediction. In this case, only the | ||
| rhs is evaluated using data. | ||
|
|
||
| Returns | ||
| ------- | ||
| tuple[DataFrame, ...], tuple[ndarray, ...], tuple[DesignMatrix, ...] | ||
| If pandas is True, returns one or more DataFrames. If False, | ||
| returns a NumPy ndarray (formulaic) or a DesignMatrix (patsy). | ||
| """ |
Check notice
Code scanning / CodeQL
Statement has no effect
Ensure statsmodels can run with only 1 of the engines available
ccf4a6a to
89d82e1
Compare
Add patsy and formulaic aware formula engine abstraction
NumPy's guide.
Details
Notes:
needed for doc changes.
then show that it is fixed with the new code.
verify you changes are well formatted by running
flake8is installed. This command is also available on Windowsusing the Windows System for Linux once
flake8is installed in thelocal Linux environment. While passing this test is not required, it is good practice and it help
improve code quality in
statsmodels.