Overfitting y Regularización — Pre-pruning vs Post-pruning
Controlar profundidad y poda del árbol
Árboles sin regularización crecen indefinidamente, ajustándose perfectamente al ruido. Train accuracy = 1.0, test accuracy = 0.6 (overfitting clásico). Para prevenir, hay dos estrategias: (1) Pre-pruning (regularización durante crecimiento): limita max_depth, min_samples_split, min_samples_leaf. El árbol crece controladamente. (2) Post-pruning (poda después del crecimiento): crecimiento dejar crecer completamente, luego poda branches que no mejoran val score. sklearn implementa cost_complexity_pruning.
max_depth=5, min_samples_leaf=5 es regularización fuerte. max_depth=None (sin límite), min_samples_leaf=1 es sin regularización. El sweet spot depende del dataset: datasets grandes toleran árboles más profundos, datasets pequeños necesitan regularización fuerte.
Cost complexity pruning (α-pruning): define parámetro α que controla trade-off entre tamaño del árbol y accuracy. α=0 es árbol sin poda (overfitting). α grande poda agresivamente (underfitting). Encuentra α óptimo con CV sobre val set.
# Pre-pruning: regularización durante crecimiento
tree = DecisionTreeClassifier(
max_depth=5,
min_samples_split=10,
min_samples_leaf=5,
random_state=42
)
tree.fit(X_train, y_train)
# Post-pruning: poda después del crecimiento
path = tree.cost_complexity_pruning_path(X_train, y_train)
ccp_alphas = path.ccp_alphas
trees = []
for ccp_alpha in ccp_alphas:
t = DecisionTreeClassifier(random_state=42, ccp_alpha=ccp_alpha)
t.fit(X_train, y_train)
trees.append(t)
# Encontrar α óptimo con val set
scores = [t.score(X_val, y_val) for t in trees]
best_tree = trees[np.argmax(scores)]Debugging lab
Detecta y corrige el error en el código.
- 01
tree = DecisionTreeClassifier() tree.fit(X_train, y_train) print(f'Train: {tree.score(X_train, y_train):.3f}') # 1.0 print(f'Test: {tree.score(X_test, y_test):.3f}') # 0.6 — overfitting