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] add Booster.set_leaf_output method #5712

Merged
merged 2 commits into from
Feb 15, 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
32 changes: 32 additions & 0 deletions python-package/lightgbm/basic.py
Original file line number Diff line number Diff line change
Expand Up @@ -4043,6 +4043,38 @@ def get_leaf_output(self, tree_id: int, leaf_id: int) -> float:
ctypes.byref(ret)))
return ret.value

def set_leaf_output(
self,
tree_id: int,
leaf_id: int,
value: float,
) -> 'Booster':
"""Set the output of a leaf.

Parameters
----------
tree_id : int
The index of the tree.
leaf_id : int
The index of the leaf in the tree.
value : float
Value to set as the output of the leaf.

Returns
-------
self : Booster
Booster with the leaf output set.
"""
_safe_call(
_LIB.LGBM_BoosterSetLeafValue(
self.handle,
ctypes.c_int(tree_id),
ctypes.c_int(leaf_id),
ctypes.c_double(value)
)
)
return self

def _to_predictor(
self,
pred_parameter: Optional[Dict[str, Any]] = None
Expand Down
12 changes: 12 additions & 0 deletions tests/python_package_test/test_basic.py
Original file line number Diff line number Diff line change
Expand Up @@ -793,3 +793,15 @@ def test_feature_num_bin_with_max_bin_by_feature():
ds = lgb.Dataset(X, params={'max_bin_by_feature': max_bin_by_feature}).construct()
actual_num_bins = [ds.feature_num_bin(i) for i in range(X.shape[1])]
np.testing.assert_equal(actual_num_bins, max_bin_by_feature)


def test_set_leaf_output():
X, y = load_breast_cancer(return_X_y=True)
ds = lgb.Dataset(X, y)
bst = lgb.Booster({'num_leaves': 2}, ds)
bst.update()
y_pred = bst.predict(X)
for leaf_id in range(2):
leaf_output = bst.get_leaf_output(tree_id=0, leaf_id=leaf_id)
bst.set_leaf_output(tree_id=0, leaf_id=leaf_id, value=leaf_output + 1)
np.testing.assert_allclose(bst.predict(X), y_pred + 1)