RuleTree for clustering#

Initialize the RuleTreeCluster and train it on your dataset#

from RuleTree import RuleTreeCluster
from RuleTree.stumps.regression import DecisionTreeStumpRegressor
from sklearn.metrics import adjusted_rand_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)
# Initialize the RuleTreeCluster
# The `prune_useless_leaves` parameter allows pruning of leaves with the same prediction outcome.
# The 'bic_eps' parameter regulates the bayesian information criterion used for splitting.
# The split criterion is a parameter of the stumps used to split the nodes.
rtclu = RuleTreeCluster(
    max_depth=3,
    bic_eps=0.2,
    prune_useless_leaves=True,
    random_state=42,
    base_stumps=DecisionTreeStumpRegressor(criterion='squared_error'),
)

# Fit the RuleTreeCluster to the training data (no target is needed)
rtclu.fit(X_train)

# Extract the rules as a dictionary using feature names
rules = rtclu.get_rules(columns_names=feature_names)
# Print textual rules of trained tree
rtclu.print_rules(rules)
|--- mean concave points <= 0.059
|   |--- worst perimeter <= 97.665
|   |   |--- mean fractal dimension <= 0.062
|   |   |    output: 7
|   |   |--- mean fractal dimension > 0.062
|   |        output: 8
|   |--- worst perimeter > 97.665
|       |--- mean area <= 857.85
|       |    output: 9
|       |--- mean area > 857.85
|            output: 10
|--- mean concave points > 0.059
    |--- mean area <= 901.95
    |   |--- mean fractal dimension <= 0.075
    |   |    output: 11
    |   |--- mean fractal dimension > 0.075
    |        output: 12
    |--- mean area > 901.95
         output: 6

Drawing the tree#

plot_tree draws the tree with matplotlib: each internal node shows its rule and its number of training instances, each leaf its cluster. The arrow “true” leads to the child that gets the instances for which the rule is true.

import matplotlib.pyplot as plt

# wrap: at most 12 characters per line, for the long names of the features
rtclu.plot_tree(columns_names=feature_names, wrap=12)
plt.show()
../_images/c9f4d48f905c55ce1b710cd295da299fe3264f9871d103f4ca28ffa07916aef1.svg
y_pred = rtclu.predict(X_test)
print('Prediction results\n', y_pred[0:10])
Prediction results
 [ 8  6 11  8  8  6  6  6 11  9]
# Agreement between the clusters and the classes of the dataset
print('Adjusted Rand Index\n', adjusted_rand_score(y_test, y_pred))
Adjusted Rand Index
 0.26791975925875205

Clusters and classes#

The test instances projected on their first two principal components, colored by cluster (left) and by class (right).

from sklearn.decomposition import PCA
from sklearn.preprocessing import StandardScaler

points = PCA(n_components=2).fit(StandardScaler().fit_transform(X_train)).transform(
    StandardScaler().fit(X_train).transform(X_test))

fig, axes = plt.subplots(1, 2, figsize=(10, 4), sharex=True, sharey=True)
for ax, labels, title in [(axes[0], y_pred, "clusters"), (axes[1], y_test, "classes")]:
    for label in sorted(set(labels)):
        ax.scatter(*points[labels == label].T, s=12, label=str(label))
    ax.set_title(title)
    ax.set_xlabel("first principal component")
    ax.legend(frameon=False, fontsize=8)
axes[0].set_ylabel("second principal component")
plt.show()
../_images/3bf68a08b91df6d5ff332461c36eec26079e6b9e72ed36f4b97aa7e79bd8c5c5.svg