Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions sklearn/preprocessing/_discretization.py
Original file line number Diff line number Diff line change
Expand Up @@ -161,6 +161,10 @@ def fit(self, X, y=None):
elif self.strategy == 'quantile':
quantiles = np.linspace(0, 100, n_bins[jj] + 1)
bin_edges[jj] = np.asarray(np.percentile(column, quantiles))
# Edge cases can lead to numerically unstable values in case of
# identical percentiles, but we need to make them monotonic
# https://github.com/numpy/numpy/issues/10373
np.maximum.accumulate(bin_edges[jj], out=bin_edges[jj])

elif self.strategy == 'kmeans':
from ..cluster import KMeans # fixes import loops
Expand Down
11 changes: 10 additions & 1 deletion sklearn/preprocessing/tests/test_discretization.py
Original file line number Diff line number Diff line change
Expand Up @@ -145,14 +145,23 @@ def test_numeric_stability():
assert_array_equal(Xt_expected, Xt)


def test_percentile_numeric_stability():
X = np.array([0.05, 0.05, 0.95]).reshape(-1, 1)
Xt_expected = np.array([5, 5, 9]).reshape(-1, 1)

Xt = KBinsDiscretizer(n_bins=10,
encode='ordinal',
strategy='quantile').fit_transform(X)
assert_array_equal(Xt_expected, Xt)


def test_invalid_encode_option():
est = KBinsDiscretizer(n_bins=[2, 3, 3, 3], encode='invalid-encode')
assert_raise_message(ValueError, "Valid options for 'encode' are "
"('onehot', 'onehot-dense', 'ordinal'). "
"Got encode='invalid-encode' instead.",
est.fit, X)


def test_encode_options():
est = KBinsDiscretizer(n_bins=[2, 3, 3, 3],
encode='ordinal').fit(X)
Expand Down