Get e2tree on CRAN or GitHub.
Dependencies installed automatically: Rcpp, dplyr. Recommended: randomForest or ranger, rpart.plot, partykit.
No install? Try it in your browser.
e2tree ships as a WebAssembly build for webR — R running entirely in your browser, nothing to install. Open the REPL and paste:
Note: the webR build can lag behind the CRAN release by a version.
Classification in 5 steps.
Derives the co-occurrence dissimilarity matrix from any supported tree ensemble. Performance-critical computation runs in C++ via Rcpp with OpenMP; supports parallel execution and chunked computation for large samples.
| Argument | Type | Description |
|---|---|---|
| ensemble | ensemble | A fitted tree ensemble: randomForest, ranger, xgb.Booster, lgb.Booster, gbm, or catboost.Model. |
| data | data.frame | The training dataset used to fit the ensemble. |
| label | character | Name of the response variable column. |
| parallel | list | active: logical; enable parallel computation. no_cores: number of cores. |
| chunk_size | integer | When smaller than the sample size, computes D in chunks to bound memory. use_disk = TRUE persists the result. |
Returns: A symmetric numeric matrix of dimensions n × n with values in [0, 1] and zero diagonal, carrying an ensemble_backend attribute. Reusing a stale D with a different model raises a warning rather than producing a silent bug.
Interpretation note (bagging vs boosting). The dissimilarity scale differs systematically between backend families. Compare fidelity values within a backend, not across them.
Grows a single decision tree guided by the ensemble's dissimilarity structure. Returns an object of class e2tree.
| Argument | Type | Description |
|---|---|---|
| formula | formula | Standard R formula specifying the response and predictors, e.g. Species ~ . |
| data | data.frame | Training dataset. Must match the data used to compute D. |
| D | matrix | Dissimilarity matrix produced by createDisMatrix(). |
| ensemble | rf / ranger | The original ensemble model. Used to extract terminal node assignments. |
| setting | list | Stopping rules: impTotal (min impurity), maxDec (min decrease), n (min observations), level (max depth). |
Predicts responses for new observations by routing them through the e2tree's split rules.
| Argument | Type | Description |
|---|---|---|
| object | e2tree | A fitted e2tree model. |
| newdata | data.frame | New data to predict. Must contain the same predictor columns. |
Also available: fitted(object) returns training predictions, residuals(object) returns training residuals.
Assesses reconstruction quality by comparing the ensemble proximity matrix with the one induced by the e2tree, using the nLoI plus four complementary divergence and similarity measures, each with a permutation test.
| Argument | Type | Description |
|---|---|---|
| data | data.frame | The data frame containing the variables in the model. |
| fit | e2tree | A fitted e2tree object. |
| D | matrix | Dissimilarity matrix from createDisMatrix(). |
| test | character | "measures" runs the divergence measures with permutation tests (agreement); "mantel" runs the Mantel test only (association); "both" is the default. |
| n_perm | integer | Permutations for the measure tests. 0 skips permutation testing. |
Returns: An eValidation object holding both proximity matrices, the loi object with its decomposition, and a data frame of all measures (nLoI, Hellinger, wRMSE, RV, SSIM). Use measures(), proximity(), and plot().
Computes global variable importance from the e2tree's split structure, weighted by the impurity decrease at each split. Classification or regression is auto-detected from the fitted object.
Returns: A list with the importance table (Variable, MeanImpurityDecrease) and $g_imp, a ggplot2 importance plot.
Loss of Interpretability. A scale-sensitive divergence measuring how faithfully the e2tree reconstructs the ensemble's co-occurrence structure — agreement, not association. Normalized by the pair count it yields the nLoI, bounded in [0, 1], zero if and only if the reconstruction is exact.
| Argument | Type | Description |
|---|---|---|
| O | matrix | Ensemble proximity matrix (n × n), values in [0, 1]. Typically proximity(eValidation(...))$ensemble. |
| O_hat | matrix | e2tree-induced proximity matrix (n × n). Crisp and block-diagonal: zero for every separated pair. |
| normalize | logical | TRUE (default) returns the nLoI, divided by M = n(n−1)/2; FALSE returns the raw LoI. |
Returns: An object of class loi carrying the exact decomposition — loi_in / loi_out and their per-pair averages mean_in / mean_out, which are directly comparable. A high mean_out (> 0.3) means the partition is too coarse; a high mean_in (> 0.1) means poor within-node calibration.
Disaggregates the global nLoI into a per-node and per-observation component, so you can see where the reconstruction is reliable. A high per-observation value flags a case whose local explanation is less trustworthy.
Returns: An object of class localLoI with an obs and a node data frame. The per-observation values average back exactly to the global statistic: mean(obs$loi) == nLoI. Passing fit only relabels the detected blocks with the real terminal-node ids.
Per-instance explanations, verified against the ensemble.
e2tree is interpretive, not predictive: it reconstructs the grouping geometry a trained ensemble induces, and its quality is fidelity to that ensemble. This layer brings the same lens down to the individual observation. All functions are backend-agnostic.
A single per-instance entry point composing the whole local layer — routing, additive attribution, ensemble neighbours, region fidelity, outcome dispersion, and on request the counterfactual and stability — into one narrative object with print() and plot() methods.
| Function | What it answers |
|---|---|
| eContribution() | Per-instance Saabas-style attribution of the reconstructed value. Exactly additive, per class for classification. A decomposition of the reconstruction, not of a prediction. |
| eNeighbors() | Case-based explanation: the nearest training cases by the ensemble's own leaf co-occurrence proximity, plus leaf prototypes. Not a generic feature-space distance. |
| eCounterfactual() | The smallest feature change moving an instance into a different region — validated against the ensemble's grouping geometry. validated is TRUE only when the forest actually regroups the counterfactual, unlike surrogate-only methods that merely flip the approximating tree. |
| eStability() | Confidence and stability of a local explanation via bootstrap over the ensemble's trees. Yields a per-instance confidence, a neighbour-stability score, and an interval on the reconstructed outcome. |
| eHeterogeneity() | Descriptive per-region outcome dispersion: entropy and prediction set for classification, central band and sd for regression. |
| nodeStats() | Full profile of any node: metadata, decision rule, per-predictor node-vs-rest statistics (Cohen's d, Cramér's V) and the response distribution. |
| plotNodeComparison() | Side-by-side comparison of two nodes on the predictors that separate them most. |
Longitudinal explanations, decomposed.
On panel (unit × time) data with high intraclass correlation, a single pooled e2tree conflates two sources of variation and the within-unit signal is crowded out. panel_e2tree() decomposes the feature representation à la Mundlak (1978) into a between component (unit means, one row per unit) and a within component (unit-demeaned deviations), then grows a separate e2tree surrogate for each. The reconstruction is additive.
Returns: An e2panel object with print(), summary() (fidelity plus decomposed between/within importance), plot() and predict(). Ships with the panel_health dataset — a simulated country × year panel with known between and within drivers. Regression outcomes with numeric predictors.
Standard interface for e2tree objects.
| Class | Methods |
|---|---|
| e2tree | print, summary, plot, predict, fitted, residuals, as.rpart, as.party, nodes, e2splits |
| eValidation | print, summary, plot, measures, proximity |
| loi | print, summary, plot |
| loi_perm | print, summary, plot |
| localLoI | print, summary, plot |
| e2explanation | print, plot |
| e2contribution | print, plot |
| e2neighbors | print, plot |
| e2counterfactual | print, plot |
| e2stability | print, plot |
| e2heterogeneity | print, plot |
| e2nodeStats | print, plot |
| e2panel | print, summary, plot, predict |
Convert to rpart and partykit.
e2tree objects can be converted to two widely-used R tree formats, unlocking the full ecosystem of tree visualization and inspection tools.