Skip to content
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

[python-package] Fix misdetected objective after multiple calls to LGBMClassifier.fit #6002

Merged
merged 4 commits into from
Sep 12, 2023
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
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"