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

WIP: [python-package] preserve params when copying Booster (fixes #5539) #6101

Draft
wants to merge 4 commits into
base: master
Choose a base branch
from
Draft
Changes from 1 commit
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
Prev Previous commit
Next Next commit
more tests
  • Loading branch information
jameslamb committed Sep 15, 2023
commit aea7f0fa92000c66307b6254ac222f52b9e426d6
6 changes: 3 additions & 3 deletions python-package/lightgbm/basic.py
Original file line number Diff line number Diff line change
@@ -3245,14 +3245,14 @@ def __init__(
params = self._get_loaded_param()
elif model_str is not None:
self.model_from_string(model_str)
# ensure params are updated on the C++ side
self.params = params
self.reset_parameter(params)
else:
raise TypeError('Need at least one training dataset or model file or model string '
'to create Booster instance')
self.params = params

# ensure params are updated on the C++ side
self.reset_parameter(params)

def __del__(self) -> None:
try:
if self._network:
24 changes: 20 additions & 4 deletions tests/python_package_test/test_basic.py
Original file line number Diff line number Diff line change
@@ -826,26 +826,42 @@ def test_feature_names_are_set_correctly_when_no_feature_names_passed_into_Datas


def test_booster_deepcopy_preserves_parameters():
orig_params = {
'num_leaves': 5,
'verbosity': -1
}
bst = lgb.train(
params={'num_leaves': 5, 'verbosity': -1},
params=orig_params,
num_boost_round=2,
train_set=lgb.Dataset(np.random.rand(100, 2))
)
bst2 = copy.deepcopy(bst)
bst2 = deepcopy(bst)
assert bst2.params == bst.params
assert bst.params["num_leaves"] == 5
assert bst.params["verbosity"] == -1

# passed-in params shouldn't have been modified outside of lightgbm
assert orig_params == {'num_leaves': 5, 'verbosity': -1}


def test_booster_params_kwarg_overrides_params_from_model_string():
orig_params = {
'num_leaves': 5,
'verbosity': -1
}
bst = lgb.train(
params={'num_leaves': 5, 'learning_rate': 0.708, 'verbosity': -1},
params=orig_params,
num_boost_round=2,
train_set=lgb.Dataset(np.random.rand(100, 2))
)
bst2 = lgb.Booster(
params={'num_leaves': 7},
model_str=bst.model_to_string()
)

# params should have been updated on the Python object and the C++ side
assert bst2.params["num_leaves"] == 7
assert bst2.params["learning_rate"] == 0.708
assert "[num_leaves: 7]" in bst2.model_to_string()

# passed-in params shouldn't have been modified outside of lightgbm
assert orig_params == {'num_leaves': 5, 'verbosity': -1}