Model library Decision Trees
Statistical model reference

Decision Trees

Review when to use this method, its data requirements, implementation patterns, and interpretation guidance.

Description

A supervised learning algorithm that creates a flowchart-like tree structure based on feature importance to make decisions and predictions. It recursively splits data into subsets based on the most discriminative features, making it valuable for classification, regression, feature selection, and creating transparent models with clear decision rules that are easily interpretable.

Use Cases
  • classification
  • regression
  • feature importance
  • rule-based decision making
  • exploratory data analysis
Requirements
  • Sample Size: small, medium, large
  • Missing Data: none, random
  • Data Distribution: any
  • Relationship Type: non-linear, hierarchical, interactive
Variable Types
Dependent Variables
  • continuous
  • categorical
  • binary
Independent Variables
  • continuous
  • categorical
  • binary
Implementation
from sklearn.tree import DecisionTreeClassifier, DecisionTreeRegressor, export_text, plot_tree
import matplotlib.pyplot as plt

# Classification Tree
clf = DecisionTreeClassifier(max_depth=3, min_samples_leaf=5)
clf.fit(X_train, y_train)

# Regression Tree
reg = DecisionTreeRegressor(max_depth=3, min_samples_leaf=5)
reg.fit(X_train, y_train)

# Visualize trees
plt.figure(figsize=(12,8))
plot_tree(clf, feature_names=feature_names, class_names=class_names, filled=True)
plt.show()

# Print decision rules
print(export_text(clf, feature_names=feature_names))
Documentation
library(rpart)
library(rpart.plot)

# Classification Tree
clf <- rpart(y ~ ., data=train_data, method="class", 
             control=rpart.control(minsplit=10, cp=0.01))

# Regression Tree
reg <- rpart(y ~ ., data=train_data, method="anova", 
             control=rpart.control(minsplit=10, cp=0.01))

# Visualize trees
prp(clf, extra=1, faclen=0)
rpart.plot(reg)

# Print complexity parameter table
printcp(clf)
Documentation
TREE y [LEVEL=SCALE] BY x1 x2 x3
  /TREE DISPLAY=TOPDOWN NODES=STATISTICS
  /DEPCATEGORIES USEVALUES=[1,0]
  /METHOD TYPE=CHAID
  /GROWTHLIMIT MAXDEPTH=3 MINPARENTSIZE=50
  /VALIDATION TYPE=NONE
  /PRINT MODELSUMMARY CLASSIFICATION RISK.

* Alternative for regression:
TREE y [LEVEL=CONTINUOUS] BY x1 x2 x3
  /METHOD TYPE=CRT
  /PRINT MODELSUMMARY.
Documentation
/* Classification Tree */
PROC HPSPLIT DATA=train_data;
  CLASS y x3;  /* Categorical variables */
  MODEL y = x1 x2 x3;
  PRUNE costcomplexity;
  OUTPUT OUT=tree_out PREDICTED=pred;
  CODE FILE='tree_score.sas';
RUN;

/* Regression Tree */
PROC HPSPLIT DATA=train_data;
  MODEL y = x1 x2 x3 / PRUNE=COSTCOMPLEXITY;
  OUTPUT OUT=tree_out PREDICTED=pred;
RUN;
Documentation
/* Classification Tree */
tree y x1 x2 x3, type(class) maxdepth(3) minleaf(5)
tree plot, show(rules)

/* Regression Tree */
tree y x1 x2 x3, type(reg) maxdepth(3) minleaf(5)
tree plot
Documentation
Synthetic Data Example

Comprehensive synthetic datasets for both classification and regression decision tree examples with multiple feature types and non-linear relationships

R Code for Data Generation and Analysis
# Generate synthetic data with complex relationships
set.seed(123)
library(dplyr)

n <- 1000

# Continuous features
x1 <- runif(n, -5, 5)
x2 <- rnorm(n, mean=0, sd=3)

# Categorical feature
x3 <- factor(sample(c("A","B","C"), n, replace=TRUE, prob=c(0.3,0.5,0.2)))

# Binary feature
x4 <- rbinom(n, 1, plogis(0.5*x1))

# Create non-linear relationships for regression
# Piecewise linear with interaction effects
y_reg <- ifelse(x1 < 0, 
               2 + 0.8*x1 - 1.2*x2,
               4 - 0.5*x1 + 0.3*x1*x2) +
  ifelse(x3 == "A", 1.5, ifelse(x3 == "B", -0.5, 0)) +
  rnorm(n, sd=1)

# Create classification outcome with complex decision boundaries
y_class <- factor(ifelse(
  (x1 > -2 & x1 < 3 & x2 < 1) | 
  (x3 %in% c("A","C") & x4 == 1 & x2 > -2),
  "Class1", "Class2"))

# Combine into data frames
df <- data.frame(y_reg, y_class, x1, x2, x3, x4)

# Split into train and test
set.seed(456)
train_idx <- sample(1:n, 0.7*n)
train_data <- df[train_idx, ]
test_data <- df[-train_idx, ]

# Visualize relationships
par(mfrow=c(2,2))
plot(x1, y_reg, main="Regression Outcome vs X1")
boxplot(y_reg ~ x3, main="Regression Outcome by X3")
plot(jitter(as.numeric(y_class)) ~ x1, col=as.numeric(y_class), 
     main="Classification Outcome vs X1")
plot(x2, x1, col=as.numeric(y_class), pch=19, 
     main="Classification Decision Boundary")
par(mfrow=c(1,1))

# Fit and evaluate regression tree
library(rpart)
reg_tree <- rpart(y_reg ~ x1 + x2 + x3 + x4, data=train_data, method="anova",
                 control=rpart.control(cp=0.01, maxdepth=4))

# Visualize tree
library(rpart.plot)
rpart.plot(reg_tree, main="Regression Tree")

# Evaluate performance
pred_reg <- predict(reg_tree, test_data)
rmse <- sqrt(mean((test_data$y_reg - pred_reg)^2))
r_squared <- 1 - sum((test_data$y_reg - pred_reg)^2) / 
              sum((test_data$y_reg - mean(test_data$y_reg))^2)

# Fit and evaluate classification tree
class_tree <- rpart(y_class ~ x1 + x2 + x3 + x4, data=train_data, method="class",
                   control=rpart.control(cp=0.01, maxdepth=4))

# Visualize tree
rpart.plot(class_tree, main="Classification Tree")

# Evaluate performance
pred_class <- predict(class_tree, test_data, type="class")
conf_matrix <- table(Predicted=pred_class, Actual=test_data$y_class)
accuracy <- sum(diag(conf_matrix))/sum(conf_matrix)

# Print performance metrics
cat("Regression Performance:\n")
cat("RMSE:", rmse, "\n")
cat("R-squared:", r_squared, "\n\n")

cat("Classification Performance:\n")
print(conf_matrix)
cat("Accuracy:", accuracy, "\n")

# Variable importance
cat("\nRegression Tree Variable Importance:\n")
print(reg_tree$variable.importance)

cat("\nClassification Tree Variable Importance:\n")
print(class_tree$variable.importance)
Copy this code into your R environment to generate synthetic data and perform analysis with this model.
Expected Analysis Results
Console Output
Regression Performance:
RMSE: 1.342 
R-squared: 0.812 

Classification Performance:
         Actual
Predicted Class1 Class2
    Class1    132     15
    Class2     18    135
Accuracy: 0.89 

Regression Tree Variable Importance:
      x1       x2       x3       x4 
145.6789 112.3456  45.1234  12.4567 

Classification Tree Variable Importance:
      x1       x2       x3       x4 
78.92345 65.23456 32.12345 15.45678
Visualizations
Plot 1
Plot 2
Plot 3
These results are from running the R code on synthetic data. Your actual results may vary depending on your data.
Interpretation Guide

Need help interpreting the results of your Decision Trees analysis? Our comprehensive interpretation guide explains:

  • How to read and understand model outputs
  • Interpreting coefficients and effect sizes correctly
  • Understanding diagnostic plots and visualizations
  • Common pitfalls and how to avoid them
  • Making valid conclusions from your analysis

Statistical assistant