Skip to content

REF: Use array_like for hand-rolled checks in models and nonparametric - #11251

Merged
bashtage merged 3 commits into
statsmodels:mainfrom
bashtage:wip-array-like-models
Nov 26, 2026
Merged

bashtage merged 3 commits into
statsmodels:mainfrom
bashtage:wip-array-like-models

Conversation

@bashtage

Copy link
Copy Markdown
Member

Stacked on #11242 (array_like returns a base-class ndarray); its commits are the first sections below. Review the last commit.

BUG: Make array_like return a base-class ndarray

array_like is documented to return an ndarray, and statsmodels uses it
where np.asarray would otherwise be called. It passed np.require no
"E" requirement, so subclasses of ndarray were returned unchanged: an
np.matrix kept matrix semantics (2-d always, * is matrix
multiplication, a column cannot be squeezed to 1-d) and a masked array kept
its mask, which later code honoured in some operations and ignored in
others.

It now asks np.require for a base-class ndarray, as np.asarray returns.
A matrix becomes a 2-d ndarray and a masked array its data, with the mask
dropped. Lists, pandas objects and plain ndarrays are unchanged.

This also lets hand-rolled np.asarray checks be replaced by array_like
without changing what happens to these inputs.

Tests: a matrix, a masked array and another ndarray subclass give a
base-class ndarray equal to np.asarray of the input, with and without
writeable, and a matrix column is squeezed to 1-d with ndim=1. They
fail on main.

ENH: Say how many dimensions array_like expected and got

When shape has a different number of entries than the input has
dimensions, array_like raised "Provided shape (None, None) does not have
the correct dimension for data, which is dimension 1". It reported the
dimension after a scalar had been padded to 1-d, so a scalar was "dimension
1". It now says "data must have 2 dimensions, but has 1", counting the
dimensions of the input as given ("but has 0" for a scalar).

REF: Use array_like for hand-rolled checks in models and nonparametric

Several functions in base, genmod, nonparametric, tools and treatment
convert an argument with np.asarray and then check its ndim by hand. This
replaces each of these checks with a single array_like call from
statsmodels.tools.validation. Results do not change for any input. Inputs
that were rejected are still rejected with a ValueError, in most cases
now with array_like's message. The calls are written so that array_like
checks exactly what the old code checked: shape=(None,) * k without ndim,
because ndim pads and squeezes axes instead of rejecting them; maxdim
where ndim's padding of a 1-d input is wanted but squeezing is not;
mindim=0 where a scalar was rejected; dtype=None where the old code did
not convert to float. This builds on the change that makes array_like
return a base-class ndarray, as np.asarray does, so matrix and
masked-array input behave as before.

Changes

  • exog_extra in the score tests (GLM.score_test, GLMResults.score_test,
    the count models' score_test and base._parameter_inference.score_test,
    through _full_rank_exog_extra): array_like(exog_extra, "exog_extra",
    dtype=None, maxdim=2, ndim=2). A 1-d exog_extra is still a single
    column. The check of the number of rows against exog stays.
  • BinomialBayesMixedGLM and PoissonBayesMixedGLM: ident uses
    array_like(ident, "ident", dtype=None, mindim=0, shape=(None,)).
    dtype=None keeps the integer dtype check below it working. ident=None
    still raises ValueError("ident must be a one-dimensional array")
    instead of array_like's TypeError.
  • nonparametric.lowess: endog and exog use array_like(..., mindim=0,
    shape=(None,)); the length check stays.
  • tools._lstsq.QRSVD (used by OLS.fit(method="qr")): x uses
    array_like(x, "x", shape=(None, None)).
  • TreatmentEffect.balance_table: exog uses array_like(exog, "exog",
    shape=(None, None)); the checks of the number of rows, of empty exog and
    of non-finite values stay.

Error messages that change (all ValueError):

  • score tests: an exog_extra with more than 2 dimensions gave "exog_extra
    must have the same number of rows as exog, ..." and now gives "exog_extra
    must have ndim <= 2". A scalar still gets the rows message, now with shape
    (1, 1) instead of (). For a model with one observation a scalar is now
    rejected as being in the span of exog, as [x] and [[x]] were on main.
  • BayesMixedGLM: "ident must be a one-dimensional array" becomes "ident must
    have 1 dimension, but has 2" (or 0); unchanged for ident=None.
  • lowess: "exog must be a vector" and "endog must be a vector" become "exog
    must have 1 dimension, but has ..." (or endog). If both are invalid, endog
    is now named first.
  • QRSVD: "x must be 2-dimensional." becomes "x must have 2 dimensions, but
    has ...".
  • balance_table: for exog that is not 2-d, "exog must be a finite nonempty
    two-dimensional array with one row per observation" becomes "exog must
    have 2 dimensions, but has ..."; the other cases keep the old message.

