Ravindra BagaleCourses & study guides मराठी Track your progress

35. Decision Trees and Random Forests in Python

35.3 Copy-Run a Small Decision Tree

Why. Fit a small tree so you see fit / predict and optional text rules.

What. DecisionTreeClassifier with max_depth keeps the tree short for beginners.

How.

Copy-run a shallow tree

  1. Reuse a tiny churn-style table.
  2. Fit with max_depth=3.
  3. Predict on test rows.
  4. Optional: export_text to print rules.
import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.tree import DecisionTreeClassifier, export_text

df = pd.DataFrame({
 "orders_last_30d": [2, 8, 1, 12, 3, 9, 0, 11, 4, 7, 1, 10],
 "complaints": [1, 0, 2, 0, 1, 0, 3, 0, 1, 0, 2, 0],
 "churned": [1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0],
})
X = df[["orders_last_30d", "complaints"]]
y = df["churned"]
X_train, X_test, y_train, y_test = train_test_split(
 X, y, test_size=0.33, random_state=0, stratify=y
)

tree = DecisionTreeClassifier(max_depth=3, random_state=0)
tree.fit(X_train, y_train)
print("preds:", tree.predict(X_test))
print(export_text(tree, feature_names=list(X.columns)))

What you should see. Predictions plus a short indented rule list. Depth 3 stays readable.