Skip to content

Deep Regression Trees (Experimental)

regression

Deep-forest regression estimator built on Keras.

This module provides :class:~tree_machine.deep_trees.regression.DFRegression, an sklearn-compatible regressor that builds a differentiable forest model using Keras.

The estimator follows the familiar fit/predict/score API and supports both built-in and user-provided Keras losses/metrics.

DFRegression

Bases: BaseDeep, RegressorMixin

A deep-forest regressor with an sklearn-compatible API.

Parameters:

Name Type Description Default
metric AcceptableMetric

Name of the built-in metric/loss key. Must be one of "mae", "mse", or "mape".

required
n_estimators int

Number of trees/estimators to build.

required
internal_size int

Internal representation size used by the differentiable tree layers.

required
max_depth int

Maximum depth of each differentiable tree.

required
feature_fraction float

Fraction of features sampled per estimator.

required
loss LossLike | None

Optional custom Keras loss (callable/instance/class). If omitted (and metrics is also omitted), the built-in loss derived from metric is used.

None
metrics Sequence[MetricLike] | None

Optional sequence of custom Keras metrics (callables/instances/classes).

None
compile_kwargs dict[str, Any] | None

Extra keyword arguments forwarded to Model.compile. If compile_kwargs does not define an optimizer, "adam" is used.

None
decision_l1/decision_l2

L1/L2 regularization strength applied to routing Dense weights.

required
leaf_l1/leaf_l2

L1/L2 regularization strength applied to leaf values.

required
feature_dropout float

Dropout rate applied to inputs during training.

0.0
routing_dropout float

Dropout rate applied to routing probabilities during training.

0.0
Notes
  • Each call to :meth:fit builds and compiles a new Keras model.
  • :meth:score returns the negative loss value on (X, y).
