Skip to content

[data/preprocessors] Fix StandardScaler to handle NaN stats - #51281

Merged
richardliaw merged 5 commits into
masterfrom
pg-51243
Mar 12, 2025
Merged

richardliaw merged 5 commits into
masterfrom
pg-51243

Conversation

@gvspraveen

Copy link
Copy Markdown
Contributor

Why are these changes needed?

When StandardScaler.stats_ has a column with NaN then short circuit transform for that columns.

Related issue number

Closes #51243

Checks

@gvspraveen
gvspraveen requested a review from richardliaw March 11, 2025 23:06
@gvspraveen
gvspraveen requested a review from a team as a code owner March 11, 2025 23:06
Comment thread python/ray/data/preprocessors/scaler.py Resolved
Signed-off-by: Praveen Gorthy <[email protected]>
@gvspraveen gvspraveen changed the title Fix StandardScaler to handle NAN stats Fix StandardScaler to handle NaN stats Mar 12, 2025
@richardliaw richardliaw changed the title Fix StandardScaler to handle NaN stats [data/preprocessors] Fix StandardScaler to handle NaN stats Mar 12, 2025
@PawaritL

Copy link
Copy Markdown

while it's unlikely that only one of the two stats will be None for a given column, it might be a bit safer to use or in the if condition

@richardliaw richardliaw added the go add ONLY when ready to merge, run all tests label Mar 12, 2025
Praveen Gorthy added 2 commits March 12, 2025 13:01
@richardliaw
richardliaw merged commit a62e4a0 into master Mar 12, 2025
@richardliaw
richardliaw deleted the pg-51243 branch March 12, 2025 21:21
qinyiyan pushed a commit to qinyiyan/ray that referenced this pull request Mar 13, 2025
…ect#51281)

<!-- Thank you for your contribution! Please review
https://github.com/ray-project/ray/blob/master/CONTRIBUTING.rst before
opening a pull request. -->

<!-- Please add a reviewer to the assignee section when you create a PR.
If you don't have the access to it, we will shortly find a reviewer and
assign them to your PR. -->

## Why are these changes needed?

When `StandardScaler.stats_` has a column with `NaN` then short circuit
transform for that columns.

## Related issue number

Closes ray-project#51243

## Checks

