Skip to content

Commit

Permalink
[python-package] Fix misdetected objective after multiple calls to `L…
Browse files Browse the repository at this point in the history
…GBMClassifier.fit` (#6002)
  • Loading branch information
david-cortes authored Sep 12, 2023
1 parent 501ce1c commit 5e592fe
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 0 deletions.
2 changes: 2 additions & 0 deletions python-package/lightgbm/sklearn.py
Original file line number Diff line number Diff line change
Expand Up @@ -1103,6 +1103,8 @@ def fit( # type: ignore[override]

self._classes = self._le.classes_
self._n_classes = len(self._classes) # type: ignore[arg-type]
if self.objective is None:
self._objective = None

# adjust eval metrics to match whether binary or multiclass
# classification is being performed
Expand Down
17 changes: 17 additions & 0 deletions tests/python_package_test/test_sklearn.py
Original file line number Diff line number Diff line change
Expand Up @@ -1561,3 +1561,20 @@ def test_ranking_minimally_works_with_all_all_accepted_data_types(X_type, y_type
)
preds = model.predict(X)
assert spearmanr(preds, y).correlation >= 0.99


def test_classifier_fit_detects_classes_every_time():
rng = np.random.default_rng(seed=123)
nrows = 1000
ncols = 20

X = rng.standard_normal(size=(nrows, ncols))
y_bin = (rng.random(size=nrows) <= .3).astype(np.float64)
y_multi = rng.integers(4, size=nrows)

model = lgb.LGBMClassifier(verbose=-1)
for _ in range(2):
model.fit(X, y_multi)
assert model.objective_ == "multiclass"
model.fit(X, y_bin)
assert model.objective_ == "binary"

0 comments on commit 5e592fe

Please sign in to comment.