Skip to content

Deep Classification Trees (Experimental)

classifier

Deep-forest classification estimator built on Keras.

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

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

DFClassifier

Bases: BaseDeep, ClassifierMixin

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

Parameters:

Name Type Description Default
metric AcceptableMetric

Name of the built-in metric/loss key. Currently only "cross_entropy" is supported.

'cross_entropy'
n_estimators int

Number of trees/estimators to build.

100
internal_size int

Internal representation size used by the differentiable tree layers.

12
max_depth int

Maximum depth of each differentiable tree.

6
feature_fraction float

Fraction of features sampled per estimator.

1.0
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/classifier.py
 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
293
294
295
296
297
298
299
300
301
302
303
304
305
class DFClassifier(BaseDeep, ClassifierMixin):
    """A deep-forest classifier with an sklearn-compatible API.

    Parameters:
        metric:
            Name of the built-in metric/loss key. Currently only
            ``"cross_entropy"`` is supported.
        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)``.
    """

    label_encoder_: LabelEncoder
    classes_: NDArray[np.object_] | NDArray[np.int_] | NDArray[np.str_]

    @validate_call(config={"arbitrary_types_allowed": True})
    def __init__(
        self,
        metric: AcceptableMetric = "cross_entropy",
        n_estimators: int = 100,
        internal_size: int = 12,
        max_depth: int = 6,
        feature_fraction: float = 1.0,
        *,
        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:
        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) -> "DFClassifier":
        """Fit the classifier.

        Args:
            X: Feature matrix.
            y: Class labels (binary or multiclass).
            fit_params: Extra keyword arguments forwarded to ``Model.fit``.

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

        y_checked = self._validate_y(y)

        # Encode classes to integer indices, then to one-hot.
        self.label_encoder_ = LabelEncoder()
        y_index = self.label_encoder_.fit_transform(np.array(y_checked).reshape(-1))
        self.classes_ = tp.cast(NDArray, self.label_encoder_.classes_)

        n_classes = int(len(self.classes_))
        y_onehot = np.eye(n_classes, dtype=np.float64)[y_index]

        inputs, outputs = DeepForestBuilder(
            self.n_estimators,
            self.max_depth,
            self.feature_fraction,
            "classification",
            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(
            np.array(X).shape[1],
            self.internal_size,
            n_classes,
        )

        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_onehot, **fit_params)
        return self

    def predict_proba(self, X: Inputs) -> Predictions:
        """Predict class probabilities.

        Returns:
            Array of shape ``(n_samples, n_classes)``.
        """
        check_is_fitted(self, "model_")
        proba = self.model_.predict(self._validate_X(X))
        return np.asarray(proba, dtype=np.float64).reshape(np.array(X).shape[0], -1)

    def predict(self, X: Inputs) -> Predictions:
        """Predict classes."""
        proba = self.predict_proba(X)
        idx = np.argmax(proba, axis=1)
        return tp.cast(Predictions, self.label_encoder_.inverse_transform(idx))

    def score(
        self,
        X: Inputs,
        y: GroundTruth,
        sample_weight: NDArray[np.float64] | None = None,
    ) -> float:
        """Return the negative loss on ``(X, y)`` (higher is better)."""
        y_checked = self._validate_y(y)
        y_idx = self.label_encoder_.transform(np.array(y_checked).reshape(-1))
        y_true = np.eye(len(self.classes_), dtype=np.float64)[y_idx]
        y_pred = np.asarray(self.predict_proba(X), dtype=np.float64)

        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 classification targets.

        Supports binary and multiclass 1D targets; rejects multilabel indicators.
        """
        y_arr = _check_y(np.array(y), multi_output=False, y_numeric=False)
        t = type_of_target(y_arr)
        if t not in {"binary", "multiclass"}:
            raise ValueError(
                "Only binary and multiclass 1D targets are supported for DFClassifier. "
                f"Got target type: {t}."
            )
        return y_arr

fit

fit(X, y, **fit_params)

Fit the classifier.

Parameters:

Name Type Description Default
X Inputs

Feature matrix.

required
y GroundTruth

Class labels (binary or multiclass).

required
fit_params

Extra keyword arguments forwarded to Model.fit.

{}

Returns:

Type Description
'DFClassifier'

self.

Source code in src/tree_machine/deep_trees/classifier.py
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
def fit(self, X: Inputs, y: GroundTruth, **fit_params) -> "DFClassifier":
    """Fit the classifier.

    Args:
        X: Feature matrix.
        y: Class labels (binary or multiclass).
        fit_params: Extra keyword arguments forwarded to ``Model.fit``.

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

    y_checked = self._validate_y(y)

    # Encode classes to integer indices, then to one-hot.
    self.label_encoder_ = LabelEncoder()
    y_index = self.label_encoder_.fit_transform(np.array(y_checked).reshape(-1))
    self.classes_ = tp.cast(NDArray, self.label_encoder_.classes_)

    n_classes = int(len(self.classes_))
    y_onehot = np.eye(n_classes, dtype=np.float64)[y_index]

    inputs, outputs = DeepForestBuilder(
        self.n_estimators,
        self.max_depth,
        self.feature_fraction,
        "classification",
        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(
        np.array(X).shape[1],
        self.internal_size,
        n_classes,
    )

    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_onehot, **fit_params)
    return self

predict

predict(X)

Predict classes.

Source code in src/tree_machine/deep_trees/classifier.py
256
257
258
259
260
def predict(self, X: Inputs) -> Predictions:
    """Predict classes."""
    proba = self.predict_proba(X)
    idx = np.argmax(proba, axis=1)
    return tp.cast(Predictions, self.label_encoder_.inverse_transform(idx))

predict_proba

predict_proba(X)

Predict class probabilities.

Returns:

Type Description
Predictions

Array of shape (n_samples, n_classes).

Source code in src/tree_machine/deep_trees/classifier.py
246
247
248
249
250
251
252
253
254
def predict_proba(self, X: Inputs) -> Predictions:
    """Predict class probabilities.

    Returns:
        Array of shape ``(n_samples, n_classes)``.
    """
    check_is_fitted(self, "model_")
    proba = self.model_.predict(self._validate_X(X))
    return np.asarray(proba, dtype=np.float64).reshape(np.array(X).shape[0], -1)

score

score(X, y, sample_weight=None)

Return the negative loss on (X, y) (higher is better).

Source code in src/tree_machine/deep_trees/classifier.py
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
def score(
    self,
    X: Inputs,
    y: GroundTruth,
    sample_weight: NDArray[np.float64] | None = None,
) -> float:
    """Return the negative loss on ``(X, y)`` (higher is better)."""
    y_checked = self._validate_y(y)
    y_idx = self.label_encoder_.transform(np.array(y_checked).reshape(-1))
    y_true = np.eye(len(self.classes_), dtype=np.float64)[y_idx]
    y_pred = np.asarray(self.predict_proba(X), dtype=np.float64)

    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()