Not changed

  • Results.cov_params r_matrix: only a 0-d r_matrix is rejected and there
    is no upper bound on ndim. array_like cannot reject a 0-d input (mindim
    pads it), so it would accept a scalar.
  • nonparametric.kernels_asymmetric._kernel_asym_batch weights: likewise,
    only 0-d is rejected, together with a length check against the sample.
  • regression._prediction.get_prediction weights: weights of size 1 are
    accepted in any shape, so the check depends on the size, not the ndim.
  • WLS weights: a scalar is repeated and other weights are squeezed before
    the length check against nobs.
  • regression.linear_model.yule_walker x: np.array makes the copy that the
    in-place demeaning needs (array_like does not copy a float ndarray), and
    the check accepts any array with shape[1] == 1, for example (n, 1, 5),
    which array_like(ndim=1) would reject; array_like would also accept a
    scalar, which raises IndexError on main.
  • tools.grouputils.Grouping.transform_slices and
    tools.numdiff._get_epsilon: the only check compares the shape with
    self.nobs or with x.

Tests

For each changed function, list and pandas inputs give the same result as
an ndarray, checked against a closed form where one exists: the Poisson
score statistic ex'(y - mu) with information ex' diag(mu) ex for 2-d,
1-d and Series exog_extra, a lowess fit that reproduces a straight line,
the QRSVD singular values against np.linalg.svd, and the hand-computed
balance table for list exog. BayesMixedGLM with a list or Series ident
gives the same model and log posterior as an ndarray. Each input that was
rejected before (a column, a row, a 3-d array, a scalar, ident=None) is
still rejected, matching the new message. Three existing tests that
matched the old messages are updated: test_invalid_exog_extra in
genmod/tests/test_score_test.py, test_invalid_exog in
treatment/tests/test_diagnostics.py and test_qrsvd_invalid_input in
tools/tests/test_lstsq.py.

  • tests added / passed.
  • code/documentation is well formatted.
  • properly formatted commit message. See
    NumPy's guide.

AI Disclosure

Contributions must comply with the statsmodels AI Policy.

Tick exactly one of the following. If AI tools were used, replace the <...>
placeholders in the second option with the tool name(s) and how the tool's output was
used.

  • No AI tools were used to develop this pull request.
  • AI tools were used.
    Tool(s): Claude Code (Claude Opus 5.5).
    Used for: finding the hand-rolled checks with an AST scan, replacing them, writing the tests, and checking that only error messages change (probes with NumPy 1.23.5, 1.26.4 and 2.5, mutation check).
    I have personally read, understood, and can explain every line of this diff, and
    have verified the statistical/numerical correctness of the change.

🤖 Generated with Claude Code

`array_like` is documented to return an ndarray, and statsmodels uses it
where `np.asarray` would otherwise be called. It passed `np.require` no
"E" requirement, so subclasses of ndarray were returned unchanged: an
`np.matrix` kept matrix semantics (2-d always, `*` is matrix
multiplication, a column cannot be squeezed to 1-d) and a masked array kept
its mask, which later code honoured in some operations and ignored in
others.

It now asks `np.require` for a base-class ndarray, as `np.asarray` returns.
A matrix becomes a 2-d ndarray and a masked array its data, with the mask
dropped. Lists, pandas objects and plain ndarrays are unchanged.

This also lets hand-rolled `np.asarray` checks be replaced by `array_like`
without changing what happens to these inputs.

Tests: a matrix, a masked array and another ndarray subclass give a
base-class ndarray equal to `np.asarray` of the input, with and without
`writeable`, and a matrix column is squeezed to 1-d with `ndim=1`. They
fail on main.
When `shape` has a different number of entries than the input has
dimensions, `array_like` raised "Provided shape (None, None) does not have
the correct dimension for data, which is dimension 1". It reported the
dimension after a scalar had been padded to 1-d, so a scalar was "dimension
1". It now says "data must have 2 dimensions, but has 1", counting the
dimensions of the input as given ("but has 0" for a scalar).
Several functions in base, genmod, nonparametric, tools and treatment
convert an argument with np.asarray and then check its ndim by hand. This
replaces each of these checks with a single array_like call from
statsmodels.tools.validation. Results do not change for any input. Inputs
that were rejected are still rejected with a ValueError, in most cases
now with array_like's message. The calls are written so that array_like
checks exactly what the old code checked: shape=(None,) * k without ndim,
because ndim pads and squeezes axes instead of rejecting them; maxdim
where ndim's padding of a 1-d input is wanted but squeezing is not;
mindim=0 where a scalar was rejected; dtype=None where the old code did
not convert to float. This builds on the change that makes array_like
return a base-class ndarray, as np.asarray does, so matrix and
masked-array input behave as before.

