Skip to content

Commit af7df5c

Browse files
Fix Improve error when categorical_features is an empty list (scikit-learn#31146)
Signed-off-by: Pedro Lopes <pedro.m.a.r.lopes@tecnico.ulisboa.pt> Co-authored-by: Jérémie du Boisberranger <jeremie@probabl.ai>
1 parent 0b68836 commit af7df5c

File tree

3 files changed

+29
-0
lines changed

3 files changed

+29
-0
lines changed
Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
1+
- :func:`inspection.partial_dependence` now raises an informative error when passing
2+
an empty list as the `categorical_features` parameter. `None` should be used instead
3+
to indicate that no categorical features are present.
4+
By :user:`Pedro Lopes <pedroL0pes>`.

sklearn/inspection/_partial_dependence.py

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -673,6 +673,12 @@ def partial_dependence(
673673
is_categorical = [False] * len(features_indices)
674674
else:
675675
categorical_features = np.asarray(categorical_features)
676+
if categorical_features.size == 0:
677+
raise ValueError(
678+
"Passing an empty list (`[]`) to `categorical_features` is not "
679+
"supported. Use `None` instead to indicate that there are no "
680+
"categorical features."
681+
)
676682
if categorical_features.dtype.kind == "b":
677683
# categorical features provided as a list of boolean
678684
if categorical_features.size != n_features:

sklearn/inspection/tests/test_partial_dependence.py

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1196,3 +1196,22 @@ def test_reject_pandas_with_integer_dtype():
11961196
warnings.simplefilter("error")
11971197
partial_dependence(clf, X, features=["a"])
11981198
partial_dependence(clf, X, features=["c"], categorical_features=["c"])
1199+
1200+
1201+
def test_partial_dependence_empty_categorical_features():
1202+
"""Check that we raise the proper exception when `categorical_features`
1203+
is an empty list"""
1204+
clf = make_pipeline(StandardScaler(), LogisticRegression())
1205+
clf.fit(iris.data, iris.target)
1206+
1207+
with pytest.raises(
1208+
ValueError,
1209+
match=re.escape(
1210+
"Passing an empty list (`[]`) to `categorical_features` is not "
1211+
"supported. Use `None` instead to indicate that there are no "
1212+
"categorical features."
1213+
),
1214+
):
1215+
partial_dependence(
1216+
estimator=clf, X=iris.data, features=[0], categorical_features=[]
1217+
)

0 commit comments

Comments
 (0)