Source code in src/tree_machine/deep_trees/regression.py
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
class DFRegression(BaseDeep, RegressorMixin):
    """A deep-forest regressor with an sklearn-compatible API.

    Parameters:
        metric:
            Name of the built-in metric/loss key. Must be one of ``"mae"``, ``"mse"``,
            or ``"mape"``.
        n_estimators:
            Number of trees/estimators to build.
        internal_size:
            Internal representation size used by the differentiable tree layers.
        max_depth:
            Maximum depth of each differentiable tree.
        feature_fraction:
            Fraction of features sampled per estimator.
        loss:
            Optional custom Keras loss (callable/instance/class). If omitted (and
            ``metrics`` is also omitted), the built-in loss derived from ``metric``
            is used.
        metrics:
            Optional sequence of custom Keras metrics (callables/instances/classes).
        compile_kwargs:
            Extra keyword arguments forwarded to ``Model.compile``. If
            ``compile_kwargs`` does not define an optimizer, ``"adam"`` is used.
        decision_l1/decision_l2:
            L1/L2 regularization strength applied to routing Dense weights.
        leaf_l1/leaf_l2:
            L1/L2 regularization strength applied to leaf values.
        feature_dropout:
            Dropout rate applied to inputs during training.
        routing_dropout:
            Dropout rate applied to routing probabilities during training.

    Notes:
        * Each call to :meth:`fit` builds and compiles a new Keras model.
        * :meth:`score` returns the negative loss value on ``(X, y)``.
    """

    @validate_call(config={"arbitrary_types_allowed": True})
    def __init__(
        self,
        metric: AcceptableMetric,
        n_estimators: int,
        internal_size: int,
        max_depth: int,
        feature_fraction: float,
        *,
        loss: LossLike | None = None,
        metrics: tp.Sequence[MetricLike] | None = None,
        compile_kwargs: dict[str, tp.Any] | None = None,
        decision_l1: float = 0.0,
        decision_l2: float = 0.0,
        leaf_l1: float = 0.0,
        leaf_l2: float = 0.0,
        feature_dropout: float = 0.0,
        routing_dropout: float = 0.0,
    ) -> None:
        """Create a :class:`DFRegression` instance."""
        super().__init__(
            n_estimators,
            internal_size,
            max_depth,
            feature_fraction,
        )

        self.metric = metric
        self.loss = loss
        self.metrics = list(metrics) if metrics is not None else None
        self.compile_kwargs = (
            dict(compile_kwargs) if compile_kwargs is not None else None
        )

        self.decision_l1 = float(decision_l1)
        self.decision_l2 = float(decision_l2)
        self.leaf_l1 = float(leaf_l1)
        self.leaf_l2 = float(leaf_l2)
        self.feature_dropout = float(feature_dropout)
        self.routing_dropout = float(routing_dropout)

        self._resolved_loss_: tp.Any | None = None
        self._resolved_metrics_: list[tp.Any] | None = None

    def fit(self, X: Inputs, y: GroundTruth, **fit_params) -> "DFRegression":
        """Fit the regressor.

        The model is built through :class:`~tree_machine.deep_trees.layers.DeepForestBuilder`
        and compiled with the resolved loss/metrics.

        Args:
            X: Feature matrix.
            y: Numeric regression targets.
            fit_params: Extra keyword arguments forwarded to ``Model.fit``.

        Returns:
            ``self``.
        """
        self.feature_names_ = list(X.columns) if isinstance(X, pd.DataFrame) else []

        y_ = self._validate_y(y).reshape(X.shape[0], -1)

        inputs, outputs = DeepForestBuilder(
            self.n_estimators,
            self.max_depth,
            self.feature_fraction,
            "regression",
            decision_l1=self.decision_l1,
            decision_l2=self.decision_l2,
            leaf_l1=self.leaf_l1,
            leaf_l2=self.leaf_l2,
            feature_dropout=self.feature_dropout,
            routing_dropout=self.routing_dropout,
        ).get_tree(
            X.shape[1],
            self.internal_size,
            y_.shape[1],
        )

        self.model_ = Model(inputs=inputs, outputs=outputs)

        loss_obj, metrics_list = _resolve_loss_and_metrics(
            metric_key=self.metric,
            loss=self.loss,
            metrics=self.metrics,
        )
        self._resolved_loss_ = loss_obj
        self._resolved_metrics_ = metrics_list

        compile_kwargs = (
            dict(self.compile_kwargs) if self.compile_kwargs is not None else {}
        )
        optimizer = compile_kwargs.pop("optimizer", "adam")
        self.model_.compile(
            loss=loss_obj,
            optimizer=optimizer,
            metrics=metrics_list,
            **compile_kwargs,
        )
        self.model_.fit(self._validate_X(X), y_, **fit_params)
        return self

    def predict(self, X: Inputs) -> Predictions:
        """Predict regression targets.

        Args:
            X: Feature matrix.

        Returns:
            A 1D array of predictions with shape ``(n_samples,)``.
        """
        check_is_fitted(self, "model_")

        return self.model_.predict(
            self._validate_X(X),
        ).reshape(-1)

    def score(
        self,
        X: Inputs,
        y: GroundTruth,
        sample_weight: NDArray[np.float64] | None = None,
    ) -> float:
        """Return the negative loss on ``(X, y)``.

        This matches sklearn's convention that higher scores are better.

        Args:
            X: Feature matrix.
            y: Ground-truth regression targets.
            sample_weight: Optional per-sample weights.

        Returns:
            The negative loss value as a Python ``float``.
        """
        y_true = self._validate_y(y).reshape(np.array(X).shape[0], -1)
        y_pred = np.array(self.predict(X)).reshape(y_true.shape)

        if getattr(self, "_resolved_loss_", None) is None:
            loss_obj, _ = _resolve_loss_and_metrics(
                metric_key=self.metric,
                loss=self.loss,
                metrics=self.metrics,
            )
        else:
            loss_obj = tp.cast(tp.Any, self._resolved_loss_)

        if sample_weight is None:
            loss_value = loss_obj(y_true, y_pred)
        else:
            try:
                loss_value = loss_obj(y_true, y_pred, sample_weight=sample_weight)
            except TypeError:
                loss_value = loss_obj(y_true, y_pred)

        return -loss_value.numpy()

    def _validate_y(self, y: GroundTruth) -> GroundTruth:
        """Validate regression targets.

        Targets must be numeric and one-dimensional; multi-output targets are rejected.
        """
        return _check_y(np.array(y), multi_output=False, y_numeric=True)

__init__

__init__(metric, n_estimators, internal_size, max_depth, feature_fraction, *, loss=None, metrics=None, compile_kwargs=None, decision_l1=0.0, decision_l2=0.0, leaf_l1=0.0, leaf_l2=0.0, feature_dropout=0.0, routing_dropout=0.0)

Create a :class:DFRegression instance.

Source code in src/tree_machine/deep_trees/regression.py
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
@validate_call(config={"arbitrary_types_allowed": True})
def __init__(
    self,
    metric: AcceptableMetric,
    n_estimators: int,
    internal_size: int,
    max_depth: int,
    feature_fraction: float,
    *,
    loss: LossLike | None = None,
    metrics: tp.Sequence[MetricLike] | None = None,
    compile_kwargs: dict[str, tp.Any] | None = None,
    decision_l1: float = 0.0,
    decision_l2: float = 0.0,
    leaf_l1: float = 0.0,
    leaf_l2: float = 0.0,
    feature_dropout: float = 0.0,
    routing_dropout: float = 0.0,
) -> None:
    """Create a :class:`DFRegression` instance."""
    super().__init__(
        n_estimators,
        internal_size,
        max_depth,
        feature_fraction,
    )

    self.metric = metric
    self.loss = loss
    self.metrics = list(metrics) if metrics is not None else None
    self.compile_kwargs = (
        dict(compile_kwargs) if compile_kwargs is not None else None
    )

    self.decision_l1 = float(decision_l1)
    self.decision_l2 = float(decision_l2)
    self.leaf_l1 = float(leaf_l1)
    self.leaf_l2 = float(leaf_l2)
    self.feature_dropout = float(feature_dropout)
    self.routing_dropout = float(routing_dropout)

    self._resolved_loss_: tp.Any | None = None
    self._resolved_metrics_: list[tp.Any] | None = None

