import numpy as np
from collections import Counter
class Node:
"""
A class to represent a single node in the decision tree.
"""
def __init__(self, feature=None, threshold=None, left=None, right=None,*, value=None):
self.feature = feature # Index of the feature to split on
self.threshold = threshold # Threshold value for the split
self.left = left # Left child (Node)
self.right = right # Right child (Node)
self.value = value # Value if this is a leaf node (Class label)
def is_leaf_node(self):
return self.value is not None
class DecisionTree:
"""
The main Decision Tree Classifier class.
"""
def __init__(self, min_samples_split=2, max_depth=100, n_features=None):
self.min_samples_split = min_samples_split # Minimum samples required to split a node
self.max_depth = max_depth # Maximum depth of the tree
self.n_features = n_features # Number of features to consider for best split (useful for Random Forest)
self.root = None
def fit(self, X, y):
"""
Train the decision tree using the training data.
"""
# If n_features is not specified, use all features
self.n_features = X.shape[1] if not self.n_features else min(X.shape[1], self.n_features)
self.root = self._grow_tree(X, y)
def _grow_tree(self, X, y, depth=0):
"""
Recursive function to build the tree.
"""
n_samples, n_feats = X.shape
n_labels = len(np.unique(y))
# 1. Check the stopping criteria
if (depth >= self.max_depth or n_labels == 1 or n_samples < self.min_samples_split):
leaf_value = self._most_common_label(y)
return Node(value=leaf_value)
# 2. Find the best split
feat_idxs = np.random.choice(n_feats, self.n_features, replace=False)
best_feature, best_thresh = self._best_split(X, y, feat_idxs)
# 3. Create child nodes
left_idxs, right_idxs = self._split(X[:, best_feature], best_thresh)
# If a split results in an empty node, stop and create leaf
if len(left_idxs) == 0 or len(right_idxs) == 0:
leaf_value = self._most_common_label(y)
return Node(value=leaf_value)
left = self._grow_tree(X[left_idxs, :], y[left_idxs], depth+1)
right = self._grow_tree(X[right_idxs, :], y[right_idxs], depth+1)
return Node(best_feature, best_thresh, left, right)
def _best_split(self, X, y, feat_idxs):
"""
Finds the best feature and threshold to split on based on Information Gain (Gini).
"""
best_gain = -1
split_idx, split_threshold = None, None
for feat_idx in feat_idxs:
X_column = X[:, feat_idx]
thresholds = np.unique(X_column)
for thr in thresholds:
# Calculate Information Gain (or reduction in Gini)
gain = self._information_gain(y, X_column, thr)
if gain > best_gain:
best_gain = gain
split_idx = feat_idx
split_threshold = thr
return split_idx, split_threshold
def _information_gain(self, y, X_column, threshold):
"""
Calculates the Information Gain using Gini Impurity.
IG = Parent_Gini - (Weighted_Avg_Children_Gini)
"""
# Parent impurity
parent_gini = self._gini_impurity(y)
# Create children
left_idxs, right_idxs = self._split(X_column, threshold)
if len(left_idxs) == 0 or len(right_idxs) == 0:
return 0
# Calculate weighted avg. impurity of children
n = len(y)
n_l, n_r = len(left_idxs), len(right_idxs)
g_l, g_r = self._gini_impurity(y[left_idxs]), self._gini_impurity(y[right_idxs)
child_gini = (n_l / n) * g_l + (n_r / n) * g_r
# Calculate information gain
information_gain = parent_gini - child_gini
return information_gain
def _gini_impurity(self, y):
"""
Calculates Gini Impurity: 1 - sum(p_i^2)
"""
hist = np.bincount(y)
ps = hist / len(y)
return 1.0 - np.sum(ps ** 2)
def _split(self, X_column, split_thresh):
"""
Splits the data indices based on a threshold.
"""
left_idxs = np.argwhere(X_column <= split_thresh).flatten()
right_idxs = np.argwhere(X_column > split_thresh).flatten()
return left_idxs, right_idxs
def _most_common_label(self, y):
"""
Returns the most common label in a list (for leaf nodes).
"""
counter = Counter(y)
return counter.most_common(1)[0][0]
def predict(self, X):
"""
Predict class for X.
"""
return np.array([self._traverse_tree(x, self.root) for x in X])
def _traverse_tree(self, x, node):
"""
Recursively traverse the tree to find the prediction for a single sample.
"""
if node.is_leaf_node():
return node.value
if x[node.feature] <= node.threshold:
return self._traverse_tree(x, node.left)
return self._traverse_tree(x, node.right)