Skip to content

Add sample_weight support for QuantileTransformer when fit on dense data - #31147

Closed
kaekkr wants to merge 5 commits into
scikit-learn:mainfrom
kaekkr:quantile-transformer-sample-weight
Closed

kaekkr wants to merge 5 commits into
scikit-learn:mainfrom
kaekkr:quantile-transformer-sample-weight

Conversation

@kaekkr

@kaekkr kaekkr commented Apr 4, 2025 •

Copy link
Copy Markdown

Reference Issues/PRs

Fixes #30707
See also the discussion in #30707.

What does this implement/fix? Explain your changes.

This PR adds support for the sample_weight parameter to QuantileTransformer, allowing users to apply weights to samples when computing quantiles. This makes the transformation more flexible, especially in cases where samples have varying importance or are part of imbalanced datasets.

Changes made:

  • Added sample_weight parameter to fit and _dense_fit.
  • Implemented weighted quantile logic.
  • Updated tests to check for correct behavior with and without sample_weight.

Any other comments?

  • The implementation ensures backward compatibility.
  • Tests pass and maintain previous behavior when sample_weight is not provided.
  • Would appreciate feedback on edge cases or numerical accuracy concerns.

Thanks for the review!

@github-actions

github-actions Bot commented Apr 4, 2025 •

Copy link
Copy Markdown

✔️ Linting Passed

All linting checks passed. Your pull request is in excellent shape! ☀️

Generated for commit: 06960cf. Link to the linter CI: here

@ogrisel

ogrisel commented Apr 4, 2025 •

Copy link
Copy Markdown
Member

Thanks for the PR. Could you please instead use sklearn.utils.stats._averaged_weighted_percentile instead of reimplementing a new version of weighted quantiles?

For the unweighted case, we should use np.nanquantile/np.percentile with method="averaged_inverted_cdf" instead.

The two changes together should help make the weighting/repetition semantic check of check_sample_weight_equivalence_on_dense_data pass.

Please mark check_sample_weight_equivalence_on_sparse_data XFAIL in the PER_ESTIMATOR_XFAIL_CHECKS dict.

@ogrisel ogrisel changed the title Quantile transformer sample weight Add sample_weight support for QuantileTransformer when fit on dense data Apr 4, 2025
@ogrisel

ogrisel commented Apr 4, 2025 •

Copy link
Copy Markdown
Member

Please also don't forget to document your change in a changelog entry by adding a file under doc/whats_new/upcoming_changes. See #29907 for an example.

@kaekkr

kaekkr commented Apr 4, 2025

Copy link
Copy Markdown
Author

@ogrisel Okay, thank you for your reply! I will fix that

@lucyleeow

Copy link
Copy Markdown
Member

Are you still interested in working on this?
If so, could you check on the failing tests? Please also add a whats new entry. Thank you

self.references_ = np.linspace(0, 1, self.n_quantiles_, endpoint=True)
if sparse.issparse(X):
if sample_weight is not None:
raise ValueError("sample_weight is not supported for sparse input.")

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Suggested change
raise ValueError("sample_weight is not supported for sparse input.")
raise NotImplementedError(
"sample_weight is not supported for sparse input."
)

X_roundtrip = qt_weighted.inverse_transform(Xt_weighted)
np.testing.assert_allclose(
X[~np.isnan(X)], X_roundtrip[~np.isnan(X)], rtol=1e-2, atol=1e-2
)

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

I think this test is not necessary since there is already a common test check_sample_weight_equivalence_on_dense_data that should be executed when running the following command:

pytest -v -k "QuantileTransformer and check_sample_weight_equivalence" sklearn/tests/test_common.py

weights_clean = sample_weight[mask]
self.quantiles_[:, i] = _averaged_weighted_percentile(
col_clean, sample_weight=weights_clean, quantile=references / 100.0
)

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Please check the source code of _averaged_weighted_percentile and the docstring of _weighted_percentile to learn how to use it properly.

In particular:

  • it accepts percentile ranks, not quantile ranks;
  • it can compute for for a single rank at a time, hence you might need to call this in a list comprehension for all possible ranks passed in the references array.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Note that _averaged_weighted_percentile has now been merged into _weighted_percentile via the average=True option.


self.quantiles_ = np.zeros((len(references), n_features))

for i in range(n_features):

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Please rename i to feature_idx to make the code easier to follow.

@adrinjalali

Copy link
Copy Markdown
Member

Closing due to lack of activity from the OP. Happy to reopen if you get to work on this further.

for i in range(n_features):
col = X[:, i]
mask = ~np.isnan(col)
col_clean = col[mask]

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

_weighted_percentile has builtin support to ignore nan values, so this should no longer be needed.

@Mohataseem89

Mohataseem89 commented Dec 8, 2025 •

Copy link
Copy Markdown

This earlier PR was really helpful in shaping the current direction of sample_weight support for QuantileTransformer. Many of the suggestions here especially around using _weighted_percentile and updating the common tests have clearly influenced the ongoing work in #32761

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Add sample_weight support to QuantileTransformer

6 participants