diff --git a/python/cuml/cuml/neighbors/kernel_density.py b/python/cuml/cuml/neighbors/kernel_density.py index 5cb03c664d..59fc4e0509 100644 --- a/python/cuml/cuml/neighbors/kernel_density.py +++ b/python/cuml/cuml/neighbors/kernel_density.py @@ -255,24 +255,26 @@ def fit(self, X, y=None, sample_weight=None, *, convert_dtype=True): self : object Returns the instance itself. """ + self.X_ = input_to_cupy_array( + X, + order="C", + convert_to_dtype=(np.float32 if convert_dtype else None), + check_dtype=[cp.float32, cp.float64], + ).array + if sample_weight is not None: self.sample_weight_ = input_to_cupy_array( sample_weight, convert_to_dtype=(np.float32 if convert_dtype else None), check_dtype=[cp.float32, cp.float64], + check_cols=1, + check_rows=self.X_.shape[0], ).array if self.sample_weight_.min() <= 0: raise ValueError("sample_weight must have positive values") else: self.sample_weight_ = None - self.X_ = input_to_cupy_array( - X, - order="C", - convert_to_dtype=(np.float32 if convert_dtype else None), - check_dtype=[cp.float32, cp.float64], - ).array - return self def score_samples(self, X, *, convert_dtype=True): diff --git a/python/cuml/tests/test_kernel_density.py b/python/cuml/tests/test_kernel_density.py index adadf3e5bc..29a18af3c4 100644 --- a/python/cuml/tests/test_kernel_density.py +++ b/python/cuml/tests/test_kernel_density.py @@ -195,3 +195,16 @@ def test_not_fitted(): kde.sample(X) with pytest.raises(NotFittedError): kde.score_samples(X) + + +def test_bad_sample_weight_errors(): + kde = KernelDensity() + X = np.array([[0.0, 1.0], [2.0, 0.5]]) + + with pytest.raises(ValueError, match="Expected 2 rows but got 3 rows."): + kde.fit(X, sample_weight=np.array([1, 2, 3])) + + with pytest.raises( + ValueError, match="Expected 1 columns but got 2 columns." + ): + kde.fit(X, sample_weight=np.array([[1, 2], [3, 4]]))