- [ ] I've signed off every commit(by using the -s flag, i.e., `git
commit -s`) in this PR.
- [ ] I've run `scripts/format.sh` to lint the changes in this PR.
- [ ] I've included any doc changes needed for
https://docs.ray.io/en/master/.
- [ ] I've added any new APIs to the API Reference. For example, if I
added a
method in Tune, I've added it in `doc/source/tune/api/` under the
           corresponding `.rst` file.
- [ ] I've made sure the tests are passing. Note that there might be a
few flaky tests, see the recent failures at https://flakey-tests.ray.io/
- Testing Strategy
   - [ ] Unit tests
   - [ ] Release tests
   - [ ] This PR is not tested :(

---------

Signed-off-by: Praveen Gorthy <[email protected]>
park12sj pushed a commit to park12sj/ray that referenced this pull request Mar 18, 2025
…ect#51281)

<!-- Thank you for your contribution! Please review
https://github.com/ray-project/ray/blob/master/CONTRIBUTING.rst before
opening a pull request. -->

<!-- Please add a reviewer to the assignee section when you create a PR.
If you don't have the access to it, we will shortly find a reviewer and
assign them to your PR. -->

## Why are these changes needed?

When `StandardScaler.stats_` has a column with `NaN` then short circuit
transform for that columns.

## Related issue number

Closes ray-project#51243

## Checks

- [ ] I've signed off every commit(by using the -s flag, i.e., `git
commit -s`) in this PR.
- [ ] I've run `scripts/format.sh` to lint the changes in this PR.
- [ ] I've included any doc changes needed for
https://docs.ray.io/en/master/.
- [ ] I've added any new APIs to the API Reference. For example, if I
added a
method in Tune, I've added it in `doc/source/tune/api/` under the
           corresponding `.rst` file.
- [ ] I've made sure the tests are passing. Note that there might be a
few flaky tests, see the recent failures at https://flakey-tests.ray.io/
- Testing Strategy
   - [ ] Unit tests
   - [ ] Release tests
   - [ ] This PR is not tested :(

---------

Signed-off-by: Praveen Gorthy <[email protected]>
dhakshin32 pushed a commit to dhakshin32/ray that referenced this pull request Mar 27, 2025
…ect#51281)

<!-- Thank you for your contribution! Please review
https://github.com/ray-project/ray/blob/master/CONTRIBUTING.rst before
opening a pull request. -->

<!-- Please add a reviewer to the assignee section when you create a PR.
If you don't have the access to it, we will shortly find a reviewer and
assign them to your PR. -->

## Why are these changes needed?

When `StandardScaler.stats_` has a column with `NaN` then short circuit
transform for that columns.

## Related issue number

Closes ray-project#51243

## Checks

- [ ] I've signed off every commit(by using the -s flag, i.e., `git
commit -s`) in this PR.
- [ ] I've run `scripts/format.sh` to lint the changes in this PR.
- [ ] I've included any doc changes needed for
https://docs.ray.io/en/master/.
- [ ] I've added any new APIs to the API Reference. For example, if I
added a
method in Tune, I've added it in `doc/source/tune/api/` under the
           corresponding `.rst` file.
- [ ] I've made sure the tests are passing. Note that there might be a
few flaky tests, see the recent failures at https://flakey-tests.ray.io/
- Testing Strategy
   - [ ] Unit tests
   - [ ] Release tests
   - [ ] This PR is not tested :(

---------

Signed-off-by: Praveen Gorthy <[email protected]>
Signed-off-by: Dhakshin Suriakannu <[email protected]>
AarryaSaraf added a commit to AarryaSaraf/ray that referenced this pull request Aug 10, 2026
Ray 2.56 (ray-project#63017) made `BlockAccessor.to_pandas` hand out Arrow-backed pandas
frames, in which a missing value is `pd.NA` rather than `np.nan`. Five
preprocessors regressed. Each is fixed locally; batches stay Arrow-backed, so
ray-project#63017's memory and speed win is kept.

The change swapped a sentinel that silently pretends to be a number for one that
refuses to be anything. `np.nan` is a `float`, so it takes part in any float
operation and always gives an answer: `np.nan >= 0` is False, `0 + np.nan` is
`nan`, and a NumPy array holding it stays `float64`. None of those answers is
meaningful for a missing value, but each is usable, and this code had been
written to them. `pd.NA` gives none of them, and multi-column
`df[cols].to_numpy()` over Arrow-backed columns returns `dtype=object` even with
nothing missing, because pandas has no rule for combining Arrow extension types
into one NumPy dtype.

So each regression fix is the same shape: say out loud what `np.nan` used to say
silently.

  - PowerTransformer: `.fillna(False)` on the sign mask, since `pd.NA >= 0` is
    `pd.NA` and a three-valued mask cannot index a NumPy array. A missing value
    takes the negative branch, where the arithmetic leaves it missing -- the same
    result as before, when `np.nan >= 0` was already False.
  - Concatenator: stack one column at a time instead of calling `to_numpy` on a
    multi-column selection. A single Arrow-backed column converts to its natural
    NumPy dtype. Previously the output tensor column silently became pickled
    Python objects, with no error raised and no null required to trigger it.
  - FeatureHasher: map a missing token count to `np.nan`. `0 + pd.NA` is `pd.NA`,
    which absorbs the accumulator and degrades the output column to
    `dtype=object`; `np.nan` propagates the same way but stays a float.
  - Encoder fit path: `_is_null` extended to `pd.NA`/`pd.NaT`, so a null is
    filtered before `sorted()` instead of raising `TypeError: boolean value of NA
    is ambiguous`, and the documented "consider imputing missing values first"
    ValueError is reached again. `Counter.update` guarded for the same reason.
  - `_is_series_composed_of_lists`: recognise a list column from an Arrow dtype.
    It gated on `is_object_dtype`, which is False for
    `list<item: string>[pyarrow]`, so list columns were treated as scalar and
    sent to `value_counts`, which has no pyarrow kernel for lists. This broke
    MultiHotEncoder with no nulls at all, and OrdinalEncoder on list columns.

MaxAbsScaler is the mirror image: it needed to express something `np.nan` could
not express. Fitting an all-null column leaves `stats_` holding None, and
`s / None` has no answer for a float column, so it raised TypeError. For an
Arrow-backed column None is a valid null scalar of the column's own type, so the
division yields nulls -- the right answer, and the one StandardScaler was patched
to give in ray-project#51281. An explicit guard mirroring StandardScaler's makes the two
paths agree instead of leaving the correct result to depend on a pandas
arithmetic rule. No behaviour change on the default path.

The survey that found those regressions also found seven preprocessors that were
already broken on missing data before ray-project#63017, failing identically on both
representations. They are the same situations failing in the same illegible way,
so they are fixed to the same rule: propagate the gap, or refuse with an error
naming the column.

Propagate, because the output can represent "missing" and the work is per-row:

  - MinMaxScaler, RobustScaler -- an all-null column has no range and no
    quantiles, so `fit` has no statistic to store. Return nulls, as
    StandardScaler has for an uncomputable mean or std since ray-project#51281.
    MinMaxScaler previously reported `'DataFrame' object has no attribute
    'name'`: the real failure is `max - min` on two Nones, but
    `DataFrame.transform` retries a failing per-column function with the whole
    frame, and the retry dies on `s.name` instead. RobustScaler failed earlier
    still, in `fit`, unpacking an empty list of quantiles.
  - Tokenizer, CountVectorizer, HashingVectorizer -- a missing document is not
    tokenized, and contributes nothing to CountVectorizer's vocabulary. It gets
    no token list and no count vector, rather than a zero vector that would be
    indistinguishable from a document containing none of the vocabulary. These
    three died on a single missing cell in a text column, with
    `AttributeError: 'NAType' object has no attribute 'split'`. The guard lives
    at the call site rather than in `simple_split_tokenizer`, because a
    user-supplied `tokenization_fn` should not have to know about `pd.NA` either.

Refuse, because no defensible output exists:

  - UniformKBinsDiscretizer -- with no observed values there is no range to
    divide into `bins` intervals. Was `TypeError: unsupported operand type(s)
    for +: 'NoneType' and 'float'`.
  - SimpleImputer(strategy="most_frequent") -- nothing to impute from. This
    message already existed for `strategy="mean"` (f4c4c81) but was
    unreachable here: the strategy died during `fit` on `most_common(1)[0][0]`
    with `IndexError: list index out of range`, before the guard that raises it.

Tests: `tests/test_preprocessors_arrow_backed.py` covers 19 preprocessors across
four input shapes -- no nulls, some nulls, an all-null column, and the same data
as a NumPy-backed pandas block -- asserting that output stays numeric rather than
`dtype=object`, that a missing input stays missing, and that the two refusals
name the column rather than only raising the right exception type. Its
`_is_missing` helper also counts `pd.NA`, which is what a missing value looks
like when the output column keeps the block in pandas, as a column of Python
lists does.

The RobustScaler all-null case is worth a note: it was passing locally only
because `datasketches` was absent, which skipped the test. It fails without this
fix anywhere that optional package is installed, including CI.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Signed-off-by: Aarrya <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

community-backlog go add ONLY when ready to merge, run all tests

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Data] StandardScaler.transform() cannot handle non-NAN columns when StandardScaler.stats_ is NAN for that column

4 participants