Repository navigation
BUG: Build the regressors of formula predictions with the model's specification - #884
Conversation
…cification predict with data evaluated the formula again on the new data, so formulaic took the state of stateful transforms, such as center or scale, and the levels of categorical variables from the new data and not from the estimation data. Predictions from formulas with stateful transforms were silently wrong, and new data without every level of a C() term raised an error about the number of columns. The formula parsers of the IV, panel and system models keep the ModelSpec of each variable that they build, from_formula stores them on the model, and predict builds the regressors with them. Setting formula clears them.
Codecov Report❌ Patch coverage is
Additional details and impacted files@@ Coverage Diff @@
## main #884 +/- ##
==========================================
- Coverage 99.69% 99.68% -0.01%
==========================================
Files 202 204 +2
Lines 38871 39118 +247
Branches 2501 2514 +13
==========================================
+ Hits 38752 38996 +244
- Misses 51 52 +1
- Partials 68 70 +2
Flags with carried forward coverage won't be shown. Click here to find out more. ☔ View full report in Codecov by Harness. 🚀 New features to boost your workflow:
|
bashtage
left a comment
There was a problem hiding this comment.
Thanks, this is a real fix. predict(data=...) after from_formula evaluated the formula on the new data, so stateful transforms used the mean, scale or knots of the new data and categorical variables used its levels. Against the in-sample design, main is off by up to 10.3 with center, scale, bs or poly, and silently wrong for a categorical with a different category order, in the IV, panel and system models; this PR is exact, and in-sample results are unchanged.
-
Release note, under "Changes that alter results":
- ``predict`` with ``data`` of a model created with ``from_formula`` builds the regressors with the specification of the estimation data. Stateful transforms, such as ``center``, ``scale``, ``bs`` and ``poly``, use the mean, scale, knots and coefficients of the estimation data, and categorical variables keep its levels. 7.1 evaluated the formula again on the new data, so that predictions with a stateful transform were wrong, new data without every level of a categorical variable raised an error, and new data whose levels differ in order or set were silently encoded with the wrong columns. New data with a level that is not in the estimation data raises a ``ValueError``. The IV, panel and system models are affected (:issue:`884`).
-
A
.. versionchanged:: 7.2in the Notes of thepredictmethods of the IV, panel and system models (and preferably their results):.. versionchanged:: 7.2 With ``data``, the regressors are built with the categories and the state of the stateful transforms, such as ``center``, of the estimation data. They were built from ``data`` alone.
-
A level that isn't in the estimation data is encoded as the base level with formulaic's
DataMismatchWarning, which makes the predictions for those rows wrong. Please raise aValueErrorthat names the variable and the new levels instead (the note above assumes this), with a test.
Optional: the predict path of a curly-brace string system formula isn't tested (passing no specs on the string branch leaves every test passing). Parametrizing test_system over the dict and the equivalent "{y ~ ...} {y2 ~ ...}" formula would cover it.
predict with data builds a categorical variable with the levels of the estimation data, and formulaic encoded a level that is not one of them as the base level, with a DataMismatchWarning, so that the predictions for its rows were wrong. The formula parsers of the IV, panel and system models now raise a ValueError that names each variable and its new levels. A missing value is not a new level and keeps the warning of formulaic.
Add the note to the changes that alter results of 7.2, and a versionchanged to the Notes of predict of the IV, panel and system models and of their results.
Parametrize test_system over the dict of formulas and the equivalent
"{y ~ ...} {y2 ~ ...}" string, whose parser builds the equations in
another branch.
|
Thanks for the review. The three points and the optional test are in new commits on top of e96afab:
|
|
Thanks |
Follow-up to bashtage#884. The error of model_matrix_from_spec for new levels of categorical variables was only tested with one categorical variable, so the branch that skips a variable without new levels was not covered. With two categorical variables of which only one has new levels, the error names that variable alone. The test fails if the "if new:" check is removed.
predict(data=...)on a model created withfrom_formulaevaluated the formula again on the new data. formulaic then took the state of stateful transforms and the levels of categorical variables from the new data instead of the estimation data:center(x),scale(x),bs(x)orpoly(x)were silently wrong. For example, withIV2SLS.from_formula("y ~ 1 + center(x1) + [en ~ z]", data), predicting the first 5 rows ofdatagave 4.94, 6.56, 6.08, ... while the fitted values of the same rows are 5.04, 6.66, 6.17, ...C(...)term, for example only some categories, raised a matmul shape error in the IV models and "exog does not have the correct number of columns" in the panel models.The IV, panel and system models are all affected.
The formula parsers now keep the
ModelSpecof each block they build,from_formulastores them on the model, andpredictbuilds the new regressors withModelSpec.get_model_matrix, which reuses the levels and transform state of the estimation data. Settingformulaby hand clears the stored specs, so that case behaves as before. A level that was not in the estimation data now gives formulaic'sDataMismatchWarningand is encoded as the base level, where it previously raised a shape error.Tests: new
linearmodels/tests/test_formula_predict_new_data.pywith 14 cases (IV2SLS, IVLIML, IVGMM, IVGMMCUE, IVJIVE, the six panel models, SUR, IV3SLS, IVSystemGMM). The expected predictions are computed by hand from the parameters, withxcentered at its mean in the estimation data plus the coefficient of each level, using new data without the base level. All 14 fail on main and pass with the fix.The 37 test files under
linearmodels/teststhat usefrom_formula, a formula parser orpredictpass (8934 passed, 28 skipped).ruff check,black --checkandisort --check-onlyare clean on the changed files.