Skip to content

FEA: Support for interaction_cst in trees and downstream ensemble models - #33278

Open
cakedev0 wants to merge 36 commits into
scikit-learn:mainfrom
cakedev0:tree/interactions-cst
Open

cakedev0 wants to merge 36 commits into
scikit-learn:mainfrom
cakedev0:tree/interactions-cst

Conversation

@cakedev0

@cakedev0 cakedev0 commented Feb 13, 2026 •

Copy link
Copy Markdown
Member

Add support for interaction_cst in decision trees and downstream ensemble models.

Reference Issues/PRs

I did not find issues explicitly asking for this, but I was asked for it in a freelance project (and we agreed on making it open-source).

This helps with issue #27873 because HGB already supports interaction_cst, so this PR brings GB one step closer to HGB.

What does this implement/fix? Explain your changes.

API changes:

Adds a new interaction_cst parameter to:

  • <Decision/Extra>Tree<Classifier/Regressor>
  • <RandomForest/ExtraTrees/GradientBoosting><Classifier/Regressor>

The interaction_cst parameter supports the same options as in HGB:

  • explicit groups (list/tuple/set of feature indices),
  • "pairwise" shorthand,
  • "no_interactions" shorthand.

It's validated and normalized in BaseDecisionTree.

Logic of the implementation:

  • Constraints are converted to sparse group<->feature mappings
  • Allowed features are maintained as a prefix of splitter.features, forbidden features are moved to the suffix and excluded from future draws.
  • Handles both builder strategies:
    • depth-first: propagates constraint state incrementally via stack records (very efficient)
    • best-first: reconstructs node state from ancestor splits using stored parent ids (a bit less efficient, but still has a very small impact even on worst case scenarios)

Implementation details

The interaction-constraint logic is encapsulated in a dedicated Cython class:
InteractionConstraints (in sklearn/tree/_tree.pyx).

It builds and stores group <-> feature mappings in both directions so updates after each split are efficient.

At fit time it also allocates:

  • an array for active interaction groups (stored as a prefix to represent the current state),
  • reusable working buffers: marking arrays and tokens for efficient set-like operations on groups/features.

The core method is update_after_split(..., split_feature). It updates the active groups and moves newly forbidden features to the tail of splitter.features.
It then persists state by writing n_active_interaction_groups and n_allowed_features to the parent record.

Integration points in existing code paths are intentionally small:

  • Splitters (_splitter.pyx): feature sampling is restricted to
    features[:n_allowed_features].
  • Depth-first builder: updates constraints incrementally after each non-leaf split,
    and children inherit the updated state.
  • Best-first builder: because nodes are expanded out of DFS order, it reconstructs
    node state by replaying ancestor split features through stored parent links.

Test coverage added/updated:

For trees:

  • constraint parsing/validation and error cases,
  • structural enforcement across classifier/regressor, best/random splitters, dense/sparse inputs,
  • overlapping groups and array-like input,
  • a numerical check that "no_interactions" removes mixed second-order effects.

+ Ensemble smoke tests for Random Forest / Extra Trees / Gradient Boosting to verify parameter plumbing.

AI usage disclosure

I used AI assistance for:

  • Code generation: almost 100% AI written but I iterated a lot (see the commit history ^^), and I think the resulting code is at least as good as what I would have written myself.
  • Test/benchmark generation: same
  • Docstrings

The human part is: research, understanding, designing.

Benchmarks

Except for pathological cases I don't expect to see in the real world, providing interactions constraints has no negative impact on fit time. In most cases, it will reduce fit time because it reduces the number candidate splits.

I can provide detailed benchmark results using the script below if needed (including some pathological/near-pathological cases):

Details
from time import perf_counter
import numpy as np

from sklearn.tree import DecisionTreeRegressor


n_samples = int(3e5)
n_features = 300

rng = np.random.RandomState(0)
X = rng.normal(size=(n_samples, n_features)).astype(np.float32).round(1)
y = rng.normal(size=n_samples)

cases = {
    "none": None,
    "no_interactions": "no_interactions",
    "disjoint_10": np.arange(n_features).reshape(-1, 10),
    "pairwise": "pairwise",
    "many_overlap_10": [range(i, i + 10) for i in range(n_features - 10)]
}


def time_fit(X, y, n_repeats: int = 7, **kwargs):
    """Measure fit times across repeats and return times + leaf counts."""
    times = []
    leave_counts = []
    for repeat in range(n_repeats):
        est = DecisionTreeRegressor(
            random_state=repeat,
            **kwargs
        )
        start = perf_counter()
        est.fit(X, y)
        times.append(perf_counter() - start)
        leave_counts.append((est.tree_.node_count + 1) // 2)
    return times, leave_counts

rows = []

for max_leaf_nodes in [None, n_samples]:
    builder_name = "Depth-first" if max_leaf_nodes is None else "Best-first"
    print(builder_name)
    for case_name, interaction_cst in cases.items():
        times, leave_counts = time_fit(
            X, y, interaction_cst=interaction_cst,
            max_features=1,
            max_leaf_nodes=max_leaf_nodes,
        )
        mean_s = np.mean(times)
        mean_leaves = round(np.mean(leave_counts))
        print(
            f"{case_name:<16} {mean_s:>7.3f}  {mean_leaves:>10.1f}"
        )
        rows.append({
            'builder': builder_name,
            'case': case_name,
            'avg time': mean_s,
            'n_leaves': mean_leaves,
        })

        

@cakedev0 cakedev0 changed the title FEA: Support for `interaction FEA: Support for interaction_cst in trees and downstream ensemble models Feb 13, 2026
@cakedev0
cakedev0 marked this pull request as ready for review February 13, 2026 17:53
@ogrisel ogrisel moved this to Blocked in Labs May 25, 2026
@ogrisel ogrisel added this to Labs May 25, 2026
@jeremiedbb jeremiedbb moved this to PR waiting for reviews in Labs Jun 29, 2026

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant