From f260e57694e91ce598c56f4a8146e07077401df5 Mon Sep 17 00:00:00 2001 From: hal0taso <11371960+hal0taso@users.noreply.github.com> Date: Sat, 14 Nov 2026 19:55:58 +0000 Subject: [PATCH 1/2] Add project_input() to check tree solutions Solver tolerances and float32 rounding can leave the input of a solution outside the leaves it selects, so predict(x) need not match the output variable. - Add project_input() to the tree constraint classes. It returns the closest input inside the selected leaves, in the precision the regressor evaluates, or NaN rows if the leaves share no input. - Share the projection across frameworks; each wrapper stores its trees and declares its strict side and input precision. - Keep LightGBM thresholds in float64, as LightGBM compares them. - Call add_tree_ensemble_formulation directly from the sklearn ensembles and drop the helper that converted the trees again. - Document the parameters of _compute_leafs_bounds. Co-Authored-By: Claude Fable 5.2 --- src/gurobi_ml/lightgbm/lgbm_regressor.py | 20 +++-- .../modeling/decision_tree/_common.py | 63 +++++++++++++- .../decision_tree/decision_tree_model.py | 46 ++++++++++ .../sklearn/decision_tree_regressor.py | 40 +-------- .../sklearn/gradient_boosting_regressor.py | 11 ++- .../sklearn/random_forest_regressor.py | 11 ++- src/gurobi_ml/xgboost/xgboost_regressor.py | 12 ++- tests/test_lightgbm/test_project_input.py | 21 +++++ tests/test_sklearn/test_project_input.py | 46 ++++++++++ tests/test_xgboost/test_project_input.py | 21 +++++ tests/tree_ensemble.py | 85 +++++++++++++++++++ 11 files changed, 318 insertions(+), 58 deletions(-) create mode 100644 tests/test_lightgbm/test_project_input.py create mode 100644 tests/test_sklearn/test_project_input.py create mode 100644 tests/test_xgboost/test_project_input.py diff --git a/src/gurobi_ml/lightgbm/lgbm_regressor.py b/src/gurobi_ml/lightgbm/lgbm_regressor.py index b81c9b5d..e9b01a68 100644 --- a/src/gurobi_ml/lightgbm/lgbm_regressor.py +++ b/src/gurobi_ml/lightgbm/lgbm_regressor.py @@ -179,6 +179,8 @@ class LGBMConstr(TreeLeavesAccessor, AbstractPredictorConstr): |ClassShort| """ + _input_dtype = np.float64 + def __init__( self, gp_model, @@ -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: @@ -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, @@ -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( diff --git a/src/gurobi_ml/modeling/decision_tree/_common.py b/src/gurobi_ml/modeling/decision_tree/_common.py index 2fee9406..9f068798 100644 --- a/src/gurobi_ml/modeling/decision_tree/_common.py +++ b/src/gurobi_ml/modeling/decision_tree/_common.py @@ -142,10 +142,29 @@ def _compute_leafs_bounds(gp_model, tree, safety_floor=0.0): side by epsilon (see :py:func:`_split_offsets`), only for the inputs whose bounds do not decide the split. + The formulations call this with the model they are building. It is also + called without a model (``gp_model=None``) to check a solution, by + :py:func:`_project_to_leaves`. + Parameters ---------- + gp_model : :external+gurobi:py:class:`Model` or None + Model the tree is formulated in. Only its ``FeasibilityTol`` is + read, to warn about nonzero thresholds smaller than it. With None, + there is no such warning. tree : dict The decision tree to model. + safety_floor : float, optional + Nonzero thresholds smaller than this in absolute value are moved + to it, keeping their sign. The default 0.0 leaves the thresholds + unchanged. + + Returns + ------- + node_lb, node_ub : np.ndarray + Lower and upper bounds of the input box routed to each node, of + shape ``(n_features, capacity)``. A side with no split is + ``-GRB.INFINITY`` or ``GRB.INFINITY``. """ capacity = tree["capacity"] n_features = tree["n_features"] @@ -161,7 +180,8 @@ def _compute_leafs_bounds(gp_model, tree, safety_floor=0.0): 0, ] - feas_tol = gp_model.Params.FeasibilityTol + # Without a model (checking a solution), skip the tolerance warning. + feas_tol = gp_model.Params.FeasibilityTol if gp_model is not None else 0.0 while len(stack) > 0: node = stack.pop() @@ -195,6 +215,47 @@ def _compute_leafs_bounds(gp_model, tree, safety_floor=0.0): return (node_lb, node_ub) +def _round_up(values, dtype, strict): + """Smallest values of dtype above (strict) or at least ``values``.""" + rounded = values.astype(dtype) + keep = rounded > values if strict else rounded >= values + return np.where(keep, rounded, np.nextafter(rounded, dtype(np.inf))) + + +def _round_down(values, dtype, strict): + """Largest values of dtype below (strict) or at most ``values``.""" + rounded = values.astype(dtype) + keep = rounded < values if strict else rounded <= values + return np.where(keep, rounded, np.nextafter(rounded, dtype(-np.inf))) + + +def _project_to_leaves(trees, tree_leaves, x, left_strict, dtype): + """Move each row of x into the leaves selected in the solution. + + Intersect, row by row, the boxes of the leaves selected in each tree + and clip x to the intersection, in the precision ``dtype`` in which the + regression evaluates its inputs. The box of a leaf is ``lo < x <= hi``, + or ``lo <= x < hi`` if ``left_strict``. Rows whose selected leaves have + no input in common are NaN. + """ + lo = np.full(x.shape, -np.inf) + hi = np.full(x.shape, np.inf) + for tree, leaves in zip(trees, tree_leaves): + selected = leaves.nodes[np.argmax(leaves.variables.X, axis=1)] + node_lb, node_ub = _compute_leafs_bounds(None, tree) + lo = np.maximum(lo, node_lb[:, selected].T) + hi = np.minimum(hi, node_ub[:, selected].T) + # A side with no split is +-GRB.INFINITY: make it a true infinity, which + # every dtype can represent. + lo[lo <= -GRB.INFINITY] = -np.inf + hi[hi >= GRB.INFINITY] = np.inf + lo = _round_up(lo, dtype, strict=not left_strict) + hi = _round_down(hi, dtype, strict=left_strict) + projected = np.clip(x.astype(dtype), lo, hi).astype(float) + projected[(lo > hi).any(axis=1)] = np.nan + return projected + + def _compute_reachability(gp_model, tree, _input, epsilon, nodes, safety_floor=0.0): """Which examples can reach which of the given tree nodes. diff --git a/src/gurobi_ml/modeling/decision_tree/decision_tree_model.py b/src/gurobi_ml/modeling/decision_tree/decision_tree_model.py index 49c3805c..bbfed0ff 100644 --- a/src/gurobi_ml/modeling/decision_tree/decision_tree_model.py +++ b/src/gurobi_ml/modeling/decision_tree/decision_tree_model.py @@ -20,6 +20,7 @@ import numpy as np from gurobipy import GRB +from ...exceptions import NoSolutionError from ..base_predictor_constr import AbstractPredictorConstr from ._common import ( TreeLeaves, @@ -27,6 +28,7 @@ _goes_left, _goes_right, _no_reachable_leaf_error, + _project_to_leaves, ) from .biggs_perakis import _biggs_perakis_formulation from .ensemble_model import ENSEMBLE_FORMULATIONS, add_tree_ensemble_formulation @@ -45,6 +47,49 @@ class TreeLeavesAccessor: """Mixin exposing per-tree leaf variables.""" _tree_leaves = None + #: The trees in the order of ``tree_leaves``, as dictionaries (see + #: :py:class:`AbstractTreeEstimator`). + _trees = None + #: How the regression routes an input: left iff ``x <= threshold``, + #: or ``x < threshold`` if ``_left_strict``, with ``x`` rounded to + #: ``_input_dtype``. + _left_strict = False + _input_dtype = np.float32 + + def project_input(self): + """Inputs that reach the leaves selected in the solution. + + For each input row, the point closest to ``input_values`` that every + tree sends to the leaf it selected in the solution, in the precision + the regression uses to evaluate its inputs. Evaluating the regression + there gives the predicted values the solution relies on, even when + ``input_values`` sits on a split threshold. If the selected leaves + have no input in common, the row is NaN: no input attains the + values of the output variables. Other constraints on the input are + not taken into account. + + Pass the returned array to the regression as it is: converting it to + another precision can move a value across a threshold. + + Returns + ------- + numpy.ndarray + Array of shape (number of inputs, number of features). + + Raises + ------ + NoSolutionError + If the Gurobi model has no solution. + AttributeError + If the formulation does not expose leaf variables (``"paths"``). + """ + tree_leaves = self.tree_leaves + if not self._has_solution: + raise NoSolutionError() + x = np.asarray(self.input_values, dtype=float) + return _project_to_leaves( + self._trees, tree_leaves, x, self._left_strict, self._input_dtype + ) @property def tree_leaves(self): @@ -318,6 +363,7 @@ def __init__( ): self._default_name = "tree" self._tree = tree + self._trees = [tree] self._epsilon = epsilon self._safety_floor = safety_floor diff --git a/src/gurobi_ml/sklearn/decision_tree_regressor.py b/src/gurobi_ml/sklearn/decision_tree_regressor.py index fdc3ce45..9785c8f7 100644 --- a/src/gurobi_ml/sklearn/decision_tree_regressor.py +++ b/src/gurobi_ml/sklearn/decision_tree_regressor.py @@ -18,10 +18,7 @@ in a :external+gurobi:py:class:`Model`. """ -from ..modeling.decision_tree import ( - AbstractTreeEstimator, - add_tree_ensemble_formulation, -) +from ..modeling.decision_tree import AbstractTreeEstimator from .skgetter import SKgetter @@ -39,41 +36,6 @@ def _sklearn_tree_to_dict(tree): } -def _add_sklearn_tree_ensemble_formulation( - gp_model, - estimators, - weights, - input_vars, - output_vars, - formulation, - epsilon, - name_var, - safety_floor=0.0, - constant=0.0, - output_coef=1.0, -): - """Formulate a list of fitted sklearn decision trees as one ensemble. - - Shared by the gradient boosting and random forest classes; they differ - only in how the tree predictions are combined. Returns the per-tree - leaf variables. - """ - trees = [_sklearn_tree_to_dict(estimator.tree_) for estimator in estimators] - return add_tree_ensemble_formulation( - gp_model, - trees, - weights, - input_vars, - output_vars, - formulation, - epsilon, - name_var, - safety_floor=safety_floor, - constant=constant, - output_coef=output_coef, - ) - - def add_decision_tree_regressor_constr( gp_model, decision_tree_regressor, diff --git a/src/gurobi_ml/sklearn/gradient_boosting_regressor.py b/src/gurobi_ml/sklearn/gradient_boosting_regressor.py index 16a87a91..8edbc42d 100644 --- a/src/gurobi_ml/sklearn/gradient_boosting_regressor.py +++ b/src/gurobi_ml/sklearn/gradient_boosting_regressor.py @@ -28,9 +28,10 @@ TreeLeavesAccessor, _flatten_tree_leaves, _formulation_kwarg, + add_tree_ensemble_formulation, ) from .decision_tree_regressor import ( - _add_sklearn_tree_ensemble_formulation, + _sklearn_tree_to_dict, add_decision_tree_regressor_constr, ) from .skgetter import SKgetter @@ -145,11 +146,15 @@ def _mip_model(self, **kwargs): "Output dimension of gradient boosting regressor should be 1", ) + self._trees = [ + _sklearn_tree_to_dict(estimator[0].tree_) + for estimator in predictor.estimators_ + ] formulation = _formulation_kwarg(kwargs) if formulation in ENSEMBLE_FORMULATIONS: - self._tree_leaves = _add_sklearn_tree_ensemble_formulation( + self._tree_leaves = add_tree_ensemble_formulation( model, - [predictor.estimators_[i][0] for i in range(predictor.n_estimators_)], + self._trees, np.full(predictor.n_estimators_, predictor.learning_rate), _input, output, diff --git a/src/gurobi_ml/sklearn/random_forest_regressor.py b/src/gurobi_ml/sklearn/random_forest_regressor.py index b079c8e1..b28551f8 100644 --- a/src/gurobi_ml/sklearn/random_forest_regressor.py +++ b/src/gurobi_ml/sklearn/random_forest_regressor.py @@ -27,9 +27,10 @@ TreeLeavesAccessor, _flatten_tree_leaves, _formulation_kwarg, + add_tree_ensemble_formulation, ) from .decision_tree_regressor import ( - _add_sklearn_tree_ensemble_formulation, + _sklearn_tree_to_dict, add_decision_tree_regressor_constr, ) from .skgetter import SKgetter @@ -136,11 +137,15 @@ def _mip_model(self, **kwargs): output = self._output nex = _input.shape[0] + self._trees = [ + _sklearn_tree_to_dict(estimator.tree_) + for estimator in predictor.estimators_ + ] formulation = _formulation_kwarg(kwargs) if formulation in ENSEMBLE_FORMULATIONS: - self._tree_leaves = _add_sklearn_tree_ensemble_formulation( + self._tree_leaves = add_tree_ensemble_formulation( model, - predictor.estimators_, + self._trees, np.ones(predictor.n_estimators), _input, output, diff --git a/src/gurobi_ml/xgboost/xgboost_regressor.py b/src/gurobi_ml/xgboost/xgboost_regressor.py index 42de7bfe..7cf5f9b2 100644 --- a/src/gurobi_ml/xgboost/xgboost_regressor.py +++ b/src/gurobi_ml/xgboost/xgboost_regressor.py @@ -189,6 +189,8 @@ class XGBoostRegressorConstr(TreeLeavesAccessor, AbstractPredictorConstr): |ClassShort| """ + _left_strict = True + def __init__( self, gp_model, @@ -274,7 +276,11 @@ def _mip_model(self, **kwargs): raise ModelConfigurationError( xgb_regressor, f"model not implemented for {booster_type}" ) - trees = xgb_raw["learner"]["gradient_booster"]["model"]["trees"] + trees = [ + self._xgb_tree_to_dict(tree) + for tree in xgb_raw["learner"]["gradient_booster"]["model"]["trees"] + ] + self._trees = trees if self._no_debug: kwargs["no_record"] = True @@ -288,7 +294,7 @@ def _mip_model(self, **kwargs): # output variable only to read it back. trees_sum, output_lb, output_ub, self._tree_leaves = _build_tree_ensemble( model, - [self._xgb_tree_to_dict(tree) for tree in trees], + trees, np.ones(n_estimators), _input, 1, @@ -314,7 +320,7 @@ def _mip_model(self, **kwargs): estimators.append( AbstractTreeEstimator( self.gp_model, - self._xgb_tree_to_dict(tree), + tree, self.input, tree_vars[:, i, :], -self.epsilon, diff --git a/tests/test_lightgbm/test_project_input.py b/tests/test_lightgbm/test_project_input.py new file mode 100644 index 00000000..5957f7f9 --- /dev/null +++ b/tests/test_lightgbm/test_project_input.py @@ -0,0 +1,21 @@ +"""Tests for ``project_input`` with LightGBM.""" + +import unittest + +import lightgbm as lgb +from sklearn import datasets + +from ..tree_ensemble import ProjectInputMixin + + +class TestProjectInputLightGBM(ProjectInputMixin, unittest.TestCase): + @classmethod + def setUpClass(cls): + cls.X, y = datasets.load_diabetes(return_X_y=True) + cls.predictor = lgb.LGBMRegressor( + n_estimators=10, max_depth=3, random_state=0, verbose=-1 + ).fit(cls.X, y) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/test_sklearn/test_project_input.py b/tests/test_sklearn/test_project_input.py new file mode 100644 index 00000000..0bc023eb --- /dev/null +++ b/tests/test_sklearn/test_project_input.py @@ -0,0 +1,46 @@ +"""Tests for ``project_input`` with scikit-learn tree ensembles.""" + +import unittest + +from sklearn import datasets +from sklearn.ensemble import GradientBoostingRegressor, RandomForestRegressor +from sklearn.tree import DecisionTreeRegressor + +from ..tree_ensemble import ProjectInputMixin + + +class TestProjectInputDecisionTree(ProjectInputMixin, unittest.TestCase): + @classmethod + def setUpClass(cls): + cls.X, y = datasets.load_diabetes(return_X_y=True) + cls.predictor = DecisionTreeRegressor(max_depth=4, random_state=0).fit(cls.X, y) + + +class TestProjectInputRandomForest(ProjectInputMixin, unittest.TestCase): + @classmethod + def setUpClass(cls): + cls.X, y = datasets.load_diabetes(return_X_y=True) + cls.predictor = RandomForestRegressor( + n_estimators=10, max_depth=4, random_state=0 + ).fit(cls.X, y) + + +class TestProjectInputGradientBoosting(ProjectInputMixin, unittest.TestCase): + @classmethod + def setUpClass(cls): + cls.X, y = datasets.load_diabetes(return_X_y=True) + cls.predictor = GradientBoostingRegressor( + n_estimators=10, max_depth=3, random_state=0 + ).fit(cls.X, y) + + def test_incompatible_leaves_are_nan(self): + # Known instance: at epsilon=0 the trees of "leaf" take opposite + # branches at a shared threshold, so no input reaches the leaves. + import numpy as np + + _, projected = self.solve("leaf", 0.0) + self.assertTrue(np.isnan(projected).all()) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/test_xgboost/test_project_input.py b/tests/test_xgboost/test_project_input.py new file mode 100644 index 00000000..98011a9e --- /dev/null +++ b/tests/test_xgboost/test_project_input.py @@ -0,0 +1,21 @@ +"""Tests for ``project_input`` with XGBoost.""" + +import unittest + +import xgboost as xgb +from sklearn import datasets + +from ..tree_ensemble import ProjectInputMixin + + +class TestProjectInputXGBoost(ProjectInputMixin, unittest.TestCase): + @classmethod + def setUpClass(cls): + cls.X, y = datasets.load_diabetes(return_X_y=True) + cls.predictor = xgb.XGBRegressor( + n_estimators=10, max_depth=3, random_state=0 + ).fit(cls.X, y) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/tree_ensemble.py b/tests/tree_ensemble.py index 4e01da31..b810661a 100644 --- a/tests/tree_ensemble.py +++ b/tests/tree_ensemble.py @@ -68,3 +68,88 @@ def ties_duplicated_threshold(tree_pairs, x_star, feas_tol): if abs(x_star[feature] - threshold) <= tie_tol: return True return False + + +class ProjectInputMixin: + """Tests of ``project_input`` shared by the frameworks. + + The test class provides ``X``, ``predictor`` (a fitted regressor whose + ``predict`` takes a numpy array) and derives from ``unittest.TestCase``. + """ + + FORMULATIONS = ("leaf", "misic", "misic_lazy", "ocean", "biggs_perakis") + #: Large enough for Gurobi's tolerances and the float32 rounding of the + #: features of the diabetes data. + EPSILON = 1e-4 + + def solve(self, formulation, epsilon): + """Maximize the prediction of two inputs; return the value of the + output variables and the projected inputs.""" + import warnings + + import gurobipy as gp + + from gurobi_ml import add_predictor_constr + + with gp.Model() as model: + model.Params.OutputFlag = 0 + x = model.addMVar( + (2, self.X.shape[1]), lb=self.X.min(axis=0), ub=self.X.max(axis=0) + ) + with warnings.catch_warnings(): + warnings.simplefilter("ignore", UserWarning) + pred_constr = add_predictor_constr( + model, self.predictor, x, formulation=formulation, epsilon=epsilon + ) + model.setObjective(pred_constr.output.sum(), gp.GRB.MAXIMIZE) + model.optimize() + self.assertEqual(model.Status, gp.GRB.OPTIMAL) + return pred_constr.output.X.ravel(), pred_constr.project_input() + + def test_projection_attains_output_with_epsilon(self): + # With a sufficient epsilon, the selected leaves of every + # formulation contain an input, and the regression evaluated at the + # projection gives the values of the output variables. + for formulation in self.FORMULATIONS: + with self.subTest(formulation=formulation): + output, projected = self.solve(formulation, self.EPSILON) + self.assertFalse(np.isnan(projected).any()) + np.testing.assert_allclose( + self.predictor.predict(projected).ravel(), output, rtol=1e-6 + ) + + def test_projection_attains_output_misic_without_epsilon(self): + # The shared split variables keep the leaves compatible at epsilon=0. + for formulation in ("misic", "misic_lazy"): + with self.subTest(formulation=formulation): + output, projected = self.solve(formulation, 0.0) + self.assertFalse(np.isnan(projected).any()) + np.testing.assert_allclose( + self.predictor.predict(projected).ravel(), output, rtol=1e-6 + ) + + def test_projection_without_epsilon_attains_output_or_is_nan(self): + # At epsilon=0 the other formulations may select leaves that no + # input reaches: such rows are NaN, the others attain the output. + for formulation in ("leaf", "ocean", "biggs_perakis"): + with self.subTest(formulation=formulation): + output, projected = self.solve(formulation, 0.0) + reached = ~np.isnan(projected).any(axis=1) + if reached.any(): + np.testing.assert_allclose( + self.predictor.predict(projected[reached]).ravel(), + output[reached], + rtol=1e-6, + ) + + def test_no_solution(self): + import gurobipy as gp + + from gurobi_ml import add_predictor_constr + from gurobi_ml.exceptions import NoSolutionError + + with gp.Model() as model: + x = model.addMVar((1, self.X.shape[1]), lb=-1, ub=1) + pred_constr = add_predictor_constr(model, self.predictor, x) + with self.assertRaises(NoSolutionError): + pred_constr.project_input() From af4acfe9a934e115f282f370c72bb8fdcb924b92 Mon Sep 17 00:00:00 2001 From: hal0taso <11371960+hal0taso@users.noreply.github.com> Date: Sat, 14 Nov 2026 20:10:41 +0000 Subject: [PATCH 2/2] Use project_input() in the docs and notebooks - Describe project_input() in Split Thresholds and Exactness of the user guide, with a short example. - Replace the hand-written leaf box helpers of the three tree ensemble notebooks with project_input(). - Show the leaves selected in each tree in the Tree Ensemble Formulations notebook. Co-Authored-By: Claude Fable 5.2 --- docs/source/user/mip-models.rst | 29 ++++++- .../Drug Design with Tree Ensembles.ipynb | 63 +++------------ ...oncrete and Wine Forest Optimization.ipynb | 71 ++++------------- .../Tree Ensemble Formulations.ipynb | 78 ++++++------------- 4 files changed, 72 insertions(+), 169 deletions(-) diff --git a/docs/source/user/mip-models.rst b/docs/source/user/mip-models.rst index 8f055fa8..cdce6be1 100644 --- a/docs/source/user/mip-models.rst +++ b/docs/source/user/mip-models.rst @@ -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() +` +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 ` -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 `_ shows how to read them and check a solution. diff --git a/notebooks/tree-ensembles-merck/Drug Design with Tree Ensembles.ipynb b/notebooks/tree-ensembles-merck/Drug Design with Tree Ensembles.ipynb index c5401156..3e107b5b 100644 --- a/notebooks/tree-ensembles-merck/Drug Design with Tree Ensembles.ipynb +++ b/notebooks/tree-ensembles-merck/Drug Design with Tree Ensembles.ipynb @@ -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", @@ -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." @@ -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", diff --git a/notebooks/tree-ensembles/Concrete and Wine Forest Optimization.ipynb b/notebooks/tree-ensembles/Concrete and Wine Forest Optimization.ipynb index 0dda850e..0f1aba78 100644 --- a/notebooks/tree-ensembles/Concrete and Wine Forest Optimization.ipynb +++ b/notebooks/tree-ensembles/Concrete and Wine Forest Optimization.ipynb @@ -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", @@ -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", @@ -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." ] }, { @@ -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", diff --git a/notebooks/tree-ensembles/Tree Ensemble Formulations.ipynb b/notebooks/tree-ensembles/Tree Ensemble Formulations.ipynb index d4b2104d..dc91522c 100644 --- a/notebooks/tree-ensembles/Tree Ensemble Formulations.ipynb +++ b/notebooks/tree-ensembles/Tree Ensemble Formulations.ipynb @@ -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):" ] }, { @@ -294,23 +294,13 @@ "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" ] }, { @@ -318,15 +308,18 @@ "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." ] }, { @@ -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",