RuleTree for regression#
Initialize the RuleTreeRegressor and train it on your dataset#
from RuleTree import RuleTreeRegressor
from RuleTree.stumps.regression import DecisionTreeStumpRegressor
from sklearn.datasets import load_diabetes
from sklearn.model_selection import train_test_split
from sklearn.metrics import mean_squared_error
# Load the diabetes dataset
data = load_diabetes()
X = data.data # Features
y = data.target # Target values
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 RuleTreeRegressor
# The `prune_useless_leaves` parameter allows pruning of leaves with the same prediction outcome.
# The split criterion is a parameter of the stumps used to split the nodes.
rtr = RuleTreeRegressor(
max_depth=3,
prune_useless_leaves=True,
random_state=42,
base_stumps=DecisionTreeStumpRegressor(criterion='squared_error'),
)
# Fit the RuleTreeRegressor to the training data
rtr.fit(X_train, y_train)
# Extract the rules as a dictionary using feature names
rules = rtr.get_rules(columns_names=feature_names)
# Print textual rules of trained tree
rtr.print_rules(rules)
|--- bmi <= 0.005
| |--- s5 <= 0.014
| | |--- s2 <= 0.091
| | | output: 100.82
| | |--- s2 > 0.091
| | output: 241.5
| |--- s5 > 0.014
| |--- bp <= -0.032
| | output: 114.0
| |--- bp > -0.032
| output: 180.71
|--- bmi > 0.005
|--- bmi <= 0.073
| |--- bp <= 0.003
| | output: 160.05
| |--- bp > 0.003
| output: 210.98
|--- bmi > 0.073
|--- s2 <= 0.022
| output: 292.47
|--- s2 > 0.022
output: 225.75
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 predicted value, colored from low to high. 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
rtr.plot_tree(columns_names=feature_names, wrap=12)
plt.show()
y_pred = rtr.predict(X_test)
print('Prediction results\n', y_pred[0:10])
Prediction results
[180.71428571 210.98275862 180.71428571 210.98275862 100.81617647
241.5 225.75 210.98275862 114. 160.04651163]
print('MSE result\n', mean_squared_error(y_test, y_pred))
MSE result
3616.769894653006
Predicted and actual values#
Each leaf predicts one value, so the predictions take as many values as the leaves: the points form horizontal bands, closer to the diagonal the better the prediction.
fig, ax = plt.subplots(figsize=(5, 5))
ax.scatter(y_test, y_pred, s=15, alpha=0.6)
limits = [min(y_test.min(), y_pred.min()), max(y_test.max(), y_pred.max())]
ax.plot(limits, limits, color="gray", linestyle="--", linewidth=1)
ax.set_xlabel("actual value")
ax.set_ylabel("predicted value")
plt.show()
# Get local feature importances similar to https://github.com/andosa/treeinterpreter implementation
# Prediction is the sum of bias and feature contributions
prediction, bias, contributions = rtr.local_interpretation(X_test, joint_contribution=True)
print('First instance analysis')
print(f'Prediction: {prediction[0]}')
print(f'Bias: {bias[0]}')
print(f'Contributions: {contributions[0]}')
First instance analysis
Prediction: 180.71428571428572
Bias: 153.90291262135923
Contributions: {(2,): np.float64(-35.54772136452863), (2, 8): np.float64(47.53369763205828), (2, 3, 8): np.float64(14.825396825396837)}