fit

fit(X, y, **fit_params)

Fit the regressor.

The model is built through :class:~tree_machine.deep_trees.layers.DeepForestBuilder and compiled with the resolved loss/metrics.

Parameters:

Name Type Description Default
X Inputs

Feature matrix.

required
y GroundTruth

Numeric regression targets.

required
fit_params

Extra keyword arguments forwarded to Model.fit.

{}

Returns:

Type Description
DFRegression

self.

Source code in src/tree_machine/deep_trees/regression.py
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
def fit(self, X: Inputs, y: GroundTruth, **fit_params) -> "DFRegression":
    """Fit the regressor.

    The model is built through :class:`~tree_machine.deep_trees.layers.DeepForestBuilder`
    and compiled with the resolved loss/metrics.

    Args:
        X: Feature matrix.
        y: Numeric regression targets.
        fit_params: Extra keyword arguments forwarded to ``Model.fit``.

    Returns:
        ``self``.
    """
    self.feature_names_ = list(X.columns) if isinstance(X, pd.DataFrame) else []

    y_ = self._validate_y(y).reshape(X.shape[0], -1)

    inputs, outputs = DeepForestBuilder(
        self.n_estimators,
        self.max_depth,
        self.feature_fraction,
        "regression",
        decision_l1=self.decision_l1,
        decision_l2=self.decision_l2,
        leaf_l1=self.leaf_l1,
        leaf_l2=self.leaf_l2,
        feature_dropout=self.feature_dropout,
        routing_dropout=self.routing_dropout,
    ).get_tree(
        X.shape[1],
        self.internal_size,
        y_.shape[1],
    )

    self.model_ = Model(inputs=inputs, outputs=outputs)

    loss_obj, metrics_list = _resolve_loss_and_metrics(
        metric_key=self.metric,
        loss=self.loss,
        metrics=self.metrics,
    )
    self._resolved_loss_ = loss_obj
    self._resolved_metrics_ = metrics_list

    compile_kwargs = (
        dict(self.compile_kwargs) if self.compile_kwargs is not None else {}
    )
    optimizer = compile_kwargs.pop("optimizer", "adam")
    self.model_.compile(
        loss=loss_obj,
        optimizer=optimizer,
        metrics=metrics_list,
        **compile_kwargs,
    )
    self.model_.fit(self._validate_X(X), y_, **fit_params)
    return self

predict

predict(X)

Predict regression targets.

Parameters:

Name Type Description Default
X Inputs

Feature matrix.

required

Returns:

Type Description
Predictions

A 1D array of predictions with shape (n_samples,).

Source code in src/tree_machine/deep_trees/regression.py
232
233
234
235
236
237
238
239
240
241
242
243
244
245
def predict(self, X: Inputs) -> Predictions:
    """Predict regression targets.

    Args:
        X: Feature matrix.

    Returns:
        A 1D array of predictions with shape ``(n_samples,)``.
    """
    check_is_fitted(self, "model_")

    return self.model_.predict(
        self._validate_X(X),
    ).reshape(-1)

score

score(X, y, sample_weight=None)

Return the negative loss on (X, y).

This matches sklearn's convention that higher scores are better.

Parameters:

Name Type Description Default
X Inputs

Feature matrix.

required
y GroundTruth

Ground-truth regression targets.

required
sample_weight NDArray[float64] | None

Optional per-sample weights.

None

Returns:

Type Description
float

The negative loss value as a Python float.

Source code in src/tree_machine/deep_trees/regression.py
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
def score(
    self,
    X: Inputs,
    y: GroundTruth,
    sample_weight: NDArray[np.float64] | None = None,
) -> float:
    """Return the negative loss on ``(X, y)``.

    This matches sklearn's convention that higher scores are better.

    Args:
        X: Feature matrix.
        y: Ground-truth regression targets.
        sample_weight: Optional per-sample weights.

    Returns:
        The negative loss value as a Python ``float``.
    """
    y_true = self._validate_y(y).reshape(np.array(X).shape[0], -1)
    y_pred = np.array(self.predict(X)).reshape(y_true.shape)

    if getattr(self, "_resolved_loss_", None) is None:
        loss_obj, _ = _resolve_loss_and_metrics(
            metric_key=self.metric,
            loss=self.loss,
            metrics=self.metrics,
        )
    else:
        loss_obj = tp.cast(tp.Any, self._resolved_loss_)

    if sample_weight is None:
        loss_value = loss_obj(y_true, y_pred)
    else:
        try:
            loss_value = loss_obj(y_true, y_pred, sample_weight=sample_weight)
        except TypeError:
            loss_value = loss_obj(y_true, y_pred)

    return -loss_value.numpy()