Skip to content

BUG: Build the regressors of formula predictions with the model's specification - #884

Merged
bashtage merged 5 commits into
bashtage:mainfrom
WeiLiuu:fix-formula-predict-model-spec
Dec 3, 2026
Merged

bashtage merged 5 commits into
bashtage:mainfrom
WeiLiuu:fix-formula-predict-model-spec

Conversation

@WeiLiuu

@WeiLiuu WeiLiuu commented Nov 28, 2026

Copy link
Copy Markdown
Contributor

predict(data=...) on a model created with from_formula evaluated 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:

  • Predictions from formulas with stateful transforms such as center(x), scale(x), bs(x) or poly(x) were silently wrong. For example, with IV2SLS.from_formula("y ~ 1 + center(x1) + [en ~ z]", data), predicting the first 5 rows of data gave 4.94, 6.56, 6.08, ... while the fitted values of the same rows are 5.04, 6.66, 6.17, ...
  • New data that does not contain every level of a 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 ModelSpec of each block they build, from_formula stores them on the model, and predict builds the new regressors with ModelSpec.get_model_matrix, which reuses the levels and transform state of the estimation data. Setting formula by hand clears the stored specs, so that case behaves as before. A level that was not in the estimation data now gives formulaic's DataMismatchWarning and is encoded as the base level, where it previously raised a shape error.

Tests: new linearmodels/tests/test_formula_predict_new_data.py with 14 cases (IV2SLS, IVLIML, IVGMM, IVGMMCUE, IVJIVE, the six panel models, SUR, IV3SLS, IVSystemGMM). The expected predictions are computed by hand from the parameters, with x centered 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/tests that use from_formula, a formula parser or predict pass (8934 passed, 28 skipped). ruff check, black --check and isort --check-only are clean on the changed files.

…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

codecov Bot commented Nov 28, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 98.51485% with 3 lines in your changes missing coverage. Please review.
✅ Project coverage is 99.68%. Comparing base (00528bd) to head (1a1243a).
⚠️ Report is 8 commits behind head on main.

Files with missing lines Patch % Lines
linearmodels/shared/utility.py 85.71% 1 Missing and 2 partials ⚠️
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     
Flag Coverage Δ
adder 99.68% <98.51%> (-0.01%) ⬇️
subtractor 99.68% <98.51%> (-0.01%) ⬇️

Flags with carried forward coverage won't be shown. Click here to find out more.

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

@bashtage bashtage left a comment

Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

  1. 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`).
  2. A .. versionchanged:: 7.2 in the Notes of the predict methods 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.
  3. 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 a ValueError that 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.
@WeiLiuu

WeiLiuu commented Dec 2, 2026

Copy link
Copy Markdown
Contributor Author

Thanks for the review. The three points and the optional test are in new commits on top of e96afab:

  1. The release note is under "Changes that alter results" of 7.2 in doc/source/changes/7.0.rst, with your text (7d9c401).
  2. The .. versionchanged:: 7.2 with your text is in the Notes of predict of the IV, panel (including PooledOLS.predict, which has its own docstring) and system models, and of OLSResults, PanelResults and SystemResults (7d9c401).
  3. A level that is not in the estimation data raises a ValueError that names the variable and the new levels, for example C(c): 'd', 'e' (7fd6fb7). The IV and panel formula parsers, and so the system parser, build the regressors with model_matrix_from_spec in linearmodels/shared/utility.py, which turns formulaic's DataMismatchWarning into the error. Levels that are a subset of the estimation levels or in another order are not new levels. A missing value is not reported as a new level and keeps formulaic's warning. The tests cover the IV, panel and system models through the model and the results, and a string column without C(); the Raises sections of predict mention the error.
  4. test_system is parametrized over the dict and the equivalent "{y ~ ...} {y2 ~ ...}" string (1a1243a). Without the specifications on the string branch, the three string cases fail.

@bashtage

bashtage commented Dec 3, 2026

Copy link
Copy Markdown
Owner

Thanks

@bashtage
bashtage merged commit 1e04074 into bashtage:main Dec 3, 2026
0 of 2 checks passed
bashtage added a commit to echuq/linearmodels that referenced this pull request Dec 3, 2026
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.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants