Pivot trees#
A pivot tree is a RuleTreeClassifier whose base stumps are pivot stumps: each split compares the distance of the instances from a pivot, an instance of the training set. See the pivot stumps in the user guide (Choosing the splits: stumps).
from RuleTree import RuleTreeClassifier
from RuleTree.stumps.classification import PivotTreeStumpClassifier
from sklearn.metrics import accuracy_score
from sklearn.datasets import load_breast_cancer
from sklearn.model_selection import train_test_split
# Load the breast cancer dataset
data = load_breast_cancer()
X = data.data # Features
y = data.target # Target labels
feature_names = data.feature_names
# Split the data into training and testing sets
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=42)
# Pivot-based stump: each split compares the distance of the instances from a pivot instance.
# The distance matrix is computed once at fitting time and cached in the tree.
pt_stump = PivotTreeStumpClassifier(distance_measure='euclidean')
print(pt_stump)
PivotTreeStumpClassifier()
# Use the pivot-based stump as base_stumps
rt_pivot = RuleTreeClassifier(
max_depth=3,
prune_useless_leaves=True,
random_state=42,
base_stumps=pt_stump,
)
rt_pivot.fit(X_train, y_train);
y_pred = rt_pivot.predict(X_test)
print('Prediction results', y_pred[0:10])
Prediction results [1 0 0 1 1 0 0 0 0 1]
print('Accuracy result: ', accuracy_score(y_test, y_pred))
Accuracy result: 0.9532163742690059
y_pred_proba = rt_pivot.predict_proba(X_test)
print('Prediction probability results', y_pred_proba[0:10])
Prediction probability results [[0.02880658 0.97119342]
[0.99212598 0.00787402]
[0.99212598 0.00787402]
[0.02880658 0.97119342]
[0.02880658 0.97119342]
[0.99212598 0.00787402]
[0.99212598 0.00787402]
[0.99212598 0.00787402]
[0.99212598 0.00787402]
[0.02880658 0.97119342]]
rules = rt_pivot.get_rules()
rt_pivot.print_rules(rules)
|--- P_149 <= 12.327
| |--- P_362 <= 3.08
| | output: 1
| |--- P_362 > 3.08
| |--- P_298 <= 3.704
| | output: 1
| |--- P_298 > 3.704
| output: 0
|--- P_149 > 12.327
|--- P_74 <= 9.548
| |--- P_267 <= 2.318
| | output: 0
| |--- P_267 > 2.318
| output: 1
|--- P_74 > 9.548
|--- P_61 <= 6.687
| output: 1
|--- P_61 > 6.687
output: 0
Drawing the tree#
In the rules, P_i is the distance from the training instance i, the pivot of the split.
plot_tree draws the tree with matplotlib.
import matplotlib.pyplot as plt
# wrap: at most 12 characters per line, for the long names of the features
rt_pivot.plot_tree(class_names=list(data.target_names), wrap=12)
plt.show()