-
Notifications
You must be signed in to change notification settings - Fork 14
[Feature] create construct_scorecard and fix get_leafs and in lgb_constructor
#8
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
Merged
Merged
Changes from 4 commits
Commits
Show all changes
7 commits
Select commit
Hold shift + click to select a range
d39ef88
make get leaf simplify
RektPunk 08a6e93
make constuct scorecard
RektPunk 7eff6ec
diff base score for 0 tree
RektPunk 6073c6e
fix typo
RektPunk a7b392f
make test happy
RektPunk 8c220f7
fix: correct get_leafs() margin summation and add base score validation
xRiskLab 54b27a8
docs: clarify sklearn API vs internal booster base_score behavior
xRiskLab File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change | ||||||||||||||||||||||||||||||||||||||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
|
|
@@ -36,6 +36,7 @@ | |||||||||||||||||||||||||||||||||||||||||||||||
| import numpy as np | ||||||||||||||||||||||||||||||||||||||||||||||||
| import pandas as pd | ||||||||||||||||||||||||||||||||||||||||||||||||
| from lightgbm import LGBMClassifier | ||||||||||||||||||||||||||||||||||||||||||||||||
| from ._utils import calculate_information_value, calculate_weight_of_evidence | ||||||||||||||||||||||||||||||||||||||||||||||||
|
|
||||||||||||||||||||||||||||||||||||||||||||||||
| # Note: These will be needed when implementing the methods: | ||||||||||||||||||||||||||||||||||||||||||||||||
| # from typing import Optional | ||||||||||||||||||||||||||||||||||||||||||||||||
|
|
@@ -171,18 +172,9 @@ def get_leafs( | |||||||||||||||||||||||||||||||||||||||||||||||
| # Note: This is an approximation - pred_contrib gives feature contributions | ||||||||||||||||||||||||||||||||||||||||||||||||
| # For now, we'll use predict with num_iteration to get cumulative scores | ||||||||||||||||||||||||||||||||||||||||||||||||
| for i in range(n_trees): | ||||||||||||||||||||||||||||||||||||||||||||||||
| if i == 0: | ||||||||||||||||||||||||||||||||||||||||||||||||
| # First tree contribution is the raw score from just that tree | ||||||||||||||||||||||||||||||||||||||||||||||||
| tree_margin = ( | ||||||||||||||||||||||||||||||||||||||||||||||||
| self.model.predict(X, raw_score=True, num_iteration=1) - self.base_score | ||||||||||||||||||||||||||||||||||||||||||||||||
| ) | ||||||||||||||||||||||||||||||||||||||||||||||||
| else: | ||||||||||||||||||||||||||||||||||||||||||||||||
| # Subsequent trees: difference between cumulative scores | ||||||||||||||||||||||||||||||||||||||||||||||||
| curr_score = self.model.predict(X, raw_score=True, num_iteration=i + 1) | ||||||||||||||||||||||||||||||||||||||||||||||||
| prev_score = self.model.predict(X, raw_score=True, num_iteration=i) | ||||||||||||||||||||||||||||||||||||||||||||||||
| tree_margin = curr_score - prev_score | ||||||||||||||||||||||||||||||||||||||||||||||||
|
|
||||||||||||||||||||||||||||||||||||||||||||||||
| df_leafs[f"tree_{i}"] = tree_margin | ||||||||||||||||||||||||||||||||||||||||||||||||
| df_leafs[f"tree_{i}"] = self.model.predict( | ||||||||||||||||||||||||||||||||||||||||||||||||
| X, raw_score=True, start_iteration=i, num_iteration=1 | ||||||||||||||||||||||||||||||||||||||||||||||||
| ) - self.base_score * (i == 0) | ||||||||||||||||||||||||||||||||||||||||||||||||
|
|
||||||||||||||||||||||||||||||||||||||||||||||||
| return df_leafs | ||||||||||||||||||||||||||||||||||||||||||||||||
|
|
||||||||||||||||||||||||||||||||||||||||||||||||
|
|
@@ -220,6 +212,8 @@ def extract_leaf_weights(self) -> pd.DataFrame: | |||||||||||||||||||||||||||||||||||||||||||||||
| leaf_nodes = tree_df[tree_df["split_feature"].isna()][ | ||||||||||||||||||||||||||||||||||||||||||||||||
| ["tree_index", "node_index", "value"] | ||||||||||||||||||||||||||||||||||||||||||||||||
| ].copy() | ||||||||||||||||||||||||||||||||||||||||||||||||
| # Make leaf index relative within each tree | ||||||||||||||||||||||||||||||||||||||||||||||||
| leaf_nodes["relative_leaf_index"] = leaf_nodes.groupby("tree_index").cumcount() | ||||||||||||||||||||||||||||||||||||||||||||||||
|
|
||||||||||||||||||||||||||||||||||||||||||||||||
| # Helper function to merge decision nodes with leaf values | ||||||||||||||||||||||||||||||||||||||||||||||||
| def merge_and_format(decisions, leafs, child_column, sign): | ||||||||||||||||||||||||||||||||||||||||||||||||
|
|
@@ -232,7 +226,7 @@ def merge_and_format(decisions, leafs, child_column, sign): | |||||||||||||||||||||||||||||||||||||||||||||||
| ) | ||||||||||||||||||||||||||||||||||||||||||||||||
| result = merged.rename( | ||||||||||||||||||||||||||||||||||||||||||||||||
| columns={ | ||||||||||||||||||||||||||||||||||||||||||||||||
| "node_index_y": "Node", # Leaf node index | ||||||||||||||||||||||||||||||||||||||||||||||||
| "relative_leaf_index": "Node", # Leaf node index | ||||||||||||||||||||||||||||||||||||||||||||||||
| "split_feature": "Feature", | ||||||||||||||||||||||||||||||||||||||||||||||||
| "threshold": "Split", | ||||||||||||||||||||||||||||||||||||||||||||||||
| "value": "XAddEvidence", | ||||||||||||||||||||||||||||||||||||||||||||||||
|
|
@@ -266,10 +260,92 @@ def construct_scorecard(self) -> pd.DataFrame: | |||||||||||||||||||||||||||||||||||||||||||||||
| - Use get_leafs() to map observations to leaf nodes | ||||||||||||||||||||||||||||||||||||||||||||||||
| - Calculate event rates per leaf | ||||||||||||||||||||||||||||||||||||||||||||||||
| - Apply WOE/IV calculations from _utils | ||||||||||||||||||||||||||||||||||||||||||||||||
|
|
||||||||||||||||||||||||||||||||||||||||||||||||
| TODO: Implement this method following XGBoost pattern | ||||||||||||||||||||||||||||||||||||||||||||||||
| """ | ||||||||||||||||||||||||||||||||||||||||||||||||
| raise NotImplementedError("construct_scorecard() method needs to be implemented") | ||||||||||||||||||||||||||||||||||||||||||||||||
| n_trees = self.booster_.num_trees() | ||||||||||||||||||||||||||||||||||||||||||||||||
| labels = self.y | ||||||||||||||||||||||||||||||||||||||||||||||||
| tree_leaf_idx = self.booster_.predict(self.X, pred_leaf=True) | ||||||||||||||||||||||||||||||||||||||||||||||||
| if tree_leaf_idx.shape != (len(labels), n_trees): | ||||||||||||||||||||||||||||||||||||||||||||||||
| raise ValueError( | ||||||||||||||||||||||||||||||||||||||||||||||||
| f"Invalid leaf index shape {tree_leaf_idx.shape}. Expected {(len(labels), n_trees)}" | ||||||||||||||||||||||||||||||||||||||||||||||||
| ) | ||||||||||||||||||||||||||||||||||||||||||||||||
|
|
||||||||||||||||||||||||||||||||||||||||||||||||
| df_binning_table = pd.DataFrame() | ||||||||||||||||||||||||||||||||||||||||||||||||
| for i in range(n_trees): | ||||||||||||||||||||||||||||||||||||||||||||||||
| index_and_label = pd.concat( | ||||||||||||||||||||||||||||||||||||||||||||||||
| [ | ||||||||||||||||||||||||||||||||||||||||||||||||
| pd.Series(tree_leaf_idx[:, i], name="leaf_idx"), | ||||||||||||||||||||||||||||||||||||||||||||||||
| pd.Series(labels, name="label"), | ||||||||||||||||||||||||||||||||||||||||||||||||
| ], | ||||||||||||||||||||||||||||||||||||||||||||||||
| axis=1, | ||||||||||||||||||||||||||||||||||||||||||||||||
| ) | ||||||||||||||||||||||||||||||||||||||||||||||||
| # Create a binning table | ||||||||||||||||||||||||||||||||||||||||||||||||
| binning_table = ( | ||||||||||||||||||||||||||||||||||||||||||||||||
| index_and_label.groupby("leaf_idx").agg(["sum", "count"]).reset_index() | ||||||||||||||||||||||||||||||||||||||||||||||||
| ).astype(float) | ||||||||||||||||||||||||||||||||||||||||||||||||
| binning_table.columns = ["leaf_idx", "Events", "Count"] # type: ignore | ||||||||||||||||||||||||||||||||||||||||||||||||
| binning_table["tree"] = i | ||||||||||||||||||||||||||||||||||||||||||||||||
| binning_table["NonEvents"] = binning_table["Count"] - binning_table["Events"] | ||||||||||||||||||||||||||||||||||||||||||||||||
| binning_table["EventRate"] = binning_table["Events"] / binning_table["Count"] | ||||||||||||||||||||||||||||||||||||||||||||||||
| binning_table = binning_table[ | ||||||||||||||||||||||||||||||||||||||||||||||||
| ["tree", "leaf_idx", "Events", "NonEvents", "Count", "EventRate"] | ||||||||||||||||||||||||||||||||||||||||||||||||
| ] | ||||||||||||||||||||||||||||||||||||||||||||||||
|
Comment on lines
+294
to
+304
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. suggestion: Directly renaming columns after groupby/agg may be fragile if the aggregation changes. To avoid issues if aggregation changes, assign column names based on the aggregation output or reference columns by name rather than relying on order.
Suggested change
|
||||||||||||||||||||||||||||||||||||||||||||||||
| # Aggregate indices, leafs, and counts of events and non-events | ||||||||||||||||||||||||||||||||||||||||||||||||
| df_binning_table = pd.concat([df_binning_table, binning_table], axis=0) | ||||||||||||||||||||||||||||||||||||||||||||||||
| # Extract leaf weights (XAddEvidence) | ||||||||||||||||||||||||||||||||||||||||||||||||
| df_x_add_evidence = self.extract_leaf_weights() | ||||||||||||||||||||||||||||||||||||||||||||||||
| self.lgb_scorecard = df_x_add_evidence.merge( | ||||||||||||||||||||||||||||||||||||||||||||||||
| df_binning_table, | ||||||||||||||||||||||||||||||||||||||||||||||||
| left_on=["Tree", "Node"], | ||||||||||||||||||||||||||||||||||||||||||||||||
| right_on=["tree", "leaf_idx"], | ||||||||||||||||||||||||||||||||||||||||||||||||
| how="left", | ||||||||||||||||||||||||||||||||||||||||||||||||
| ).drop(["tree", "leaf_idx"], axis=1) | ||||||||||||||||||||||||||||||||||||||||||||||||
|
|
||||||||||||||||||||||||||||||||||||||||||||||||
| self.lgb_scorecard = self.lgb_scorecard[ | ||||||||||||||||||||||||||||||||||||||||||||||||
| [ | ||||||||||||||||||||||||||||||||||||||||||||||||
| "Tree", | ||||||||||||||||||||||||||||||||||||||||||||||||
| "Node", | ||||||||||||||||||||||||||||||||||||||||||||||||
| "Feature", | ||||||||||||||||||||||||||||||||||||||||||||||||
| "Sign", | ||||||||||||||||||||||||||||||||||||||||||||||||
| "Split", | ||||||||||||||||||||||||||||||||||||||||||||||||
| "Count", | ||||||||||||||||||||||||||||||||||||||||||||||||
| "NonEvents", | ||||||||||||||||||||||||||||||||||||||||||||||||
| "Events", | ||||||||||||||||||||||||||||||||||||||||||||||||
| "EventRate", | ||||||||||||||||||||||||||||||||||||||||||||||||
| "XAddEvidence", | ||||||||||||||||||||||||||||||||||||||||||||||||
| ] | ||||||||||||||||||||||||||||||||||||||||||||||||
| ] | ||||||||||||||||||||||||||||||||||||||||||||||||
|
|
||||||||||||||||||||||||||||||||||||||||||||||||
| # Sort by Tree and Node | ||||||||||||||||||||||||||||||||||||||||||||||||
| self.lgb_scorecard = self.lgb_scorecard.sort_values(by=["Tree", "Node"]).reset_index( | ||||||||||||||||||||||||||||||||||||||||||||||||
| drop=True | ||||||||||||||||||||||||||||||||||||||||||||||||
| ) | ||||||||||||||||||||||||||||||||||||||||||||||||
| # Get WOE and IV scores | ||||||||||||||||||||||||||||||||||||||||||||||||
| self.lgb_scorecard["WOE"] = calculate_weight_of_evidence(self.lgb_scorecard)["WOE"] | ||||||||||||||||||||||||||||||||||||||||||||||||
| self.lgb_scorecard["IV"] = calculate_information_value(self.lgb_scorecard)["IV"] | ||||||||||||||||||||||||||||||||||||||||||||||||
|
|
||||||||||||||||||||||||||||||||||||||||||||||||
| # Get % of observation counts in a Split | ||||||||||||||||||||||||||||||||||||||||||||||||
| self.lgb_scorecard["CountPct"] = self.lgb_scorecard["Count"] / self.lgb_scorecard.groupby( | ||||||||||||||||||||||||||||||||||||||||||||||||
| "Tree" | ||||||||||||||||||||||||||||||||||||||||||||||||
| )["Count"].transform("sum") | ||||||||||||||||||||||||||||||||||||||||||||||||
|
|
||||||||||||||||||||||||||||||||||||||||||||||||
| self.lgb_scorecard = self.lgb_scorecard[ | ||||||||||||||||||||||||||||||||||||||||||||||||
| [ | ||||||||||||||||||||||||||||||||||||||||||||||||
| "Tree", | ||||||||||||||||||||||||||||||||||||||||||||||||
| "Node", | ||||||||||||||||||||||||||||||||||||||||||||||||
| "Feature", | ||||||||||||||||||||||||||||||||||||||||||||||||
| "Sign", | ||||||||||||||||||||||||||||||||||||||||||||||||
| "Split", | ||||||||||||||||||||||||||||||||||||||||||||||||
| "Count", | ||||||||||||||||||||||||||||||||||||||||||||||||
| "CountPct", | ||||||||||||||||||||||||||||||||||||||||||||||||
| "NonEvents", | ||||||||||||||||||||||||||||||||||||||||||||||||
| "Events", | ||||||||||||||||||||||||||||||||||||||||||||||||
| "EventRate", | ||||||||||||||||||||||||||||||||||||||||||||||||
| "WOE", | ||||||||||||||||||||||||||||||||||||||||||||||||
| "IV", | ||||||||||||||||||||||||||||||||||||||||||||||||
| "XAddEvidence", | ||||||||||||||||||||||||||||||||||||||||||||||||
| ] | ||||||||||||||||||||||||||||||||||||||||||||||||
| ] | ||||||||||||||||||||||||||||||||||||||||||||||||
| return self.lgb_scorecard | ||||||||||||||||||||||||||||||||||||||||||||||||
|
|
||||||||||||||||||||||||||||||||||||||||||||||||
| def create_points( | ||||||||||||||||||||||||||||||||||||||||||||||||
| self, | ||||||||||||||||||||||||||||||||||||||||||||||||
|
|
||||||||||||||||||||||||||||||||||||||||||||||||
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
suggestion (bug_risk): Using cumcount for relative_leaf_index assumes leaf_nodes are sorted as intended.
Ensure leaf_nodes is sorted correctly within each tree before using cumcount to prevent incorrect relative indices.