Skip to content
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
29 changes: 25 additions & 4 deletions docs/source/user/mip-models.rst
Original file line number Diff line number Diff line change
Expand Up @@ -394,12 +394,33 @@ Recomputing the prediction at :math:`x` (as ``get_error()`` does) is not a
reliable check either: :math:`x` may sit exactly on a threshold, and the
regression may round its inputs (scikit-learn evaluates them in single
precision, so a positive ``epsilon`` only helps if it exceeds that rounding),
so it can route :math:`x` down the other branch. To know which leaf
each tree selected, read the leaf variables in the
so it can route :math:`x` down the other branch.

To check a solution, call
:py:meth:`project_input()
<gurobi_ml.modeling.decision_tree.decision_tree_model.TreeLeavesAccessor.project_input>`
on the returned object after solving the model:

.. code-block:: python

pred_constr = add_predictor_constr(model, regressor, x, y)
model.optimize()
x_projected = pred_constr.project_input()
regressor.predict(x_projected) # equals y.X up to rounding

It moves each row of :math:`x` to the closest input that lies in the leaves
selected by all trees, in the precision in which the regression evaluates its
inputs; pass the returned array to the regression as it is. A row of NaN
means that the selected leaves have no input in common: no input attains the
value of the output variables. The method changes neither the model nor its
solution, so if :math:`x` is subject to other constraints, check them at the
returned input too.

