Skip to content

Commit 77c0aad

Browse files
Add Decision Tree Classifier with overfitting controls
This script implements a Decision Tree Classifier with controls to reduce overfitting on the Iris dataset. It includes model training, predictions, and accuracy evaluation.
1 parent a051ab5 commit 77c0aad

File tree

1 file changed

+31
-0
lines changed

1 file changed

+31
-0
lines changed

reduce overfit.py

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
from sklearn.datasets import load_iris
2+
from sklearn.model_selection import train_test_split
3+
from sklearn.tree import DecisionTreeClassifier
4+
from sklearn.metrics import accuracy_score
5+
6+
# Load dataset
7+
data = load_iris()
8+
X, y = data.data, data.target
9+
10+
# Train-test split
11+
X_train, X_test, y_train, y_test = train_test_split(
12+
X, y, test_size=0.3, random_state=42)
13+
14+
# Decision Tree with Overfitting Controls
15+
model = DecisionTreeClassifier(
16+
max_depth=3, # limit depth of tree
17+
min_samples_split=4, # minimum samples to split a node
18+
min_samples_leaf=2, # minimum samples in each leaf
19+
ccp_alpha=0.01, # pruning parameter (cost-complexity pruning)
20+
random_state=42
21+
)
22+
23+
model.fit(X_train, y_train)
24+
25+
# Predictions
26+
y_pred = model.predict(X_test)
27+
28+
# Accuracy
29+
print("Accuracy:", accuracy_score(y_test, y_pred))
30+
print("Depth of Tree:", model.get_depth())
31+
print("Number of Leaves:", model.get_n_leaves())

0 commit comments

Comments
 (0)