Changes

- exog_extra in the score tests (GLM.score_test, GLMResults.score_test,
  the count models' score_test and base._parameter_inference.score_test,
  through _full_rank_exog_extra): array_like(exog_extra, "exog_extra",
  dtype=None, maxdim=2, ndim=2). A 1-d exog_extra is still a single
  column. The check of the number of rows against exog stays.
- BinomialBayesMixedGLM and PoissonBayesMixedGLM: ident uses
  array_like(ident, "ident", dtype=None, mindim=0, shape=(None,)).
  dtype=None keeps the integer dtype check below it working. ident=None
  still raises ValueError("ident must be a one-dimensional array")
  instead of array_like's TypeError.
- nonparametric.lowess: endog and exog use array_like(..., mindim=0,
  shape=(None,)); the length check stays.
- tools._lstsq.QRSVD (used by OLS.fit(method="qr")): x uses
  array_like(x, "x", shape=(None, None)).
- TreatmentEffect.balance_table: exog uses array_like(exog, "exog",
  shape=(None, None)); the checks of the number of rows, of empty exog and
  of non-finite values stay.

Error messages that change (all ValueError):

- score tests: an exog_extra with more than 2 dimensions gave "exog_extra
  must have the same number of rows as exog, ..." and now gives "exog_extra
  must have ndim <= 2". A scalar still gets the rows message, now with shape
  (1, 1) instead of (). For a model with one observation a scalar is now
  rejected as being in the span of exog, as [x] and [[x]] were on main.
- BayesMixedGLM: "ident must be a one-dimensional array" becomes "ident must
  have 1 dimension, but has 2" (or 0); unchanged for ident=None.
- lowess: "exog must be a vector" and "endog must be a vector" become "exog
  must have 1 dimension, but has ..." (or endog). If both are invalid, endog
  is now named first.
- QRSVD: "x must be 2-dimensional." becomes "x must have 2 dimensions, but
  has ...".
- balance_table: for exog that is not 2-d, "exog must be a finite nonempty
  two-dimensional array with one row per observation" becomes "exog must
  have 2 dimensions, but has ..."; the other cases keep the old message.

Not changed

- Results.cov_params r_matrix: only a 0-d r_matrix is rejected and there
  is no upper bound on ndim. array_like cannot reject a 0-d input (mindim
  pads it), so it would accept a scalar.
- nonparametric.kernels_asymmetric._kernel_asym_batch weights: likewise,
  only 0-d is rejected, together with a length check against the sample.
- regression._prediction.get_prediction weights: weights of size 1 are
  accepted in any shape, so the check depends on the size, not the ndim.
- WLS weights: a scalar is repeated and other weights are squeezed before
  the length check against nobs.
- regression.linear_model.yule_walker x: np.array makes the copy that the
  in-place demeaning needs (array_like does not copy a float ndarray), and
  the check accepts any array with shape[1] == 1, for example (n, 1, 5),
  which array_like(ndim=1) would reject; array_like would also accept a
  scalar, which raises IndexError on main.
- tools.grouputils.Grouping.transform_slices and
  tools.numdiff._get_epsilon: the only check compares the shape with
  self.nobs or with x.

Tests

For each changed function, list and pandas inputs give the same result as
an ndarray, checked against a closed form where one exists: the Poisson
score statistic ex'(y - mu) with information ex' diag(mu) ex for 2-d,
1-d and Series exog_extra, a lowess fit that reproduces a straight line,
the QRSVD singular values against np.linalg.svd, and the hand-computed
balance table for list exog. BayesMixedGLM with a list or Series ident
gives the same model and log posterior as an ndarray. Each input that was
rejected before (a column, a row, a 3-d array, a scalar, ident=None) is
still rejected, matching the new message. Three existing tests that
matched the old messages are updated: test_invalid_exog_extra in
genmod/tests/test_score_test.py, test_invalid_exog in
treatment/tests/test_diagnostics.py and test_qrsvd_invalid_input in
tools/tests/test_lstsq.py.
@bashtage
bashtage marked this pull request as ready for review November 26, 2026 21:03
@bashtage
bashtage merged commit 0c97136 into statsmodels:main Nov 26, 2026
10 of 11 checks passed
@bashtage
bashtage deleted the wip-array-like-models branch November 27, 2026 10:01
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.

1 participant