Spaces:
Sleeping
Sleeping
init
Browse files- .gitignore +12 -0
- app.py +408 -0
- decision-tree.ipynb +509 -0
- requirements.txt +4 -0
.gitignore
ADDED
|
@@ -0,0 +1,12 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
__pycache__/
|
| 2 |
+
*.pyc
|
| 3 |
+
*.pyo
|
| 4 |
+
*.pyd
|
| 5 |
+
.Python
|
| 6 |
+
venv/
|
| 7 |
+
env/
|
| 8 |
+
*.egg-info/
|
| 9 |
+
dist/
|
| 10 |
+
build/
|
| 11 |
+
.ipynb_checkpoints/
|
| 12 |
+
.DS_Store
|
app.py
ADDED
|
@@ -0,0 +1,408 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import gradio as gr
|
| 2 |
+
import numpy as np
|
| 3 |
+
import matplotlib.pyplot as plt
|
| 4 |
+
from matplotlib.patches import Rectangle, FancyBboxPatch
|
| 5 |
+
import io
|
| 6 |
+
from PIL import Image
|
| 7 |
+
from matplotlib.patches import FancyArrowPatch
|
| 8 |
+
|
| 9 |
+
class TreeNode:
|
| 10 |
+
"""Represents a node in the decision tree"""
|
| 11 |
+
def __init__(self, depth=0, bounds=None):
|
| 12 |
+
self.depth = depth
|
| 13 |
+
self.bounds = bounds if bounds else {'x': (0, 10), 'y': (0, 10)}
|
| 14 |
+
self.feature = None # 'x' or 'y'
|
| 15 |
+
self.threshold = None
|
| 16 |
+
self.left = None
|
| 17 |
+
self.right = None
|
| 18 |
+
self.is_leaf = True
|
| 19 |
+
self.samples = None
|
| 20 |
+
self.class_counts = None
|
| 21 |
+
self.entropy = None
|
| 22 |
+
self.gini = None
|
| 23 |
+
self.majority_class = None
|
| 24 |
+
|
| 25 |
+
class DecisionTreePartitioner:
|
| 26 |
+
def __init__(self):
|
| 27 |
+
self.reset_data()
|
| 28 |
+
self.splits = [] # List of (feature, threshold) tuples
|
| 29 |
+
self.root = None
|
| 30 |
+
|
| 31 |
+
def reset_data(self):
|
| 32 |
+
"""Generate sample data with two classes"""
|
| 33 |
+
np.random.seed(42)
|
| 34 |
+
# Class 0 (blue) - bottom left
|
| 35 |
+
n_samples = 50
|
| 36 |
+
self.X0 = np.random.randn(n_samples, 2) * 1.5 + np.array([3, 3])
|
| 37 |
+
# Class 1 (red) - top right
|
| 38 |
+
self.X1 = np.random.randn(n_samples, 2) * 1.5 + np.array([7, 7])
|
| 39 |
+
|
| 40 |
+
self.X = np.vstack([self.X0, self.X1])
|
| 41 |
+
self.y = np.hstack([np.zeros(n_samples), np.ones(n_samples)])
|
| 42 |
+
self.splits = []
|
| 43 |
+
self.root = None
|
| 44 |
+
|
| 45 |
+
def calculate_entropy(self, y):
|
| 46 |
+
"""Calculate entropy for a set of labels"""
|
| 47 |
+
if len(y) == 0:
|
| 48 |
+
return 0
|
| 49 |
+
_, counts = np.unique(y, return_counts=True)
|
| 50 |
+
probabilities = counts / len(y)
|
| 51 |
+
entropy = -np.sum(probabilities * np.log2(probabilities + 1e-10))
|
| 52 |
+
return entropy
|
| 53 |
+
|
| 54 |
+
def calculate_gini(self, y):
|
| 55 |
+
"""Calculate Gini index for a set of labels"""
|
| 56 |
+
if len(y) == 0:
|
| 57 |
+
return 0
|
| 58 |
+
_, counts = np.unique(y, return_counts=True)
|
| 59 |
+
probabilities = counts / len(y)
|
| 60 |
+
gini = 1 - np.sum(probabilities ** 2)
|
| 61 |
+
return gini
|
| 62 |
+
|
| 63 |
+
def build_tree_from_splits(self):
|
| 64 |
+
"""Build tree structure from the list of splits"""
|
| 65 |
+
if not self.splits:
|
| 66 |
+
return None
|
| 67 |
+
|
| 68 |
+
self.root = TreeNode(depth=0)
|
| 69 |
+
self._build_node(self.root, np.arange(len(self.y)), 0)
|
| 70 |
+
return self.root
|
| 71 |
+
|
| 72 |
+
def _build_node(self, node, indices, split_idx):
|
| 73 |
+
"""Recursively build tree nodes"""
|
| 74 |
+
if len(indices) == 0:
|
| 75 |
+
return
|
| 76 |
+
|
| 77 |
+
# Calculate node statistics
|
| 78 |
+
node.samples = len(indices)
|
| 79 |
+
y_node = self.y[indices]
|
| 80 |
+
unique, counts = np.unique(y_node, return_counts=True)
|
| 81 |
+
node.class_counts = dict(zip(unique.astype(int), counts))
|
| 82 |
+
node.entropy = self.calculate_entropy(y_node)
|
| 83 |
+
node.gini = self.calculate_gini(y_node)
|
| 84 |
+
node.majority_class = int(unique[np.argmax(counts)])
|
| 85 |
+
|
| 86 |
+
# Check if we have more splits to apply
|
| 87 |
+
if split_idx >= len(self.splits):
|
| 88 |
+
node.is_leaf = True
|
| 89 |
+
return
|
| 90 |
+
|
| 91 |
+
# Apply the split
|
| 92 |
+
feature, threshold = self.splits[split_idx]
|
| 93 |
+
feature_idx = 0 if feature == 'x' else 1
|
| 94 |
+
|
| 95 |
+
X_node = self.X[indices]
|
| 96 |
+
left_mask = X_node[:, feature_idx] <= threshold
|
| 97 |
+
right_mask = ~left_mask
|
| 98 |
+
|
| 99 |
+
left_indices = indices[left_mask]
|
| 100 |
+
right_indices = indices[right_mask]
|
| 101 |
+
|
| 102 |
+
# Only create split if both children are non-empty
|
| 103 |
+
if len(left_indices) > 0 and len(right_indices) > 0:
|
| 104 |
+
node.is_leaf = False
|
| 105 |
+
node.feature = feature
|
| 106 |
+
node.threshold = threshold
|
| 107 |
+
|
| 108 |
+
# Create child nodes with updated bounds
|
| 109 |
+
left_bounds = node.bounds.copy()
|
| 110 |
+
right_bounds = node.bounds.copy()
|
| 111 |
+
|
| 112 |
+
if feature == 'x':
|
| 113 |
+
left_bounds['x'] = (node.bounds['x'][0], threshold)
|
| 114 |
+
right_bounds['x'] = (threshold, node.bounds['x'][1])
|
| 115 |
+
else:
|
| 116 |
+
left_bounds['y'] = (node.bounds['y'][0], threshold)
|
| 117 |
+
right_bounds['y'] = (threshold, node.bounds['y'][1])
|
| 118 |
+
|
| 119 |
+
node.left = TreeNode(depth=node.depth + 1, bounds=left_bounds)
|
| 120 |
+
node.right = TreeNode(depth=node.depth + 1, bounds=right_bounds)
|
| 121 |
+
|
| 122 |
+
# Recursively build children
|
| 123 |
+
self._build_node(node.left, left_indices, split_idx + 1)
|
| 124 |
+
self._build_node(node.right, right_indices, split_idx + 1)
|
| 125 |
+
|
| 126 |
+
def add_split(self, feature, threshold):
|
| 127 |
+
"""Add a new split to the tree"""
|
| 128 |
+
self.splits.append((feature, threshold))
|
| 129 |
+
self.build_tree_from_splits()
|
| 130 |
+
|
| 131 |
+
def remove_last_split(self):
|
| 132 |
+
"""Remove the last split"""
|
| 133 |
+
if self.splits:
|
| 134 |
+
self.splits.pop()
|
| 135 |
+
if self.splits:
|
| 136 |
+
self.build_tree_from_splits()
|
| 137 |
+
else:
|
| 138 |
+
self.root = None
|
| 139 |
+
|
| 140 |
+
def draw_tree(self, node=None, ax=None, x=0.5, y=1.0, dx=0.25, level=0):
|
| 141 |
+
"""Recursively draw the decision tree"""
|
| 142 |
+
if node is None:
|
| 143 |
+
return
|
| 144 |
+
|
| 145 |
+
# Node styling
|
| 146 |
+
if node.is_leaf:
|
| 147 |
+
box_color = 'lightblue' if node.majority_class == 0 else 'orange'
|
| 148 |
+
alpha = 0.7
|
| 149 |
+
else:
|
| 150 |
+
box_color = 'lightgreen'
|
| 151 |
+
alpha = 0.5
|
| 152 |
+
|
| 153 |
+
# Create node text
|
| 154 |
+
if node.is_leaf:
|
| 155 |
+
text = f"Leaf\nClass: {node.majority_class}\n"
|
| 156 |
+
text += f"Samples: {node.samples}\n"
|
| 157 |
+
text += f"Entropy: {node.entropy:.3f}\n"
|
| 158 |
+
text += f"Gini: {node.gini:.3f}"
|
| 159 |
+
else:
|
| 160 |
+
feature_name = "Width" if node.feature == 'x' else "Height"
|
| 161 |
+
text = f"{feature_name} ≤ {node.threshold:.2f}\n"
|
| 162 |
+
text += f"Samples: {node.samples}\n"
|
| 163 |
+
text += f"Entropy: {node.entropy:.3f}\n"
|
| 164 |
+
text += f"Gini: {node.gini:.3f}"
|
| 165 |
+
|
| 166 |
+
# Draw box
|
| 167 |
+
bbox = dict(boxstyle="round,pad=0.3", facecolor=box_color,
|
| 168 |
+
edgecolor='black', linewidth=2, alpha=alpha)
|
| 169 |
+
ax.text(x, y, text, ha='center', va='center', fontsize=8,
|
| 170 |
+
bbox=bbox, fontweight='bold')
|
| 171 |
+
|
| 172 |
+
# Draw connections to children
|
| 173 |
+
if not node.is_leaf and node.left and node.right:
|
| 174 |
+
# Left child
|
| 175 |
+
y_child = y - 0.15
|
| 176 |
+
x_left = x - dx
|
| 177 |
+
x_right = x + dx
|
| 178 |
+
|
| 179 |
+
# Draw arrows
|
| 180 |
+
arrow_left = FancyArrowPatch((x, y - 0.05), (x_left, y_child + 0.05),
|
| 181 |
+
arrowstyle='->', mutation_scale=20,
|
| 182 |
+
linewidth=2, color='blue')
|
| 183 |
+
arrow_right = FancyArrowPatch((x, y - 0.05), (x_right, y_child + 0.05),
|
| 184 |
+
arrowstyle='->', mutation_scale=20,
|
| 185 |
+
linewidth=2, color='red')
|
| 186 |
+
ax.add_patch(arrow_left)
|
| 187 |
+
ax.add_patch(arrow_right)
|
| 188 |
+
|
| 189 |
+
# Add Yes/No labels
|
| 190 |
+
ax.text((x + x_left) / 2, (y + y_child) / 2, 'Yes',
|
| 191 |
+
fontsize=9, color='blue', fontweight='bold')
|
| 192 |
+
ax.text((x + x_right) / 2, (y + y_child) / 2, 'No',
|
| 193 |
+
fontsize=9, color='red', fontweight='bold')
|
| 194 |
+
|
| 195 |
+
# Recursively draw children
|
| 196 |
+
self.draw_tree(node.left, ax, x_left, y_child, dx * 0.5, level + 1)
|
| 197 |
+
self.draw_tree(node.right, ax, x_right, y_child, dx * 0.5, level + 1)
|
| 198 |
+
|
| 199 |
+
def visualize(self, split_history):
|
| 200 |
+
"""Create comprehensive visualization"""
|
| 201 |
+
fig = plt.figure(figsize=(20, 10))
|
| 202 |
+
gs = fig.add_gridspec(2, 2, height_ratios=[1, 1], width_ratios=[1.2, 1])
|
| 203 |
+
|
| 204 |
+
ax1 = fig.add_subplot(gs[0, 0]) # Partition view
|
| 205 |
+
ax2 = fig.add_subplot(gs[1, 0]) # Decision tree
|
| 206 |
+
ax3 = fig.add_subplot(gs[:, 1]) # Statistics
|
| 207 |
+
|
| 208 |
+
# Parse split history
|
| 209 |
+
self.splits = []
|
| 210 |
+
if split_history.strip():
|
| 211 |
+
for line in split_history.strip().split('\n'):
|
| 212 |
+
if ',' in line:
|
| 213 |
+
parts = line.split(',')
|
| 214 |
+
if len(parts) == 2:
|
| 215 |
+
feature = parts[0].strip().lower()
|
| 216 |
+
try:
|
| 217 |
+
threshold = float(parts[1].strip())
|
| 218 |
+
self.splits.append((feature, threshold))
|
| 219 |
+
except ValueError:
|
| 220 |
+
pass
|
| 221 |
+
|
| 222 |
+
# Build tree from splits
|
| 223 |
+
if self.splits:
|
| 224 |
+
self.build_tree_from_splits()
|
| 225 |
+
|
| 226 |
+
# === Plot 1: Partitioned Feature Space ===
|
| 227 |
+
ax1.scatter(self.X[self.y == 0, 0], self.X[self.y == 0, 1],
|
| 228 |
+
c='blue', label='Class 0 (Lemon)', s=100, alpha=0.6, edgecolors='k')
|
| 229 |
+
ax1.scatter(self.X[self.y == 1, 0], self.X[self.y == 1, 1],
|
| 230 |
+
c='orange', label='Class 1 (Orange)', s=100, alpha=0.6, edgecolors='k')
|
| 231 |
+
|
| 232 |
+
# Draw all partition lines
|
| 233 |
+
colors = plt.cm.rainbow(np.linspace(0, 1, len(self.splits)))
|
| 234 |
+
for idx, (feature, threshold) in enumerate(self.splits):
|
| 235 |
+
if feature == 'x':
|
| 236 |
+
ax1.axvline(x=threshold, color=colors[idx], linewidth=2.5,
|
| 237 |
+
linestyle='--', label=f'Split {idx+1}: x≤{threshold:.1f}', alpha=0.8)
|
| 238 |
+
else:
|
| 239 |
+
ax1.axhline(y=threshold, color=colors[idx], linewidth=2.5,
|
| 240 |
+
linestyle='--', label=f'Split {idx+1}: y≤{threshold:.1f}', alpha=0.8)
|
| 241 |
+
|
| 242 |
+
ax1.set_xlabel('Feature 1 (Width)', fontsize=14, fontweight='bold')
|
| 243 |
+
ax1.set_ylabel('Feature 2 (Height)', fontsize=14, fontweight='bold')
|
| 244 |
+
ax1.set_title('Partitioned Feature Space', fontsize=16, fontweight='bold')
|
| 245 |
+
ax1.legend(fontsize=10, loc='upper left')
|
| 246 |
+
ax1.grid(True, alpha=0.3)
|
| 247 |
+
ax1.set_xlim(0, 10)
|
| 248 |
+
ax1.set_ylim(0, 10)
|
| 249 |
+
|
| 250 |
+
# === Plot 2: Decision Tree ===
|
| 251 |
+
ax2.clear()
|
| 252 |
+
ax2.set_xlim(0, 1)
|
| 253 |
+
ax2.set_ylim(0, 1)
|
| 254 |
+
ax2.axis('off')
|
| 255 |
+
ax2.set_title('Decision Tree Structure', fontsize=16, fontweight='bold', pad=20)
|
| 256 |
+
|
| 257 |
+
if self.root:
|
| 258 |
+
self.draw_tree(self.root, ax2)
|
| 259 |
+
else:
|
| 260 |
+
ax2.text(0.5, 0.5, 'No splits yet\nAdd splits to build the tree',
|
| 261 |
+
ha='center', va='center', fontsize=14,
|
| 262 |
+
bbox=dict(boxstyle='round', facecolor='wheat', alpha=0.5))
|
| 263 |
+
|
| 264 |
+
# === Plot 3: Statistics ===
|
| 265 |
+
ax3.clear()
|
| 266 |
+
ax3.axis('off')
|
| 267 |
+
|
| 268 |
+
# Calculate overall statistics
|
| 269 |
+
entropy_initial = self.calculate_entropy(self.y)
|
| 270 |
+
gini_initial = self.calculate_gini(self.y)
|
| 271 |
+
|
| 272 |
+
stats_text = "DECISION TREE STATISTICS\n" + "="*50 + "\n\n"
|
| 273 |
+
stats_text += f"Total Samples: {len(self.y)}\n"
|
| 274 |
+
stats_text += f" • Class 0: {np.sum(self.y == 0)}\n"
|
| 275 |
+
stats_text += f" • Class 1: {np.sum(self.y == 1)}\n\n"
|
| 276 |
+
stats_text += f"Initial Impurity:\n"
|
| 277 |
+
stats_text += f" • Entropy: {entropy_initial:.4f}\n"
|
| 278 |
+
stats_text += f" • Gini: {gini_initial:.4f}\n\n"
|
| 279 |
+
|
| 280 |
+
if self.splits:
|
| 281 |
+
stats_text += f"Number of Splits: {len(self.splits)}\n\n"
|
| 282 |
+
stats_text += "SPLIT SEQUENCE:\n" + "-"*50 + "\n"
|
| 283 |
+
|
| 284 |
+
for idx, (feature, threshold) in enumerate(self.splits):
|
| 285 |
+
feature_name = "Width (x)" if feature == 'x' else "Height (y)"
|
| 286 |
+
stats_text += f"\n{idx+1}. {feature_name} ≤ {threshold:.2f}\n"
|
| 287 |
+
|
| 288 |
+
# Get leaf statistics
|
| 289 |
+
leaves = []
|
| 290 |
+
self._collect_leaves(self.root, leaves)
|
| 291 |
+
|
| 292 |
+
if leaves:
|
| 293 |
+
stats_text += f"\n\nLEAF NODES: {len(leaves)}\n" + "-"*50 + "\n"
|
| 294 |
+
for idx, leaf in enumerate(leaves):
|
| 295 |
+
stats_text += f"\nLeaf {idx+1}:\n"
|
| 296 |
+
stats_text += f" • Samples: {leaf.samples}\n"
|
| 297 |
+
stats_text += f" • Class 0: {leaf.class_counts.get(0, 0)} | "
|
| 298 |
+
stats_text += f"Class 1: {leaf.class_counts.get(1, 0)}\n"
|
| 299 |
+
stats_text += f" • Prediction: Class {leaf.majority_class}\n"
|
| 300 |
+
stats_text += f" • Entropy: {leaf.entropy:.4f}\n"
|
| 301 |
+
stats_text += f" • Gini: {leaf.gini:.4f}\n"
|
| 302 |
+
|
| 303 |
+
# Calculate weighted average impurity
|
| 304 |
+
total_samples = sum(leaf.samples for leaf in leaves)
|
| 305 |
+
avg_entropy = sum(leaf.entropy * leaf.samples for leaf in leaves) / total_samples
|
| 306 |
+
avg_gini = sum(leaf.gini * leaf.samples for leaf in leaves) / total_samples
|
| 307 |
+
|
| 308 |
+
stats_text += f"\n\nWEIGHTED AVERAGE IMPURITY:\n" + "-"*50 + "\n"
|
| 309 |
+
stats_text += f" • Entropy: {avg_entropy:.4f}\n"
|
| 310 |
+
stats_text += f" • Gini: {avg_gini:.4f}\n"
|
| 311 |
+
stats_text += f"\nTOTAL INFORMATION GAIN:\n"
|
| 312 |
+
stats_text += f" • {entropy_initial - avg_entropy:.4f}\n"
|
| 313 |
+
stats_text += f"\nTOTAL GINI REDUCTION:\n"
|
| 314 |
+
stats_text += f" • {gini_initial - avg_gini:.4f}\n"
|
| 315 |
+
else:
|
| 316 |
+
stats_text += "No splits applied yet.\n"
|
| 317 |
+
stats_text += "\nAdd splits in the format:\n"
|
| 318 |
+
stats_text += " feature, threshold\n\n"
|
| 319 |
+
stats_text += "Example:\n"
|
| 320 |
+
stats_text += " x, 5.0\n"
|
| 321 |
+
stats_text += " y, 6.5\n"
|
| 322 |
+
|
| 323 |
+
ax3.text(0.05, 0.95, stats_text, transform=ax3.transAxes,
|
| 324 |
+
fontsize=10, verticalalignment='top',
|
| 325 |
+
bbox=dict(boxstyle='round', facecolor='wheat', alpha=0.5),
|
| 326 |
+
family='monospace')
|
| 327 |
+
|
| 328 |
+
plt.tight_layout()
|
| 329 |
+
|
| 330 |
+
# Convert to image
|
| 331 |
+
buf = io.BytesIO()
|
| 332 |
+
plt.savefig(buf, format='png', dpi=120, bbox_inches='tight')
|
| 333 |
+
buf.seek(0)
|
| 334 |
+
img = Image.open(buf)
|
| 335 |
+
plt.close()
|
| 336 |
+
|
| 337 |
+
return img
|
| 338 |
+
|
| 339 |
+
def _collect_leaves(self, node, leaves):
|
| 340 |
+
"""Collect all leaf nodes"""
|
| 341 |
+
if node is None:
|
| 342 |
+
return
|
| 343 |
+
if node.is_leaf:
|
| 344 |
+
leaves.append(node)
|
| 345 |
+
else:
|
| 346 |
+
self._collect_leaves(node.left, leaves)
|
| 347 |
+
self._collect_leaves(node.right, leaves)
|
| 348 |
+
|
| 349 |
+
# Create the partitioner
|
| 350 |
+
partitioner = DecisionTreePartitioner()
|
| 351 |
+
|
| 352 |
+
# Create Gradio interface
|
| 353 |
+
with gr.Blocks(title="Multi-Split Decision Tree Visualizer", theme=gr.themes.Soft()) as demo:
|
| 354 |
+
gr.Markdown("""
|
| 355 |
+
# 🌳 Interactive Multi-Split Decision Tree Visualizer
|
| 356 |
+
|
| 357 |
+
Build a decision tree step-by-step and visualize the partitioning process!
|
| 358 |
+
|
| 359 |
+
""")
|
| 360 |
+
|
| 361 |
+
with gr.Row():
|
| 362 |
+
with gr.Column(scale=1):
|
| 363 |
+
split_input = gr.Textbox(
|
| 364 |
+
label="📝 Split Sequence (one per line: feature, threshold)",
|
| 365 |
+
placeholder="x, 5.0\ny, 6.5\nx, 3.0",
|
| 366 |
+
lines=10,
|
| 367 |
+
value="x, 5.0"
|
| 368 |
+
)
|
| 369 |
+
|
| 370 |
+
update_btn = gr.Button("🔄 Update Visualization", variant="primary", size="lg")
|
| 371 |
+
|
| 372 |
+
gr.Markdown("""
|
| 373 |
+
### Example Splits:
|
| 374 |
+
**Simple 2-split tree:**
|
| 375 |
+
```
|
| 376 |
+
x, 5.0
|
| 377 |
+
y, 6.5
|
| 378 |
+
```
|
| 379 |
+
|
| 380 |
+
**Complex 4-split tree:**
|
| 381 |
+
```
|
| 382 |
+
x, 5.0
|
| 383 |
+
y, 6.5
|
| 384 |
+
x, 3.0
|
| 385 |
+
y, 8.0
|
| 386 |
+
```
|
| 387 |
+
""")
|
| 388 |
+
|
| 389 |
+
with gr.Column(scale=2):
|
| 390 |
+
output_image = gr.Image(label="Visualization", height=800)
|
| 391 |
+
|
| 392 |
+
# Update visualization
|
| 393 |
+
update_btn.click(
|
| 394 |
+
fn=partitioner.visualize,
|
| 395 |
+
inputs=[split_input],
|
| 396 |
+
outputs=output_image
|
| 397 |
+
)
|
| 398 |
+
|
| 399 |
+
# Initial visualization
|
| 400 |
+
demo.load(
|
| 401 |
+
fn=partitioner.visualize,
|
| 402 |
+
inputs=[split_input],
|
| 403 |
+
outputs=output_image
|
| 404 |
+
)
|
| 405 |
+
|
| 406 |
+
# Launch the app
|
| 407 |
+
if __name__ == "__main__":
|
| 408 |
+
demo.launch()
|
decision-tree.ipynb
ADDED
|
@@ -0,0 +1,509 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"cells": [
|
| 3 |
+
{
|
| 4 |
+
"cell_type": "markdown",
|
| 5 |
+
"id": "164d7e04",
|
| 6 |
+
"metadata": {},
|
| 7 |
+
"source": [
|
| 8 |
+
"# Multi-Split Decision Tree Visualizer\n",
|
| 9 |
+
"\n",
|
| 10 |
+
"This notebook creates an interactive Gradio app to visualize how decision trees partition the feature space with **multiple splits** and shows the complete **decision tree structure**.\n",
|
| 11 |
+
"\n",
|
| 12 |
+
"## ✨ New Features:\n",
|
| 13 |
+
"- **Multiple Partitions**: Add as many splits as you want to build a complete tree\n",
|
| 14 |
+
"- **Decision Tree Visualization**: See the tree structure with all nodes and connections\n",
|
| 15 |
+
"- **Interactive Split Entry**: Add splits in a simple text format (feature, threshold)\n",
|
| 16 |
+
"- **Comprehensive Statistics**: Track entropy and Gini index for each node and leaf\n",
|
| 17 |
+
"- **Color-coded Visualization**: \n",
|
| 18 |
+
" - Blue arrows = \"Yes\" branch (≤ threshold)\n",
|
| 19 |
+
" - Red arrows = \"No\" branch (> threshold)\n",
|
| 20 |
+
" - Light blue leaves = Predicts Class 0 (Lemon)\n",
|
| 21 |
+
" - Orange leaves = Predicts Class 1 (Orange)\n",
|
| 22 |
+
"\n",
|
| 23 |
+
"## 📊 Three-Panel Display:\n",
|
| 24 |
+
"1. **Top-Left**: Partitioned feature space with all split boundaries\n",
|
| 25 |
+
"2. **Bottom-Left**: Complete decision tree structure\n",
|
| 26 |
+
"3. **Right**: Detailed statistics and impurity measures"
|
| 27 |
+
]
|
| 28 |
+
},
|
| 29 |
+
{
|
| 30 |
+
"cell_type": "code",
|
| 31 |
+
"execution_count": 1,
|
| 32 |
+
"id": "8b654a81",
|
| 33 |
+
"metadata": {},
|
| 34 |
+
"outputs": [
|
| 35 |
+
{
|
| 36 |
+
"name": "stderr",
|
| 37 |
+
"output_type": "stream",
|
| 38 |
+
"text": [
|
| 39 |
+
"c:\\Users\\rinab\\miniforge3\\envs\\WORK\\lib\\site-packages\\tqdm\\auto.py:21: TqdmWarning: IProgress not found. Please update jupyter and ipywidgets. See https://ipywidgets.readthedocs.io/en/stable/user_install.html\n",
|
| 40 |
+
" from .autonotebook import tqdm as notebook_tqdm\n"
|
| 41 |
+
]
|
| 42 |
+
},
|
| 43 |
+
{
|
| 44 |
+
"name": "stdout",
|
| 45 |
+
"output_type": "stream",
|
| 46 |
+
"text": [
|
| 47 |
+
"* Running on local URL: http://127.0.0.1:7860\n",
|
| 48 |
+
"* Running on public URL: https://4d58db9d9d6f8c53bc.gradio.live\n",
|
| 49 |
+
"\n",
|
| 50 |
+
"This share link expires in 1 week. For free permanent hosting and GPU upgrades, run `gradio deploy` from the terminal in the working directory to deploy to Hugging Face Spaces (https://huggingface.co/spaces)\n",
|
| 51 |
+
"* Running on public URL: https://4d58db9d9d6f8c53bc.gradio.live\n",
|
| 52 |
+
"\n",
|
| 53 |
+
"This share link expires in 1 week. For free permanent hosting and GPU upgrades, run `gradio deploy` from the terminal in the working directory to deploy to Hugging Face Spaces (https://huggingface.co/spaces)\n"
|
| 54 |
+
]
|
| 55 |
+
},
|
| 56 |
+
{
|
| 57 |
+
"data": {
|
| 58 |
+
"text/html": [
|
| 59 |
+
"<div><iframe src=\"https://4d58db9d9d6f8c53bc.gradio.live\" width=\"100%\" height=\"500\" allow=\"autoplay; camera; microphone; clipboard-read; clipboard-write;\" frameborder=\"0\" allowfullscreen></iframe></div>"
|
| 60 |
+
],
|
| 61 |
+
"text/plain": [
|
| 62 |
+
"<IPython.core.display.HTML object>"
|
| 63 |
+
]
|
| 64 |
+
},
|
| 65 |
+
"metadata": {},
|
| 66 |
+
"output_type": "display_data"
|
| 67 |
+
},
|
| 68 |
+
{
|
| 69 |
+
"data": {
|
| 70 |
+
"text/plain": []
|
| 71 |
+
},
|
| 72 |
+
"execution_count": 1,
|
| 73 |
+
"metadata": {},
|
| 74 |
+
"output_type": "execute_result"
|
| 75 |
+
}
|
| 76 |
+
],
|
| 77 |
+
"source": [
|
| 78 |
+
"import gradio as gr\n",
|
| 79 |
+
"import numpy as np\n",
|
| 80 |
+
"import matplotlib.pyplot as plt\n",
|
| 81 |
+
"from matplotlib.patches import Rectangle, FancyBboxPatch\n",
|
| 82 |
+
"import io\n",
|
| 83 |
+
"from PIL import Image\n",
|
| 84 |
+
"from matplotlib.patches import FancyArrowPatch\n",
|
| 85 |
+
"\n",
|
| 86 |
+
"class TreeNode:\n",
|
| 87 |
+
" \"\"\"Represents a node in the decision tree\"\"\"\n",
|
| 88 |
+
" def __init__(self, depth=0, bounds=None):\n",
|
| 89 |
+
" self.depth = depth\n",
|
| 90 |
+
" self.bounds = bounds if bounds else {'x': (0, 10), 'y': (0, 10)}\n",
|
| 91 |
+
" self.feature = None # 'x' or 'y'\n",
|
| 92 |
+
" self.threshold = None\n",
|
| 93 |
+
" self.left = None\n",
|
| 94 |
+
" self.right = None\n",
|
| 95 |
+
" self.is_leaf = True\n",
|
| 96 |
+
" self.samples = None\n",
|
| 97 |
+
" self.class_counts = None\n",
|
| 98 |
+
" self.entropy = None\n",
|
| 99 |
+
" self.gini = None\n",
|
| 100 |
+
" self.majority_class = None\n",
|
| 101 |
+
" \n",
|
| 102 |
+
"class DecisionTreePartitioner:\n",
|
| 103 |
+
" def __init__(self):\n",
|
| 104 |
+
" self.reset_data()\n",
|
| 105 |
+
" self.splits = [] # List of (feature, threshold) tuples\n",
|
| 106 |
+
" self.root = None\n",
|
| 107 |
+
" \n",
|
| 108 |
+
" def reset_data(self):\n",
|
| 109 |
+
" \"\"\"Generate sample data with two classes\"\"\"\n",
|
| 110 |
+
" np.random.seed(42)\n",
|
| 111 |
+
" # Class 0 (blue) - bottom left\n",
|
| 112 |
+
" n_samples = 50\n",
|
| 113 |
+
" self.X0 = np.random.randn(n_samples, 2) * 1.5 + np.array([3, 3])\n",
|
| 114 |
+
" # Class 1 (red) - top right \n",
|
| 115 |
+
" self.X1 = np.random.randn(n_samples, 2) * 1.5 + np.array([7, 7])\n",
|
| 116 |
+
" \n",
|
| 117 |
+
" self.X = np.vstack([self.X0, self.X1])\n",
|
| 118 |
+
" self.y = np.hstack([np.zeros(n_samples), np.ones(n_samples)])\n",
|
| 119 |
+
" self.splits = []\n",
|
| 120 |
+
" self.root = None\n",
|
| 121 |
+
" \n",
|
| 122 |
+
" def calculate_entropy(self, y):\n",
|
| 123 |
+
" \"\"\"Calculate entropy for a set of labels\"\"\"\n",
|
| 124 |
+
" if len(y) == 0:\n",
|
| 125 |
+
" return 0\n",
|
| 126 |
+
" _, counts = np.unique(y, return_counts=True)\n",
|
| 127 |
+
" probabilities = counts / len(y)\n",
|
| 128 |
+
" entropy = -np.sum(probabilities * np.log2(probabilities + 1e-10))\n",
|
| 129 |
+
" return entropy\n",
|
| 130 |
+
" \n",
|
| 131 |
+
" def calculate_gini(self, y):\n",
|
| 132 |
+
" \"\"\"Calculate Gini index for a set of labels\"\"\"\n",
|
| 133 |
+
" if len(y) == 0:\n",
|
| 134 |
+
" return 0\n",
|
| 135 |
+
" _, counts = np.unique(y, return_counts=True)\n",
|
| 136 |
+
" probabilities = counts / len(y)\n",
|
| 137 |
+
" gini = 1 - np.sum(probabilities ** 2)\n",
|
| 138 |
+
" return gini\n",
|
| 139 |
+
" \n",
|
| 140 |
+
" def build_tree_from_splits(self):\n",
|
| 141 |
+
" \"\"\"Build tree structure from the list of splits\"\"\"\n",
|
| 142 |
+
" if not self.splits:\n",
|
| 143 |
+
" return None\n",
|
| 144 |
+
" \n",
|
| 145 |
+
" self.root = TreeNode(depth=0)\n",
|
| 146 |
+
" self._build_node(self.root, np.arange(len(self.y)), 0)\n",
|
| 147 |
+
" return self.root\n",
|
| 148 |
+
" \n",
|
| 149 |
+
" def _build_node(self, node, indices, split_idx):\n",
|
| 150 |
+
" \"\"\"Recursively build tree nodes\"\"\"\n",
|
| 151 |
+
" if len(indices) == 0:\n",
|
| 152 |
+
" return\n",
|
| 153 |
+
" \n",
|
| 154 |
+
" # Calculate node statistics\n",
|
| 155 |
+
" node.samples = len(indices)\n",
|
| 156 |
+
" y_node = self.y[indices]\n",
|
| 157 |
+
" unique, counts = np.unique(y_node, return_counts=True)\n",
|
| 158 |
+
" node.class_counts = dict(zip(unique.astype(int), counts))\n",
|
| 159 |
+
" node.entropy = self.calculate_entropy(y_node)\n",
|
| 160 |
+
" node.gini = self.calculate_gini(y_node)\n",
|
| 161 |
+
" node.majority_class = int(unique[np.argmax(counts)])\n",
|
| 162 |
+
" \n",
|
| 163 |
+
" # Check if we have more splits to apply\n",
|
| 164 |
+
" if split_idx >= len(self.splits):\n",
|
| 165 |
+
" node.is_leaf = True\n",
|
| 166 |
+
" return\n",
|
| 167 |
+
" \n",
|
| 168 |
+
" # Apply the split\n",
|
| 169 |
+
" feature, threshold = self.splits[split_idx]\n",
|
| 170 |
+
" feature_idx = 0 if feature == 'x' else 1\n",
|
| 171 |
+
" \n",
|
| 172 |
+
" X_node = self.X[indices]\n",
|
| 173 |
+
" left_mask = X_node[:, feature_idx] <= threshold\n",
|
| 174 |
+
" right_mask = ~left_mask\n",
|
| 175 |
+
" \n",
|
| 176 |
+
" left_indices = indices[left_mask]\n",
|
| 177 |
+
" right_indices = indices[right_mask]\n",
|
| 178 |
+
" \n",
|
| 179 |
+
" # Only create split if both children are non-empty\n",
|
| 180 |
+
" if len(left_indices) > 0 and len(right_indices) > 0:\n",
|
| 181 |
+
" node.is_leaf = False\n",
|
| 182 |
+
" node.feature = feature\n",
|
| 183 |
+
" node.threshold = threshold\n",
|
| 184 |
+
" \n",
|
| 185 |
+
" # Create child nodes with updated bounds\n",
|
| 186 |
+
" left_bounds = node.bounds.copy()\n",
|
| 187 |
+
" right_bounds = node.bounds.copy()\n",
|
| 188 |
+
" \n",
|
| 189 |
+
" if feature == 'x':\n",
|
| 190 |
+
" left_bounds['x'] = (node.bounds['x'][0], threshold)\n",
|
| 191 |
+
" right_bounds['x'] = (threshold, node.bounds['x'][1])\n",
|
| 192 |
+
" else:\n",
|
| 193 |
+
" left_bounds['y'] = (node.bounds['y'][0], threshold)\n",
|
| 194 |
+
" right_bounds['y'] = (threshold, node.bounds['y'][1])\n",
|
| 195 |
+
" \n",
|
| 196 |
+
" node.left = TreeNode(depth=node.depth + 1, bounds=left_bounds)\n",
|
| 197 |
+
" node.right = TreeNode(depth=node.depth + 1, bounds=right_bounds)\n",
|
| 198 |
+
" \n",
|
| 199 |
+
" # Recursively build children\n",
|
| 200 |
+
" self._build_node(node.left, left_indices, split_idx + 1)\n",
|
| 201 |
+
" self._build_node(node.right, right_indices, split_idx + 1)\n",
|
| 202 |
+
" \n",
|
| 203 |
+
" def add_split(self, feature, threshold):\n",
|
| 204 |
+
" \"\"\"Add a new split to the tree\"\"\"\n",
|
| 205 |
+
" self.splits.append((feature, threshold))\n",
|
| 206 |
+
" self.build_tree_from_splits()\n",
|
| 207 |
+
" \n",
|
| 208 |
+
" def remove_last_split(self):\n",
|
| 209 |
+
" \"\"\"Remove the last split\"\"\"\n",
|
| 210 |
+
" if self.splits:\n",
|
| 211 |
+
" self.splits.pop()\n",
|
| 212 |
+
" if self.splits:\n",
|
| 213 |
+
" self.build_tree_from_splits()\n",
|
| 214 |
+
" else:\n",
|
| 215 |
+
" self.root = None\n",
|
| 216 |
+
" \n",
|
| 217 |
+
" def draw_tree(self, node=None, ax=None, x=0.5, y=1.0, dx=0.25, level=0):\n",
|
| 218 |
+
" \"\"\"Recursively draw the decision tree\"\"\"\n",
|
| 219 |
+
" if node is None:\n",
|
| 220 |
+
" return\n",
|
| 221 |
+
" \n",
|
| 222 |
+
" # Node styling\n",
|
| 223 |
+
" if node.is_leaf:\n",
|
| 224 |
+
" box_color = 'lightblue' if node.majority_class == 0 else 'orange'\n",
|
| 225 |
+
" alpha = 0.7\n",
|
| 226 |
+
" else:\n",
|
| 227 |
+
" box_color = 'lightgreen'\n",
|
| 228 |
+
" alpha = 0.5\n",
|
| 229 |
+
" \n",
|
| 230 |
+
" # Create node text\n",
|
| 231 |
+
" if node.is_leaf:\n",
|
| 232 |
+
" text = f\"Leaf\\nClass: {node.majority_class}\\n\"\n",
|
| 233 |
+
" text += f\"Samples: {node.samples}\\n\"\n",
|
| 234 |
+
" text += f\"Entropy: {node.entropy:.3f}\\n\"\n",
|
| 235 |
+
" text += f\"Gini: {node.gini:.3f}\"\n",
|
| 236 |
+
" else:\n",
|
| 237 |
+
" feature_name = \"Width\" if node.feature == 'x' else \"Height\"\n",
|
| 238 |
+
" text = f\"{feature_name} ≤ {node.threshold:.2f}\\n\"\n",
|
| 239 |
+
" text += f\"Samples: {node.samples}\\n\"\n",
|
| 240 |
+
" text += f\"Entropy: {node.entropy:.3f}\\n\"\n",
|
| 241 |
+
" text += f\"Gini: {node.gini:.3f}\"\n",
|
| 242 |
+
" \n",
|
| 243 |
+
" # Draw box\n",
|
| 244 |
+
" bbox = dict(boxstyle=\"round,pad=0.3\", facecolor=box_color, \n",
|
| 245 |
+
" edgecolor='black', linewidth=2, alpha=alpha)\n",
|
| 246 |
+
" ax.text(x, y, text, ha='center', va='center', fontsize=8,\n",
|
| 247 |
+
" bbox=bbox, fontweight='bold')\n",
|
| 248 |
+
" \n",
|
| 249 |
+
" # Draw connections to children\n",
|
| 250 |
+
" if not node.is_leaf and node.left and node.right:\n",
|
| 251 |
+
" # Left child\n",
|
| 252 |
+
" y_child = y - 0.15\n",
|
| 253 |
+
" x_left = x - dx\n",
|
| 254 |
+
" x_right = x + dx\n",
|
| 255 |
+
" \n",
|
| 256 |
+
" # Draw arrows\n",
|
| 257 |
+
" arrow_left = FancyArrowPatch((x, y - 0.05), (x_left, y_child + 0.05),\n",
|
| 258 |
+
" arrowstyle='->', mutation_scale=20, \n",
|
| 259 |
+
" linewidth=2, color='blue')\n",
|
| 260 |
+
" arrow_right = FancyArrowPatch((x, y - 0.05), (x_right, y_child + 0.05),\n",
|
| 261 |
+
" arrowstyle='->', mutation_scale=20,\n",
|
| 262 |
+
" linewidth=2, color='red')\n",
|
| 263 |
+
" ax.add_patch(arrow_left)\n",
|
| 264 |
+
" ax.add_patch(arrow_right)\n",
|
| 265 |
+
" \n",
|
| 266 |
+
" # Add Yes/No labels\n",
|
| 267 |
+
" ax.text((x + x_left) / 2, (y + y_child) / 2, 'Yes', \n",
|
| 268 |
+
" fontsize=9, color='blue', fontweight='bold')\n",
|
| 269 |
+
" ax.text((x + x_right) / 2, (y + y_child) / 2, 'No',\n",
|
| 270 |
+
" fontsize=9, color='red', fontweight='bold')\n",
|
| 271 |
+
" \n",
|
| 272 |
+
" # Recursively draw children\n",
|
| 273 |
+
" self.draw_tree(node.left, ax, x_left, y_child, dx * 0.5, level + 1)\n",
|
| 274 |
+
" self.draw_tree(node.right, ax, x_right, y_child, dx * 0.5, level + 1)\n",
|
| 275 |
+
" \n",
|
| 276 |
+
" def visualize(self, split_history):\n",
|
| 277 |
+
" \"\"\"Create comprehensive visualization\"\"\"\n",
|
| 278 |
+
" fig = plt.figure(figsize=(20, 10))\n",
|
| 279 |
+
" gs = fig.add_gridspec(2, 2, height_ratios=[1, 1], width_ratios=[1.2, 1])\n",
|
| 280 |
+
" \n",
|
| 281 |
+
" ax1 = fig.add_subplot(gs[0, 0]) # Partition view\n",
|
| 282 |
+
" ax2 = fig.add_subplot(gs[1, 0]) # Decision tree\n",
|
| 283 |
+
" ax3 = fig.add_subplot(gs[:, 1]) # Statistics\n",
|
| 284 |
+
" \n",
|
| 285 |
+
" # Parse split history\n",
|
| 286 |
+
" self.splits = []\n",
|
| 287 |
+
" if split_history.strip():\n",
|
| 288 |
+
" for line in split_history.strip().split('\\n'):\n",
|
| 289 |
+
" if ',' in line:\n",
|
| 290 |
+
" parts = line.split(',')\n",
|
| 291 |
+
" if len(parts) == 2:\n",
|
| 292 |
+
" feature = parts[0].strip().lower()\n",
|
| 293 |
+
" try:\n",
|
| 294 |
+
" threshold = float(parts[1].strip())\n",
|
| 295 |
+
" self.splits.append((feature, threshold))\n",
|
| 296 |
+
" except ValueError:\n",
|
| 297 |
+
" pass\n",
|
| 298 |
+
" \n",
|
| 299 |
+
" # Build tree from splits\n",
|
| 300 |
+
" if self.splits:\n",
|
| 301 |
+
" self.build_tree_from_splits()\n",
|
| 302 |
+
" \n",
|
| 303 |
+
" # === Plot 1: Partitioned Feature Space ===\n",
|
| 304 |
+
" ax1.scatter(self.X[self.y == 0, 0], self.X[self.y == 0, 1], \n",
|
| 305 |
+
" c='blue', label='Class 0 (Lemon)', s=100, alpha=0.6, edgecolors='k')\n",
|
| 306 |
+
" ax1.scatter(self.X[self.y == 1, 0], self.X[self.y == 1, 1], \n",
|
| 307 |
+
" c='orange', label='Class 1 (Orange)', s=100, alpha=0.6, edgecolors='k')\n",
|
| 308 |
+
" \n",
|
| 309 |
+
" # Draw all partition lines\n",
|
| 310 |
+
" colors = plt.cm.rainbow(np.linspace(0, 1, len(self.splits)))\n",
|
| 311 |
+
" for idx, (feature, threshold) in enumerate(self.splits):\n",
|
| 312 |
+
" if feature == 'x':\n",
|
| 313 |
+
" ax1.axvline(x=threshold, color=colors[idx], linewidth=2.5, \n",
|
| 314 |
+
" linestyle='--', label=f'Split {idx+1}: x≤{threshold:.1f}', alpha=0.8)\n",
|
| 315 |
+
" else:\n",
|
| 316 |
+
" ax1.axhline(y=threshold, color=colors[idx], linewidth=2.5,\n",
|
| 317 |
+
" linestyle='--', label=f'Split {idx+1}: y≤{threshold:.1f}', alpha=0.8)\n",
|
| 318 |
+
" \n",
|
| 319 |
+
" ax1.set_xlabel('Feature 1 (Width)', fontsize=14, fontweight='bold')\n",
|
| 320 |
+
" ax1.set_ylabel('Feature 2 (Height)', fontsize=14, fontweight='bold')\n",
|
| 321 |
+
" ax1.set_title('Partitioned Feature Space', fontsize=16, fontweight='bold')\n",
|
| 322 |
+
" ax1.legend(fontsize=10, loc='upper left')\n",
|
| 323 |
+
" ax1.grid(True, alpha=0.3)\n",
|
| 324 |
+
" ax1.set_xlim(0, 10)\n",
|
| 325 |
+
" ax1.set_ylim(0, 10)\n",
|
| 326 |
+
" \n",
|
| 327 |
+
" # === Plot 2: Decision Tree ===\n",
|
| 328 |
+
" ax2.clear()\n",
|
| 329 |
+
" ax2.set_xlim(0, 1)\n",
|
| 330 |
+
" ax2.set_ylim(0, 1)\n",
|
| 331 |
+
" ax2.axis('off')\n",
|
| 332 |
+
" ax2.set_title('Decision Tree Structure', fontsize=16, fontweight='bold', pad=20)\n",
|
| 333 |
+
" \n",
|
| 334 |
+
" if self.root:\n",
|
| 335 |
+
" self.draw_tree(self.root, ax2)\n",
|
| 336 |
+
" else:\n",
|
| 337 |
+
" ax2.text(0.5, 0.5, 'No splits yet\\nAdd splits to build the tree', \n",
|
| 338 |
+
" ha='center', va='center', fontsize=14,\n",
|
| 339 |
+
" bbox=dict(boxstyle='round', facecolor='wheat', alpha=0.5))\n",
|
| 340 |
+
" \n",
|
| 341 |
+
" # === Plot 3: Statistics ===\n",
|
| 342 |
+
" ax3.clear()\n",
|
| 343 |
+
" ax3.axis('off')\n",
|
| 344 |
+
" \n",
|
| 345 |
+
" # Calculate overall statistics\n",
|
| 346 |
+
" entropy_initial = self.calculate_entropy(self.y)\n",
|
| 347 |
+
" gini_initial = self.calculate_gini(self.y)\n",
|
| 348 |
+
" \n",
|
| 349 |
+
" stats_text = \"DECISION TREE STATISTICS\\n\" + \"=\"*50 + \"\\n\\n\"\n",
|
| 350 |
+
" stats_text += f\"Total Samples: {len(self.y)}\\n\"\n",
|
| 351 |
+
" stats_text += f\" • Class 0: {np.sum(self.y == 0)}\\n\"\n",
|
| 352 |
+
" stats_text += f\" • Class 1: {np.sum(self.y == 1)}\\n\\n\"\n",
|
| 353 |
+
" stats_text += f\"Initial Impurity:\\n\"\n",
|
| 354 |
+
" stats_text += f\" • Entropy: {entropy_initial:.4f}\\n\"\n",
|
| 355 |
+
" stats_text += f\" • Gini: {gini_initial:.4f}\\n\\n\"\n",
|
| 356 |
+
" \n",
|
| 357 |
+
" if self.splits:\n",
|
| 358 |
+
" stats_text += f\"Number of Splits: {len(self.splits)}\\n\\n\"\n",
|
| 359 |
+
" stats_text += \"SPLIT SEQUENCE:\\n\" + \"-\"*50 + \"\\n\"\n",
|
| 360 |
+
" \n",
|
| 361 |
+
" for idx, (feature, threshold) in enumerate(self.splits):\n",
|
| 362 |
+
" feature_name = \"Width (x)\" if feature == 'x' else \"Height (y)\"\n",
|
| 363 |
+
" stats_text += f\"\\n{idx+1}. {feature_name} ≤ {threshold:.2f}\\n\"\n",
|
| 364 |
+
" \n",
|
| 365 |
+
" # Get leaf statistics\n",
|
| 366 |
+
" leaves = []\n",
|
| 367 |
+
" self._collect_leaves(self.root, leaves)\n",
|
| 368 |
+
" \n",
|
| 369 |
+
" if leaves:\n",
|
| 370 |
+
" stats_text += f\"\\n\\nLEAF NODES: {len(leaves)}\\n\" + \"-\"*50 + \"\\n\"\n",
|
| 371 |
+
" for idx, leaf in enumerate(leaves):\n",
|
| 372 |
+
" stats_text += f\"\\nLeaf {idx+1}:\\n\"\n",
|
| 373 |
+
" stats_text += f\" • Samples: {leaf.samples}\\n\"\n",
|
| 374 |
+
" stats_text += f\" • Class 0: {leaf.class_counts.get(0, 0)} | \"\n",
|
| 375 |
+
" stats_text += f\"Class 1: {leaf.class_counts.get(1, 0)}\\n\"\n",
|
| 376 |
+
" stats_text += f\" • Prediction: Class {leaf.majority_class}\\n\"\n",
|
| 377 |
+
" stats_text += f\" • Entropy: {leaf.entropy:.4f}\\n\"\n",
|
| 378 |
+
" stats_text += f\" • Gini: {leaf.gini:.4f}\\n\"\n",
|
| 379 |
+
" \n",
|
| 380 |
+
" # Calculate weighted average impurity\n",
|
| 381 |
+
" total_samples = sum(leaf.samples for leaf in leaves)\n",
|
| 382 |
+
" avg_entropy = sum(leaf.entropy * leaf.samples for leaf in leaves) / total_samples\n",
|
| 383 |
+
" avg_gini = sum(leaf.gini * leaf.samples for leaf in leaves) / total_samples\n",
|
| 384 |
+
" \n",
|
| 385 |
+
" stats_text += f\"\\n\\nWEIGHTED AVERAGE IMPURITY:\\n\" + \"-\"*50 + \"\\n\"\n",
|
| 386 |
+
" stats_text += f\" • Entropy: {avg_entropy:.4f}\\n\"\n",
|
| 387 |
+
" stats_text += f\" • Gini: {avg_gini:.4f}\\n\"\n",
|
| 388 |
+
" stats_text += f\"\\nTOTAL INFORMATION GAIN:\\n\"\n",
|
| 389 |
+
" stats_text += f\" • {entropy_initial - avg_entropy:.4f}\\n\"\n",
|
| 390 |
+
" stats_text += f\"\\nTOTAL GINI REDUCTION:\\n\"\n",
|
| 391 |
+
" stats_text += f\" • {gini_initial - avg_gini:.4f}\\n\"\n",
|
| 392 |
+
" else:\n",
|
| 393 |
+
" stats_text += \"No splits applied yet.\\n\"\n",
|
| 394 |
+
" stats_text += \"\\nAdd splits in the format:\\n\"\n",
|
| 395 |
+
" stats_text += \" feature, threshold\\n\\n\"\n",
|
| 396 |
+
" stats_text += \"Example:\\n\"\n",
|
| 397 |
+
" stats_text += \" x, 5.0\\n\"\n",
|
| 398 |
+
" stats_text += \" y, 6.5\\n\"\n",
|
| 399 |
+
" \n",
|
| 400 |
+
" ax3.text(0.05, 0.95, stats_text, transform=ax3.transAxes,\n",
|
| 401 |
+
" fontsize=10, verticalalignment='top',\n",
|
| 402 |
+
" bbox=dict(boxstyle='round', facecolor='wheat', alpha=0.5),\n",
|
| 403 |
+
" family='monospace')\n",
|
| 404 |
+
" \n",
|
| 405 |
+
" plt.tight_layout()\n",
|
| 406 |
+
" \n",
|
| 407 |
+
" # Convert to image\n",
|
| 408 |
+
" buf = io.BytesIO()\n",
|
| 409 |
+
" plt.savefig(buf, format='png', dpi=120, bbox_inches='tight')\n",
|
| 410 |
+
" buf.seek(0)\n",
|
| 411 |
+
" img = Image.open(buf)\n",
|
| 412 |
+
" plt.close()\n",
|
| 413 |
+
" \n",
|
| 414 |
+
" return img\n",
|
| 415 |
+
" \n",
|
| 416 |
+
" def _collect_leaves(self, node, leaves):\n",
|
| 417 |
+
" \"\"\"Collect all leaf nodes\"\"\"\n",
|
| 418 |
+
" if node is None:\n",
|
| 419 |
+
" return\n",
|
| 420 |
+
" if node.is_leaf:\n",
|
| 421 |
+
" leaves.append(node)\n",
|
| 422 |
+
" else:\n",
|
| 423 |
+
" self._collect_leaves(node.left, leaves)\n",
|
| 424 |
+
" self._collect_leaves(node.right, leaves)\n",
|
| 425 |
+
"\n",
|
| 426 |
+
"# Create the partitioner\n",
|
| 427 |
+
"partitioner = DecisionTreePartitioner()\n",
|
| 428 |
+
"\n",
|
| 429 |
+
"# Create Gradio interface\n",
|
| 430 |
+
"with gr.Blocks(title=\"Multi-Split Decision Tree Visualizer\", theme=gr.themes.Soft()) as demo:\n",
|
| 431 |
+
" gr.Markdown(\"\"\"\n",
|
| 432 |
+
" # 🌳 Interactive Multi-Split Decision Tree Visualizer\n",
|
| 433 |
+
" \n",
|
| 434 |
+
" Build a decision tree step-by-step and visualize the partitioning process!\n",
|
| 435 |
+
" \n",
|
| 436 |
+
" \"\"\")\n",
|
| 437 |
+
" \n",
|
| 438 |
+
" with gr.Row():\n",
|
| 439 |
+
" with gr.Column(scale=1):\n",
|
| 440 |
+
" split_input = gr.Textbox(\n",
|
| 441 |
+
" label=\"📝 Split Sequence (one per line: feature, threshold)\",\n",
|
| 442 |
+
" placeholder=\"x, 5.0\\ny, 6.5\\nx, 3.0\",\n",
|
| 443 |
+
" lines=10,\n",
|
| 444 |
+
" value=\"x, 5.0\"\n",
|
| 445 |
+
" )\n",
|
| 446 |
+
" \n",
|
| 447 |
+
" update_btn = gr.Button(\"🔄 Update Visualization\", variant=\"primary\", size=\"lg\")\n",
|
| 448 |
+
" \n",
|
| 449 |
+
" gr.Markdown(\"\"\"\n",
|
| 450 |
+
" ### Example Splits:\n",
|
| 451 |
+
" **Simple 2-split tree:**\n",
|
| 452 |
+
" ```\n",
|
| 453 |
+
" x, 5.0\n",
|
| 454 |
+
" y, 6.5\n",
|
| 455 |
+
" ```\n",
|
| 456 |
+
" \n",
|
| 457 |
+
" **Complex 4-split tree:**\n",
|
| 458 |
+
" ```\n",
|
| 459 |
+
" x, 5.0\n",
|
| 460 |
+
" y, 6.5\n",
|
| 461 |
+
" x, 3.0\n",
|
| 462 |
+
" y, 8.0\n",
|
| 463 |
+
" ```\n",
|
| 464 |
+
" \"\"\")\n",
|
| 465 |
+
" \n",
|
| 466 |
+
" with gr.Column(scale=2):\n",
|
| 467 |
+
" output_image = gr.Image(label=\"Visualization\", height=800)\n",
|
| 468 |
+
" \n",
|
| 469 |
+
" # Update visualization\n",
|
| 470 |
+
" update_btn.click(\n",
|
| 471 |
+
" fn=partitioner.visualize,\n",
|
| 472 |
+
" inputs=[split_input],\n",
|
| 473 |
+
" outputs=output_image\n",
|
| 474 |
+
" )\n",
|
| 475 |
+
" \n",
|
| 476 |
+
" # Initial visualization\n",
|
| 477 |
+
" demo.load(\n",
|
| 478 |
+
" fn=partitioner.visualize,\n",
|
| 479 |
+
" inputs=[split_input],\n",
|
| 480 |
+
" outputs=output_image\n",
|
| 481 |
+
" )\n",
|
| 482 |
+
"\n",
|
| 483 |
+
"# Launch the app\n",
|
| 484 |
+
"demo.launch(share=True)"
|
| 485 |
+
]
|
| 486 |
+
}
|
| 487 |
+
],
|
| 488 |
+
"metadata": {
|
| 489 |
+
"kernelspec": {
|
| 490 |
+
"display_name": "WORK",
|
| 491 |
+
"language": "python",
|
| 492 |
+
"name": "python3"
|
| 493 |
+
},
|
| 494 |
+
"language_info": {
|
| 495 |
+
"codemirror_mode": {
|
| 496 |
+
"name": "ipython",
|
| 497 |
+
"version": 3
|
| 498 |
+
},
|
| 499 |
+
"file_extension": ".py",
|
| 500 |
+
"mimetype": "text/x-python",
|
| 501 |
+
"name": "python",
|
| 502 |
+
"nbconvert_exporter": "python",
|
| 503 |
+
"pygments_lexer": "ipython3",
|
| 504 |
+
"version": "3.10.18"
|
| 505 |
+
}
|
| 506 |
+
},
|
| 507 |
+
"nbformat": 4,
|
| 508 |
+
"nbformat_minor": 5
|
| 509 |
+
}
|
requirements.txt
ADDED
|
@@ -0,0 +1,4 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
gradio
|
| 2 |
+
numpy
|
| 3 |
+
matplotlib
|
| 4 |
+
pillow
|