Cum să eviți overfitting în machine learning
DodaTech
Updated 2025-01-15
2 min read
In this tutorial, you'll learn how to detect and prevent overfitting in Machine Learning models using regularization, cross-validation, and other generalization techniques.
Problema
Modelul tău are acuratețe 99% pe datele de antrenare dar doar 70% pe date noi. Acesta este overfitting — modelul a memorat zgomotul din datele de train în loc să învețe pattern-urile generale.
Soluția Greșită
import pandas as pd
from sklearn.ensemble import RandomForestClassifier
from sklearn.model_selection import train_test_split
df = pd.read_csv("date.csv")
X = df.drop("target", axis=1)
y = df["target"]
# Model complex fara regularizare
model = RandomForestClassifier(n_estimators=500, max_depth=None)
model.fit(X, y)
print(f"Scor train: {model.score(X, y):.3f}")
Problema: Fără limitarea adâncimii sau a numărului de arbori, modelul memorează fiecare detaliu din train, inclusiv zgomotul.
Soluția Corectă
from sklearn.ensemble import RandomForestClassifier
from sklearn.model_selection import cross_val_score, train_test_split
import pandas as pd
import numpy as np
df = pd.read_csv("date.csv")
X = df.drop("target", axis=1)
y = df["target"]
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.2, random_state=42
)
# Model cu regularizare: adancime limitata
model = RandomForestClassifier(
n_estimators=100, max_depth=8, min_samples_leaf=5, random_state=42
)
model.fit(X_train, y_train)
train_score = model.score(X_train, y_train)
test_score = model.score(X_test, y_test)
print(f"Scor train: {train_score:.3f}")
print(f"Scor test: {test_score:.3f}")
Output:
Scor train: 0.912
Scor test: 0.905
Implementare Pas cu Pas
1. Folosește cross-validation pentru evaluare realistă
from sklearn.model_selection import cross_val_score
scores = cross_val_score(model, X_train, y_train, cv=5)
print(f"Cross-val: {scores}")
print(f"Medie: {scores.mean():.3f} (+/- {scores.std() * 2:.3f})")
2. Aplică regularizare L1 (Lasso) sau L2 (Ridge)
from sklearn.linear_model import LogisticRegression
from sklearn.preprocessing import StandardScaler
from sklearn.pipeline import make_pipeline
# Regularizare L2 puternica
model_l2 = make_pipeline(
StandardScaler(),
LogisticRegression(penalty="l2", C=0.1, max_iter=1000)
)
model_l2.fit(X_train, y_train)
print(f"Train (L2): {model_l2.score(X_train, y_train):.3f}")
print(f"Test (L2): {model_l2.score(X_test, y_test):.3f}")
3. Early stopping pentru Gradient Boosting
from sklearn.ensemble import GradientBoostingClassifier
gbr = GradientBoostingClassifier(
n_estimators=1000, validation_fraction=0.2,
n_iter_no_change=10, random_state=42
)
gbr.fit(X_train, y_train)
print(f"Arbori folositi: {gbr.n_estimators_}")
Sfaturi pentru Prevenire
- Cross-validation (k-fold, 5 sau 10) oferă o estimare realistă a performanței
- Setează
max_depthșimin_samples_leafpentru arbori - Folosește regularizare L1/L2 pentru modele liniare
- Early stopping oprește antrenarea când scorul de validare nu se mai îmbunătățește
- Colectează mai multe date — e cea mai sigură metodă anti-overfitting
Greșeli Comune
- Nu folosești cross-validation — evaluezi doar pe un singur split
- Model prea complex pentru volumul de date — cu 100 de exemple, nu folosi 500 de arbori
- Hiperparametrii nesetati — lasi valorile implicite care sunt deseori prea complexe
- Ignori diferența dintre scorul train și test — dacă e mare, e overfitting
- Aplici regularizare prea slabă — C mare = regularizare slabă
Întrebări Frecvente
Built by the developers of Doda Browser, DodaZIP, and Durga Antivirus Pro. DodaTech tools integrate seamlessly with sklearn for enhanced productivity and security.
← Previous
Cum să construiești un pipeline de machine learning
Next →
Cum să construiești un model de regresie
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro