Skip to content

REF: Use array_like for hand-rolled checks in stats, distributions, robust - #11250

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

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

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 stats, distributions, robust

Several public functions in stats, distributions and robust convert an
argument with np.asarray and then check its ndim or shape 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, 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; 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

  • StepFunction (and so ECDF and ECDFDiscrete): x and y use
    array_like(..., dtype=None, mindim=0, shape=(None,)); the check that x
    and y have the same shape stays.
  • robust.covariance.cov_gk and cov_ogk: data uses
    array_like(data, "data", dtype=None, shape=(None, None)).
  • contingency_tables.mcnemar: table uses array_like(table, "table",
    shape=(None, None)); the 2x2 check stays, because its message points to
    SquareTable.symmetry for larger tables.
  • inter_rater.to_table: data uses array_like(data, "data", dtype=None,
    shape=(None, None)); dtype=None keeps string categories working.
  • inter_rater.cohens_kappa: table uses array_like(table, "table",
    shape=(None, None)); the square check stays.
  • proportion.confint_proportions_paired: table uses array_like(table,
    "table", shape=(2, 2)).
  • rates.etest_poisson_2indep: y_grid uses array_like(y_grid, "y_grid",
    dtype=None, mindim=0, shape=(None,)).

Error messages that change (all ValueError):

  • StepFunction, ECDF: "x and y must be 1-dimensional" (and, for a 2-d x in
    ECDF or a 1-d x with a 2-d y, "x and y do not have the same shape")
    becomes "x must have 1 dimension, but has 2" (or for y).
  • cov_gk, cov_ogk: "data needs to be two dimensional" becomes "data must
    have 2 dimensions, but has ...".
  • mcnemar: "mcnemar requires a two-dimensional contingency table, ..."
    becomes "table must have 2 dimensions, but has ...".
  • to_table: "data must be a 2-d array of subjects by raters, ..." becomes
    "data must have 2 dimensions, but has ...".
  • cohens_kappa, table not 2-d: "table must be a square 2-d array, ..."
    becomes "table must have 2 dimensions, but has ..."; a 2-d table that is
    not square keeps the old message.
  • confint_proportions_paired: "confint_proportions_paired requires a 2x2
    contingency table, ..." becomes "table is required to have shape (2, 2)
    but has shape (3, 3)" for a 2-d table and "table must have 2 dimensions,
    but has ..." otherwise.
  • etest_poisson_2indep: "y_grid needs to be None or 1-dimensional array"
    becomes "y_grid must have 1 dimension, but has ...".

Not changed

  • RLM.fit start_params: the code squeezes all singleton axes before the
    check, so a (1, k) row is accepted. array_like(ndim=1) only squeezes
    trailing axes and would reject it.
  • distributions.tools._eval_bernstein_2d: np.atleast_2d adds a leading
    axis, so a single point (2,) becomes (1, 2). array_like only adds
    trailing axes.
  • contrast.contrastfromcols, stats.dist_dependence_measures
    (_validate_and_tranform_x_and_y) and cohens_kappa weights: the only
    check that raises compares the shape with another argument (D, y or
    table), so it stays as an explicit check. In
    _validate_and_tranform_x_and_y, array_like(ndim=2) would also turn a
    scalar into a 1 x 1 sample, where main raises.
  • stattools.omni_normtest: the check compares resids.ndim with the axis
    argument.

Tests

For each changed function, list and pandas inputs give the same result as
an ndarray, checked against a closed form or a published value where one
exists: StepFunction values by hand, the GK covariance formula, the
McNemar statistic 9 / 7 with its chi2(1) p-value, a hand-counted
to_table, kappa 0.64 for the docstring table, the R-verified
confint_proportions_paired interval, and the E-test against its default
grid. Each input that was rejected before (a column, a row, a 2-d or 3-d
array, a 2 x 2 x 1 table, a scalar) is still rejected, matching the new
message. StepFunction keeps complex values (dtype=None) and to_table
keeps string categories. Four existing tests that matched the old
messages are updated (test_mcnemar_non_2x2,
test_cohens_kappa_rejects_non_square_table,
test_confint_proportions_paired_invalid_inputs_raises) or replaced
(test_to_table_rejects_1d_data by test_to_table_rejects_non_2d).

  • 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).
…obust

