8000 FIX validate parameter if `fit` in `KernelDensity` by DessyVV · Pull Request #21430 · scikit-learn/scikit-learn · GitHub
[go: up one dir, main page]

Skip to content

FIX validate parameter if fit in KernelDensity #21430

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 5 commits into from
Oct 24, 2021
Merged
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
7 changes: 7 additions & 0 deletions doc/whats_new/v1.1.rst
Original file line number Diff line number Diff line change
Expand Up @@ -89,6 +89,13 @@ Changelog
message when running in a jupyter notebook that is not trusted. :pr:`21316`
by `Thomas Fan`_.

:mod:`sklearn.neighbors`
........................

- |Fix| :class:`neighbors.KernelDensity` now validates input parameters in `fit`
instead of `__init__`. :pr:`21430` by :user:`Desislava Vasileva <DessyVV>` and
:user:`Lucy Jimenez <LucyJimenez>`.

Code and Documentation Contributors
-----------------------------------

Expand Down
17 changes: 7 additions & 10 deletions sklearn/neighbors/_kde.py
Original file line number Diff line number Diff line change
Expand Up @@ -135,16 +135,6 @@ def __init__(
self.leaf_size = leaf_size
self.metric_params = metric_params

# run the choose algorithm code so that exceptions will happen here
# we're using clone() in the GenerativeBayes classifier,
# so we can't do this kind of logic in __init__
self._choose_algorithm(self.algorithm, self.metric)

if bandwidth <= 0:
raise ValueError("bandwidth must be positive")
if kernel not in VALID_KERNELS:
raise ValueError("invalid kernel: '{0}'".format(kernel))

def _choose_algorithm(self, algorithm, metric):
# given the algorithm string + metric string, choose the optimal
# algorithm to compute the result.
Expand Down Expand Up @@ -188,7 +178,14 @@ def fit(self, X, y=None, sample_weight=None):
self : object
Returns the instance itself.
"""

algorithm = self._choose_algorithm(self.algorithm, self.metric)

if self.bandwidth <= 0:
raise ValueError("bandwidth must be positive")
if self.kernel not in VALID_KERNELS:
raise ValueError("invalid kernel: '{0}'".format(self.kernel))

X = self._validate_data(X, order="C", dtype=DTYPE)

if sample_weight is not None:
Expand Down
16 changes: 9 additions & 7 deletions sklearn/neighbors/tests/test_kde.py
Original file line number Diff line number Diff line change
Expand Up @@ -107,11 +107,12 @@ def test_kde_algorithm_metric_choice(algorithm, metric):
X = rng.randn(10, 2) # 2 features required for haversine dist.
Y = rng.randn(10, 2)

kde = KernelDensity(algorithm=algorithm, metric=metric)

if algorithm == "kd_tree" and metric not in KDTree.valid_metrics:
with pytest.raises(ValueError):
KernelDensity(algorithm=algorithm, metric=metric)
kde.fit(X)
else:
kde = KernelDensity(algorithm=algorithm, metric=metric)
kde.fit(X)
y_dens = kde.score_samples(Y)
assert y_dens.shape == Y.shape[:1]
Expand All @@ -126,16 +127,17 @@ def test_kde_score(n_samples=100, n_features=3):


def test_kde_badargs():
X = np.random.random((200, 10))
with pytest.raises(ValueError):
KernelDensity(algorithm="blah")
KernelDensity(algorithm="blah").fit(X)
with pytest.raises(ValueError):
KernelDensity(bandwidth=0)
KernelDensity(bandwidth=0).fit(X)
with pytest.raises(ValueError):
KernelDensity(kernel="blah")
KernelDensity(kernel="blah").fit(X)
with pytest.raises(ValueError):
KernelDensity(metric="blah")
KernelDensity(metric="blah").fit(X)
with pytest.raises(ValueError):
KernelDensity(algorithm="kd_tree", metric="blah")
KernelDensity(algorithm="kd_tree", metric="blah").fit(X)
kde = KernelDensity()
with pytest.raises(ValueError):
kde.fit(np.random.random((200, 10)), sample_weight=np.random.random((200, 10)))
Expand Down
1 change: 0 additions & 1 deletion sklearn/tests/test_common.py
Original file line number Diff line number Diff line change
Expand Up @@ -413,7 +413,6 @@ def test_transformers_get_feature_names_out(transformer):
"FeatureUnion",
"GridSearchCV",
"HalvingGridSearchCV",
"KernelDensity",
"KernelPCA",
"LabelBinarizer",
"NuSVC",
Expand Down
0