The leaf variables themselves are in the
:py:attr:`tree_leaves
<gurobi_ml.modeling.decision_tree.decision_tree_model.TreeLeavesAccessor.tree_leaves>`
attribute of the returned object rather than comparing :math:`x` with the
thresholds. The
attribute of the returned object, for example to add constraints on the
selected leaves. The
`Tree Ensemble Formulations notebook <https://github.com/Gurobi/gurobi-machinelearning/blob/main/notebooks/tree-ensembles/Tree%20Ensemble%20Formulations.ipynb>`_
shows how to read them and check a solution.

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -254,8 +254,8 @@
"`predict`: `objective` and `prediction at x` agree in the table above. With\n",
"`\"misic\"`, the interval is excluded at every threshold of the ensemble, which\n",
"can make the model infeasible. The last section, *Advanced: check a solution\n",
"with the selected leaves*, checks solutions with the leaves read from\n",
"`tree_leaves` rather than with the prediction at `x`.\n",
"with the selected leaves*, checks solutions with `project_input()` rather than\n",
"with the prediction at `x`.\n",
"\n",
"See [Split Thresholds and Exactness](https://gurobi-optimization-gurobi-machine-learning.readthedocs-hosted.com/en/latest/user/mip-models.html#split-thresholds-and-exactness)\n",
"in the user guide before interpreting this as achievable predicted activity,\n",
Expand Down Expand Up @@ -429,10 +429,12 @@
"The prediction at `x` is not an exact check of a solution: `x` can lie\n",
"exactly on a split threshold, and `predict` rounds its input to single\n",
"precision, so the forest can send `x` down a different branch than the model\n",
"did. Instead, we intersect the boxes of the inputs reaching the leaves\n",
"selected in `prediction.tree_leaves`. If the intersection is empty, no input\n",
"attains the objective. Otherwise, we move `x` to the closest single-precision\n",
"point inside it, like rounding a MIP solution, and evaluate `predict` there.\n",
"did. Instead, we call `project_input()` on the object returned by\n",
"`add_predictor_constr`. It intersects the boxes of the inputs reaching the\n",
"leaves selected in the solution and moves `x` to the closest single-precision\n",
"point inside the intersection, like rounding a MIP solution. If the\n",
"intersection is empty, no input attains the objective, and `project_input()`\n",
"returns NaN. Otherwise, we evaluate `predict` at the moved `x`.\n",
"Below, we solve the five formulations again with `c = 0.1` and also check\n",
"the shared-leaf restriction at the moved `x`, since other constraints on `x`\n",
"must hold there too."
Expand All @@ -445,59 +447,14 @@
"metadata": {},
"outputs": [],
"source": [
"def leaf_box(tree, leaf):\n",
" \"\"\"Bounds lo < x <= hi of the inputs reaching a leaf of a scikit-learn tree.\"\"\"\n",
" lo = np.full(tree.n_features, -np.inf)\n",
" hi = np.full(tree.n_features, np.inf)\n",
" parent = {}\n",
" for node in range(tree.node_count):\n",
" if tree.children_left[node] >= 0:\n",
" parent[tree.children_left[node]] = (node, True)\n",
" parent[tree.children_right[node]] = (node, False)\n",
" node = leaf\n",
" while node in parent:\n",
" node, went_left = parent[node]\n",
" feature, threshold = tree.feature[node], tree.threshold[node]\n",
" if went_left:\n",
" hi[feature] = min(hi[feature], threshold)\n",
" else:\n",
" lo[feature] = max(lo[feature], threshold)\n",
" return lo, hi\n",
"\n",
"\n",
"def selected_box(forest, prediction):\n",
" \"\"\"Intersection of the boxes of the leaves selected in prediction.\"\"\"\n",
" lo = np.full(forest.n_features_in_, -np.inf)\n",
" hi = np.full(forest.n_features_in_, np.inf)\n",
" for estimator, leaves in zip(forest.estimators_, prediction.tree_leaves):\n",
" # One column of leaves.variables per reachable leaf, whose node id in\n",
" # the scikit-learn tree is in leaves.nodes; row 0 is our only input.\n",
" selected = leaves.nodes[np.argmax(leaves.variables.X[0])]\n",
" box_lo, box_hi = leaf_box(estimator.tree_, selected)\n",
" lo = np.maximum(lo, box_lo)\n",
" hi = np.minimum(hi, box_hi)\n",
" return lo, hi\n",
"\n",
"\n",
"def project_to_box(x, lo, hi):\n",
" \"\"\"The closest single-precision point with lo < x <= hi, or None.\"\"\"\n",
" lo32 = lo.astype(np.float32)\n",
" lo32 = np.where(lo32 > lo, lo32, np.nextafter(lo32, np.float32(np.inf)))\n",
" hi32 = hi.astype(np.float32)\n",
" hi32 = np.where(hi32 <= hi, hi32, np.nextafter(hi32, np.float32(-np.inf)))\n",
" if np.any(lo32 > hi32):\n",
" return None\n",
" return np.clip(x.astype(np.float32), lo32, hi32)\n",
"\n",
"\n",
"def check_leaves(forest, prediction, x):\n",
" \"\"\"Check the solution x with the leaves selected in prediction.\n",
"\n",
" Return the results and x moved into the selected leaves, or None if no\n",
" input reaches them.\n",
" \"\"\"\n",
" moved = project_to_box(x, *selected_box(forest, prediction))\n",
" if moved is None:\n",
" moved = prediction.project_input()[0] # row 0 is our only input\n",
" if np.isnan(moved).any():\n",
" results = {\n",
" \"leaves reachable\": False,\n",
" \"max shift\": np.nan,\n",
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -244,8 +244,8 @@
"excluding a wider interval above every threshold, which can cut off the\n",
"optimum or make the model infeasible. Even with a positive `epsilon`,\n",
"`prediction at x` is not an exactness check (the wine rows of the formulation\n",
"comparison below show why); the last section checks a solution with the\n",
"leaves selected in `tree_leaves` instead.\n",
"comparison below show why); the last section checks a solution with\n",
"`project_input()` instead.\n",
"\n",
"See [Split Thresholds and Exactness](https://gurobi-optimization-gurobi-machine-learning.readthedocs-hosted.com/en/latest/user/mip-models.html#split-thresholds-and-exactness) in the user guide, and\n",
"[Tree Ensemble Formulations](Tree%20Ensemble%20Formulations.ipynb) for the\n",
Expand Down Expand Up @@ -380,8 +380,8 @@
"`x <= threshold` holds, but `predict` rounds the input to single precision,\n",
"which moves it just above the threshold and down the right branch. `epsilon`\n",
"only applies to right branches and cannot prevent this. The objective is\n",
"still attained: the leaves selected in `tree_leaves` contain a common input,\n",
"as the last section shows.\n",
"still attained: the selected leaves contain a common input, as the last\n",
"section shows.\n",
"\n",
"Rankings depend on the ensemble, surrounding constraints, hardware, Gurobi\n",
"version, threads, and seed. These results are not a substitute for testing\n",
Expand All @@ -397,12 +397,14 @@
"\n",
"`prediction at x` is not an exact check of a solution: $x$ can sit exactly on\n",
"a split threshold, and `predict` rounds its input to single precision, which\n",
"can send $x$ down the other branch. Instead, we intersect the boxes of inputs\n",
"that reach the leaves selected in `prediction.tree_leaves`, one per tree. If\n",
"the intersection is empty, no input attains the objective. Otherwise, we move\n",
"$x$ to the closest single-precision point inside it, like rounding a MIP\n",
"solution, and evaluate `predict` there. If $x$ is subject to other\n",
"constraints, check them at the moved point too."
"can send $x$ down the other branch. Instead, we call `project_input()` on the\n",
"object returned by `add_predictor_constr`. It intersects the boxes of inputs\n",
"that reach the leaves selected in the solution, one per tree, and moves $x$\n",
"to the closest single-precision point inside the intersection, like rounding\n",
"a MIP solution. If the intersection is empty, no input attains the objective,\n",
"and `project_input()` returns NaN. Otherwise, we evaluate `predict` at the\n",
"moved point. If $x$ is subject to other constraints, check them at the moved\n",
"point too."
]
},
{
Expand All @@ -412,59 +414,14 @@
"metadata": {},
"outputs": [],
"source": [
"def leaf_box(tree, leaf):\n",
" \"\"\"Bounds lo < x <= hi of the inputs reaching a leaf of a scikit-learn tree.\"\"\"\n",
" lo = np.full(tree.n_features, -np.inf)\n",
" hi = np.full(tree.n_features, np.inf)\n",
" parent = {}\n",
" for node in range(tree.node_count):\n",
" if tree.children_left[node] >= 0:\n",
" parent[tree.children_left[node]] = (node, True)\n",
" parent[tree.children_right[node]] = (node, False)\n",
" node = leaf\n",
" while node in parent:\n",
" node, went_left = parent[node]\n",
" feature, threshold = tree.feature[node], tree.threshold[node]\n",
" if went_left:\n",
" hi[feature] = min(hi[feature], threshold)\n",
" else:\n",
" lo[feature] = max(lo[feature], threshold)\n",
" return lo, hi\n",
"\n",
"\n",
"def selected_box(forest, prediction):\n",
" \"\"\"Intersection of the boxes of the leaves selected in prediction.\"\"\"\n",
" lo = np.full(forest.n_features_in_, -np.inf)\n",
" hi = np.full(forest.n_features_in_, np.inf)\n",
" for estimator, leaves in zip(forest.estimators_, prediction.tree_leaves):\n",
" # One column of leaves.variables per reachable leaf, whose node id in\n",
" # the scikit-learn tree is in leaves.nodes; row 0 is our only input.\n",
" selected = leaves.nodes[np.argmax(leaves.variables.X[0])]\n",
" box_lo, box_hi = leaf_box(estimator.tree_, selected)\n",
" lo = np.maximum(lo, box_lo)\n",
" hi = np.minimum(hi, box_hi)\n",
" return lo, hi\n",
"\n",
"\n",
"def project_to_box(x, lo, hi):\n",
" \"\"\"The closest single-precision point with lo < x <= hi, or None.\"\"\"\n",
" lo32 = lo.astype(np.float32)\n",
" lo32 = np.where(lo32 > lo, lo32, np.nextafter(lo32, np.float32(np.inf)))\n",
" hi32 = hi.astype(np.float32)\n",
" hi32 = np.where(hi32 <= hi, hi32, np.nextafter(hi32, np.float32(-np.inf)))\n",
" if np.any(lo32 > hi32):\n",
" return None\n",
" return np.clip(x.astype(np.float32), lo32, hi32)\n",
"\n",
"\n",
"def check_leaves(forest, prediction, x):\n",
" \"\"\"Check the solution x with the leaves selected in prediction.\n",
"\n",
" Return the results and x moved into the selected leaves, or None if no\n",
" input reaches them.\n",
" \"\"\"\n",
" moved = project_to_box(x, *selected_box(forest, prediction))\n",
" if moved is None:\n",
" moved = prediction.project_input()[0] # row 0 is our only input\n",
" if np.isnan(moved).any():\n",
" results = {\n",
" \"leaves reachable\": False,\n",
" \"max shift\": np.nan,\n",
Expand Down
78 changes: 23 additions & 55 deletions notebooks/tree-ensembles/Tree Ensemble Formulations.ipynb
Original file line number Diff line number Diff line change
Expand Up @@ -283,8 +283,8 @@
"can be reached) and the node ids `nodes` of those leaves in the scikit-learn\n",
"tree.\n",
"\n",
"Below, `leaf_box` computes the box of inputs reaching a leaf of a scikit-learn\n",
"tree. The inputs reaching a leaf satisfy $lo < x \\le hi$ componentwise."
"Below are the node ids of the leaves selected in each tree (columns) with\n",
"each formulation (rows):"
]
},
{
Expand All @@ -294,39 +294,32 @@
"metadata": {},
"outputs": [],
"source": [
"def leaf_box(tree, leaf):\n",
" lo = np.full(tree.n_features, -np.inf)\n",
" hi = np.full(tree.n_features, np.inf)\n",
" parent = {}\n",
" for node in range(tree.node_count):\n",
" if tree.children_left[node] >= 0:\n",
" parent[tree.children_left[node]] = (node, True)\n",
" parent[tree.children_right[node]] = (node, False)\n",
" node = leaf\n",
" while node in parent:\n",
" node, went_left = parent[node]\n",
" feature, threshold = tree.feature[node], tree.threshold[node]\n",
" if went_left:\n",
" hi[feature] = min(hi[feature], threshold)\n",
" else:\n",
" lo[feature] = max(lo[feature], threshold)\n",
" return lo, hi"
"selected_leaves = {}\n",
"for formulation, (pred_constr, _) in solutions.items():\n",
" selected_leaves[formulation] = [\n",
" leaves.nodes[np.argmax(leaves.variables.X[0])]\n",
" for leaves in pred_constr.tree_leaves\n",
" ]\n",
"pd.DataFrame(selected_leaves).rename_axis(\"tree\").T"
]
},
{
"cell_type": "markdown",
"id": "19",
"metadata": {},
"source": [
"For a solution, we intersect the boxes of the selected leaves of all trees.\n",
"If the intersection is empty, no input reaches this combination of leaves: the\n",
"objective value is not attained by the regression. Otherwise, we project $x$\n",
"onto the intersection, changing each component as little as possible, like\n",
"rounding the integer variables of a MIP solution. `predict` evaluates its input\n",
"in single precision, so the projection moves $x$ to single precision values.\n",
"The column `max shift` gives the largest change of a component of $x$; if $x$\n",
"is subject to other constraints, the projected input may violate them by that\n",
"much."
"The inputs reaching a leaf form a box: they satisfy $lo < x \\le hi$\n",
"componentwise, with bounds given by the thresholds on the path to the leaf.\n",
"For a solution, the `project_input` method intersects the boxes of the\n",
"selected leaves of all trees. If the intersection is empty, no input reaches\n",
"this combination of leaves: the objective value is not attained by the\n",
"regression, and `project_input` returns NaN. Otherwise, it projects $x$ onto\n",
"the intersection, changing each component as little as possible, like\n",
"rounding the integer variables of a MIP solution. `predict` evaluates its\n",
"input in single precision, so the projection moves $x$ to single precision\n",
"values. The column `max shift` gives the largest change of a component of\n",
"$x$; if $x$ is subject to other constraints, the projected input may violate\n",
"them by that much."
]
},
{
Expand All @@ -336,34 +329,9 @@
"metadata": {},
"outputs": [],
"source": [
"trees = [estimator[0].tree_ for estimator in regression.estimators_]\n",
"\n",
"\n",
"def selected_box(pred_constr):\n",
" lo = np.full(X.shape[1], -np.inf)\n",
" hi = np.full(X.shape[1], np.inf)\n",
" for tree, leaves in zip(trees, pred_constr.tree_leaves):\n",
" selected = leaves.nodes[np.argmax(leaves.variables.X[0])]\n",
" box_lo, box_hi = leaf_box(tree, selected)\n",
" lo = np.maximum(lo, box_lo)\n",
" hi = np.minimum(hi, box_hi)\n",
" return lo, hi\n",
"\n",
"\n",
"def project_to_box(x, lo, hi):\n",
" # The closest single precision values with lo < x <= hi, or None.\n",
" lo32 = lo.astype(np.float32)\n",
" lo32 = np.where(lo32 > lo, lo32, np.nextafter(lo32, np.float32(np.inf)))\n",
" hi32 = hi.astype(np.float32)\n",
" hi32 = np.where(hi32 <= hi, hi32, np.nextafter(hi32, np.float32(-np.inf)))\n",
" if np.any(lo32 > hi32):\n",
" return None\n",
" return np.clip(x.astype(np.float32), lo32, hi32)\n",
"\n",
"\n",
"def check_leaves(pred_constr, x):\n",
" x_projected = project_to_box(x, *selected_box(pred_constr))\n",
" if x_projected is None:\n",
" x_projected = pred_constr.project_input()\n",
" if np.isnan(x_projected).any():\n",
" return {\n",
" \"leaves reachable\": False,\n",
" \"max shift\": np.nan,\n",
Expand Down
20 changes: 11 additions & 9 deletions src/gurobi_ml/lightgbm/lgbm_regressor.py
Original file line number Diff line number Diff line change
Expand Up @@ -179,6 +179,8 @@ class LGBMConstr(TreeLeavesAccessor, AbstractPredictorConstr):
|ClassShort|
"""

_input_dtype = np.float64

def __init__(
self,
gp_model,
Expand Down Expand Up @@ -274,7 +276,7 @@ def _flat_tree_representation(root_node):
children_right = np.full(numnodes, -2, dtype=int)
feature = np.empty(numnodes, dtype=int)
value = np.empty(numnodes, dtype=np.float32)
threshold = np.empty(numnodes, dtype=np.float32)
threshold = np.empty(numnodes, dtype=np.float64)

def node_index(node):
if "split_index" in node:
Expand Down Expand Up @@ -346,13 +348,15 @@ def _mip_model(self, **kwargs):

n_estimators = len(trees_raw)

trees = []
for tree in trees_raw:
flat_tree = self._flat_tree_representation(tree["tree_structure"])
flat_tree["n_features"] = lgbm_raw["max_feature_idx"] + 1
trees.append(flat_tree)
self._trees = trees

formulation = _formulation_kwarg(kwargs)
if formulation in ENSEMBLE_FORMULATIONS:
trees = []
for tree in trees_raw:
flat_tree = self._flat_tree_representation(tree["tree_structure"])
flat_tree["n_features"] = lgbm_raw["max_feature_idx"] + 1
trees.append(flat_tree)
self._tree_leaves = add_tree_ensemble_formulation(
model,
trees,
Expand All @@ -376,11 +380,9 @@ def _mip_model(self, **kwargs):
name=self._name_var("estimator"),
)

for i, tree in enumerate(trees_raw):
for i, flat_tree in enumerate(trees):
if self.verbose:
self._timer.timing(f"Estimator {i}")
flat_tree = self._flat_tree_representation(tree["tree_structure"])
flat_tree["n_features"] = lgbm_raw["max_feature_idx"] + 1

estimators.append(
AbstractTreeEstimator(
Expand Down
Loading
Loading