Several public functions in stats, distributions and robust convert an
argument with np.asarray and then check its ndim or shape 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, 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; 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

- StepFunction (and so ECDF and ECDFDiscrete): x and y use
  array_like(..., dtype=None, mindim=0, shape=(None,)); the check that x
  and y have the same shape stays.
- robust.covariance.cov_gk and cov_ogk: data uses
  array_like(data, "data", dtype=None, shape=(None, None)).
- contingency_tables.mcnemar: table uses array_like(table, "table",
  shape=(None, None)); the 2x2 check stays, because its message points to
  SquareTable.symmetry for larger tables.
- inter_rater.to_table: data uses array_like(data, "data", dtype=None,
  shape=(None, None)); dtype=None keeps string categories working.
- inter_rater.cohens_kappa: table uses array_like(table, "table",
  shape=(None, None)); the square check stays.
- proportion.confint_proportions_paired: table uses array_like(table,
  "table", shape=(2, 2)).
- rates.etest_poisson_2indep: y_grid uses array_like(y_grid, "y_grid",
  dtype=None, mindim=0, shape=(None,)).

Error messages that change (all ValueError):

- StepFunction, ECDF: "x and y must be 1-dimensional" (and, for a 2-d x in
  ECDF or a 1-d x with a 2-d y, "x and y do not have the same shape")
  becomes "x must have 1 dimension, but has 2" (or for y).
- cov_gk, cov_ogk: "data needs to be two dimensional" becomes "data must
  have 2 dimensions, but has ...".
- mcnemar: "mcnemar requires a two-dimensional contingency table, ..."
  becomes "table must have 2 dimensions, but has ...".
- to_table: "data must be a 2-d array of subjects by raters, ..." becomes
  "data must have 2 dimensions, but has ...".
- cohens_kappa, table not 2-d: "table must be a square 2-d array, ..."
  becomes "table must have 2 dimensions, but has ..."; a 2-d table that is
  not square keeps the old message.
- confint_proportions_paired: "confint_proportions_paired requires a 2x2
  contingency table, ..." becomes "table is required to have shape (2, 2)
  but has shape (3, 3)" for a 2-d table and "table must have 2 dimensions,
  but has ..." otherwise.
- etest_poisson_2indep: "y_grid needs to be None or 1-dimensional array"
  becomes "y_grid must have 1 dimension, but has ...".

Not changed

- RLM.fit start_params: the code squeezes all singleton axes before the
  check, so a (1, k) row is accepted. array_like(ndim=1) only squeezes
  trailing axes and would reject it.
- distributions.tools._eval_bernstein_2d: np.atleast_2d adds a leading
  axis, so a single point (2,) becomes (1, 2). array_like only adds
  trailing axes.
- contrast.contrastfromcols, stats.dist_dependence_measures
  (_validate_and_tranform_x_and_y) and cohens_kappa weights: the only
  check that raises compares the shape with another argument (D, y or
  table), so it stays as an explicit check. In
  _validate_and_tranform_x_and_y, array_like(ndim=2) would also turn a
  scalar into a 1 x 1 sample, where main raises.
- stattools.omni_normtest: the check compares resids.ndim with the axis
  argument.

Tests

For each changed function, list and pandas inputs give the same result as
an ndarray, checked against a closed form or a published value where one
exists: StepFunction values by hand, the GK covariance formula, the
McNemar statistic 9 / 7 with its chi2(1) p-value, a hand-counted
to_table, kappa 0.64 for the docstring table, the R-verified
confint_proportions_paired interval, and the E-test against its default
grid. Each input that was rejected before (a column, a row, a 2-d or 3-d
array, a 2 x 2 x 1 table, a scalar) is still rejected, matching the new
message. StepFunction keeps complex values (dtype=None) and to_table
keeps string categories. Four existing tests that matched the old
messages are updated (test_mcnemar_non_2x2,
test_cohens_kappa_rejects_non_square_table,
test_confint_proportions_paired_invalid_inputs_raises) or replaced
(test_to_table_rejects_1d_data by test_to_table_rejects_non_2d).
@bashtage
bashtage marked this pull request as ready for review November 26, 2026 21:06
@bashtage
bashtage merged commit 42e0305 into statsmodels:main Nov 26, 2026
11 of 12 checks passed
@bashtage
bashtage deleted the wip-array-like-stats 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