Repository navigation
REF: Use array_like for hand-rolled checks in stats, distributions, robust - #11250
Merged
Merged
Conversation
`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).
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Stacked on #11242 (
array_likereturns 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_likeis documented to return an ndarray, and statsmodels uses itwhere
np.asarraywould otherwise be called. It passednp.requireno"E" requirement, so subclasses of ndarray were returned unchanged: an
np.matrixkept matrix semantics (2-d always,*is matrixmultiplication, 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.requirefor a base-class ndarray, asnp.asarrayreturns.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.asarraychecks be replaced byarray_likewithout changing what happens to these inputs.
Tests: a matrix, a masked array and another ndarray subclass give a
base-class ndarray equal to
np.asarrayof the input, with and withoutwriteable, and a matrix column is squeezed to 1-d withndim=1. Theyfail on main.
ENH: Say how many dimensions array_like expected and got
When
shapehas a different number of entries than the input hasdimensions,
array_likeraised "Provided shape (None, None) does not havethe 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
array_like(..., dtype=None, mindim=0, shape=(None,)); the check that x
and y have the same shape stays.
array_like(data, "data", dtype=None, shape=(None, None)).
shape=(None, None)); the 2x2 check stays, because its message points to
SquareTable.symmetry for larger tables.
shape=(None, None)); dtype=None keeps string categories working.
shape=(None, None)); the square check stays.
"table", shape=(2, 2)).
dtype=None, mindim=0, shape=(None,)).
Error messages that change (all ValueError):
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).
have 2 dimensions, but has ...".
becomes "table must have 2 dimensions, but has ...".
"data must have 2 dimensions, but has ...".
becomes "table must have 2 dimensions, but has ..."; a 2-d table that is
not square keeps the old message.
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.
becomes "y_grid must have 1 dimension, but has ...".
Not changed
check, so a (1, k) row is accepted. array_like(ndim=1) only squeezes
trailing axes and would reject it.
axis, so a single point (2,) becomes (1, 2). array_like only adds
trailing axes.
(_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.
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).
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.
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