Overfitting ve Underfitting Nedir?
Bir makine öğrenmesi modeli eğitim verisini ezberleyip yeni örneklerde başarısız olabilir ya da verideki temel örüntüyü bile öğrenemeyecek kadar basit kalabilir. Aşırı öğrenme ve yetersiz öğrenmenin belirtilerini; Cross Validation ve Regularization ile nasıl denge kurabileceğinizi örneklerle öğrenin.
- Makine Öğrenmesi
- İstatistik

Model neden yeni veride zorlanır?
Makine öğrenmesindeki hedef yalnızca eğitim kayıtlarında iyi sonuç almak değildir. Modelin, eğitim sırasında görmediği ama gerçek kullanım koşullarını temsil eden örneklerde de işe yarar tahmin üretmesi beklenir. Bu beceriye genelleme denir.
Model karmaşıklığı, veri miktarı/kalitesi, gürültü, özellik seçimi ve eğitim süreci bu dengeyi etkiler. Underfitting genellikle modelin esnekliğinin yetersiz; overfitting ise öğrenilen ayrıntıların örnekleme özgü ve gürültülü olmasının işaretidir.
Overfitting ve underfitting farkı
| Durum | Eğitim performansı | Doğrulama/test performansı | Tipik yorum |
|---|---|---|---|
| Underfitting (yetersiz öğrenme) | Zayıf | Zayıf | Model temel örüntüyü yakalayamıyor veya özellik/veri yetersiz. |
| Dengeli genelleme | İyi | Benzer ve yeterince iyi | Öğrenilen örüntü yeni gözlemlere taşınıyor. |
| Overfitting (aşırı öğrenme) | Çok iyi | Belirgin biçimde daha zayıf | Model eğitim verisine/gürültüsüne fazla uyum sağlamış olabilir. |
Performans ölçütünün yönüne dikkat edin: accuracy gibi ölçülerde yüksek iyi, hata ölçülerinde (MAE/RMSE) düşük iyidir. Eğitim-doğrulama farkını, mutlak performansla ve hedef kullanımın hata maliyetiyle beraber yorumlayın.
Bu problemlerin başlıca nedenleri
Underfitting’e yol açabilen durumlar
- İlişki karmaşıklığına göre fazla basit model seçmek.
- Önemli özellikleri dışarıda bırakmak veya yanlış dönüşüm yapmak.
- Aşırı güçlü regularization ile modeli fazla kısıtlamak.
- Eğitim sürecini yetersiz yürütmek veya veride kullanılabilir sinyalin az olması.
Overfitting’e yol açabilen durumlar
- Az sayıda gözleme kıyasla çok esnek/karmaşık model kullanmak.
- Gürültüye duyarlı özellikler, veri hataları veya hedef sızıntısı.
- Çok sayıda model/ayar deneyip doğrulama kümesine göre tekrar tekrar seçim yapmak.
- Train ve gerçek kullanım verisi arasında dağılım farkı olması.
Cross Validation ile daha güvenilir değerlendirme
Tek bir train/test bölmesi şansa bağlı olarak kolay veya zor bir test kümesi üretebilir. K-fold Cross Validation eğitim verisini k parçaya ayırır; her turda bir parça doğrulama, kalanlar eğitim için kullanılır. Skorların ortalaması ve yayılımı model performansının bölmelere ne kadar duyarlı olduğu hakkında fikir verir.
1 · Böl
Eğitim verisini K parçaya ayır.
2 · Öğren
K−1 parçayla modeli eğit.
3 · Doğrula
Boşta kalan parçadaki skoru kaydet.
4 · Tekrarla
Her parça doğrulama olacak şekilde döngüyü tamamla.
from sklearn.model_selection import cross_validate, KFold
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
from sklearn.linear_model import Ridge
cv = KFold(n_splits=5, shuffle=True, random_state=42)
model = make_pipeline(StandardScaler(), Ridge(alpha=1.0))
scores = cross_validate(
model, X, y, cv=cv,
scoring="neg_root_mean_squared_error",
return_train_score=True
)
# sklearn hata ölçülerini maximize edilecek skor biçiminde negatif döndürür.
train_rmse = -scores["train_score"].mean()
valid_rmse = -scores["test_score"].mean()
print(f"Train RMSE: {train_rmse:.2f}; CV RMSE: {valid_rmse:.2f}")
Pipeline sayesinde StandardScaler her doğrulama turunda yalnızca o turun eğitim katında öğrenilir. Test kümesini model/ayar seçmek için tekrar tekrar kullanmayın; nihai test yalnızca seçimler tamamlandıktan sonra kullanılmalıdır.
Veri zaman sıralıysa rastgele KFold gelecekteki kayıtları eğitime koyup geçmişi doğrulama yapabilir. Böyle durumlarda zaman sırasını koruyan TimeSeriesSplit veya gerçek kullanım akışını taklit eden bir bölme stratejisi seçin. Aynı kullanıcıya ait kayıtlar farklı katlara dağılmamalıysa grup bazlı ayırma kullanın.
Regularization: model karmaşıklığını sınırlama
Regularization, modelin hata fonksiyonuna parametre büyüklüğünü cezalandıran bir terim ekler. Bu, model katsayılarının aşırı büyümesini sınırlayarak varyansı düşürmeye ve genellemeyi iyileştirmeye yardımcı olabilir. Ceza aşırı yüksek seçilirse bu kez model fazla basitleşebilir ve underfitting oluşabilir.
| Yöntem | Ceza | Öne çıkan özellik |
|---|---|---|
| Ridge (L2) | Katsayı kareleri toplamı | Katsayıları küçültür; çoğunlukla sıfır yapmaz. |
| Lasso (L1) | Katsayıların mutlak değerleri toplamı | Bazı katsayıları sıfıra indirerek özellik seçimi yapabilir. |
| Elastic Net | L1 ve L2 birleşimi | İki ceza türünün dengesini kurar. |
Ölçekleri farklı sayısal özelliklerde regularization öncesi ölçekleme gerekebilir. Ölçekleme parametrelerini de yalnızca eğitim katında öğrenmek için pipeline içinde tutun.
Alpha değerini çapraz doğrulamayla seçme
from sklearn.model_selection import GridSearchCV
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
from sklearn.linear_model import Ridge
pipe = make_pipeline(StandardScaler(), Ridge())
param_grid = {"ridge__alpha": [0.01, 0.1, 1, 10, 100]}
search = GridSearchCV(
pipe, param_grid, cv=5,
scoring="neg_root_mean_squared_error"
)
search.fit(X_train, y_train)
print("En iyi parametreler:", search.best_params_)
print("CV RMSE:", -search.best_score_)
print("Test RMSE:", -search.score(X_test, y_test))
Örnek varsayımı: X_train/X_test ayrımı daha önce yapılmış ve test kümesi son değerlendirme için dokunulmadan bekletiliyor. Parametre ızgarası da araştırma alanı bilgisine göre belirlenmelidir.
Başka hangi çözümler denenebilir?
- Daha fazla ve daha temsil edici veri: Özellikle karmaşık örüntüler için genellemeyi iyileştirebilir.
- Özellik mühendisliği: Sorun alanındaki anlamlı sinyalleri modele uygun biçimde temsil edin; test verisinden bilgi taşımayın.
- Model karmaşıklığını ayarlama: Ağaç derinliği, yaprak başına örnek sayısı veya polinom derecesini doğrulamayla seçin.
- Özellik/parametre sayısını azaltma: Alan bilgisi ve yalnızca eğitim verisinde öğrenilen seçim yöntemleriyle gürültüyü sınırlayın.
- Erken durdurma: İteratif modellerde doğrulama skoru kötüleşmeye başladığında eğitimi durdurun.
- Ensemble ve bagging: Bazı yüksek varyanslı modellerde tahminleri birleştirmek kararlılığı artırabilir.
- Hedef metriği gözden geçirme: Yanlış alarm ve kaçırmanın iş maliyetine uygun ölçü seçin.
Bir çözümü uygulamadan önce hata örneklerini inceleyin. Sorun yanlış etiket, üretim verisinin kayması veya temsil edilmeyen grup olabilir; yalnızca modeli düzenlileştirmek bu veri sorunlarını düzeltmez.
Öğrenme eğrisi ve teşhis
Öğrenme eğrisi eğitim örneği sayısı arttıkça eğitim ve doğrulama performansının nasıl değiştiğini gösterir. Eğitim skoru çok iyi, doğrulama belirgin kötü ise aşırı uyum olasıdır; iki skor da zayıf ve birbirine yakınsa model/özellikler yetersiz olabilir. Ölçütlerin yönünü grafikte açıkça belirtin.
scikit-learn içindeki learning_curve ve validation_curve araçları farklı eğitim örneği sayısı veya hiperparametre değerlerinde skorları incelemeye yardımcı olur. Sonuçları tek grafikle kesin tanı gibi görmeyin: veri miktarı, katlama varyansı ve iş metriği de önemlidir.
Model seçimi için kontrol listesi
- ☐ Eğitim ve doğrulama performansını birlikte inceliyorum.
- ☐ Bölme yöntemi verinin zaman, grup ve sınıf yapısına uygun.
- ☐ Ön işleme yalnızca eğitim katında öğreniliyor; pipeline kullanıyorum.
- ☐ Hiperparametreleri çapraz doğrulamayla seçiyorum.
- ☐ Test kümesini seçim sürecinden ayrı tutuyorum.
- ☐ Seçtiğim metriğin iş kararındaki hata maliyetini yansıttığını kontrol ettim.
- ☐ Sonuçları basit bir baseline ve hata örnekleriyle kıyasladım.
- ☐ Üretim verisinin eğitim verisinden farklılaşabileceğini izleme planına ekledim.
Sonuç
Overfitting, modelin eğitim verisine fazla uyup yeni örneklerde zorlanması; underfitting ise örüntüyü yakalayamayacak kadar basit kalmasıdır. Çapraz doğrulama performansı daha kararlı değerlendirmeye ve model ayarı seçmeye yardım eder. Regularization parametre büyüklüklerini sınırlayarak aşırı karmaşıklığı azaltabilir; ancak seviyesi gereğinden yüksek olursa yetersiz öğrenmeye yol açabilir. En iyi karar, veriye uygun bölme, doğru metrik ve ayrılmış test kümesiyle yapılan ölçüme dayanır.
Kaynaklar
Why does a model struggle on new data?
The goal in machine learning is not simply to score well on the training records. A model is expected to produce useful predictions on examples it never saw during training but which represent real conditions of use. That ability is called generalisation.
Model complexity, the amount and quality of data, noise, feature selection and the training process all shape that balance. Underfitting usually means the model is not flexible enough; overfitting means the detail it has learned is specific to the sample and to its noise.
The difference between overfitting and underfitting
| Situation | Training performance | Validation/test performance | Typical reading |
|---|---|---|---|
| Underfitting | Weak | Weak | The model cannot capture the underlying pattern, or the features/data are insufficient. |
| Balanced generalisation | Good | Similar and good enough | The learned pattern carries over to new observations. |
| Overfitting | Very good | Clearly weaker | The model has probably fitted the training data and its noise too closely. |
Watch the direction of your metric: for measures like accuracy, higher is better; for error measures such as MAE and RMSE, lower is better. Read the training-validation gap alongside the absolute performance and the cost of errors in your intended use.
The main causes of these problems
What can lead to underfitting
- Choosing a model too simple for the complexity of the relationship.
- Leaving out important features or transforming them badly.
- Constraining the model too hard with overly strong regularization.
- Running the training process inadequately, or having little usable signal in the data.
What can lead to overfitting
- Using a very flexible, complex model relative to the number of observations.
- Noise-sensitive features, errors in the data, or target leakage.
- Trying many models and settings and repeatedly selecting against the validation set.
- A distribution gap between the training data and the data seen in real use.
More reliable evaluation with cross-validation
A single train/test split can, by luck, produce an easy or a hard test set. K-fold cross-validation splits the training data into k parts; in each round one part serves as validation and the rest for training. The mean and the spread of those scores tell you how sensitive the model's performance is to the split.
1 · Split
Divide the training data into K parts.
2 · Train
Fit the model on K−1 parts.
3 · Validate
Record the score on the held-out part.
4 · Repeat
Complete the loop so every part serves as validation once.
from sklearn.model_selection import cross_validate, KFold
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
from sklearn.linear_model import Ridge
cv = KFold(n_splits=5, shuffle=True, random_state=42)
model = make_pipeline(StandardScaler(), Ridge(alpha=1.0))
scores = cross_validate(
model, X, y, cv=cv,
scoring="neg_root_mean_squared_error",
return_train_score=True
)
# sklearn returns error measures negated, as scores to be maximised.
train_rmse = -scores["train_score"].mean()
valid_rmse = -scores["test_score"].mean()
print(f"Train RMSE: {train_rmse:.2f}; CV RMSE: {valid_rmse:.2f}")
Thanks to Pipeline, StandardScaler is learned only on that round's training fold. Do not use the test set over and over to pick models or settings; the final test belongs at the end, once the choices are made.
If the data is time-ordered, a random KFold will put future records into training and validate on the past. In that case use TimeSeriesSplit, which preserves ordering, or a splitting strategy that mimics real usage. Where records from the same user must not be spread across folds, use group-based splitting.
Regularization: limiting model complexity
Regularization adds a term to the model's loss function that penalises the size of the parameters. By stopping coefficients from growing too large it can lower variance and improve generalisation. Choose the penalty too high, though, and the model becomes too simple and underfits.
| Method | Penalty | Characteristic |
|---|---|---|
| Ridge (L2) | Sum of squared coefficients | Shrinks coefficients; rarely drives them to zero. |
| Lasso (L1) | Sum of absolute coefficients | Can zero out some coefficients, performing feature selection. |
| Elastic Net | A combination of L1 and L2 | Balances the two kinds of penalty. |
Numeric features on different scales usually need scaling before regularization. Keep the scaling parameters inside the pipeline so they too are learned on the training fold only.
Choosing alpha by cross-validation
from sklearn.model_selection import GridSearchCV
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
from sklearn.linear_model import Ridge
pipe = make_pipeline(StandardScaler(), Ridge())
param_grid = {"ridge__alpha": [0.01, 0.1, 1, 10, 100]}
search = GridSearchCV(
pipe, param_grid, cv=5,
scoring="neg_root_mean_squared_error"
)
search.fit(X_train, y_train)
print("Best parameters:", search.best_params_)
print("CV RMSE:", -search.best_score_)
print("Test RMSE:", -search.score(X_test, y_test))
The example assumes the X_train/X_test split was made earlier and the test set is being kept untouched for the final evaluation. The parameter grid should also reflect what you know about the problem.
What else can you try?
- More, and more representative, data: this can improve generalisation, especially for complex patterns.
- Feature engineering: represent the meaningful signals in your domain in a form the model can use, without carrying information in from the test set.
- Tuning model complexity: choose tree depth, minimum samples per leaf or polynomial degree by validation.
- Reducing the number of features or parameters: limit noise with domain knowledge and selection methods learned on the training data only.
- Early stopping: in iterative models, stop training when the validation score starts to get worse.
- Ensembles and bagging: combining predictions can add stability for some high-variance models.
- Revisiting the target metric: pick a measure that matches the business cost of false alarms and misses.
Before applying a fix, read the error cases. The problem may be mislabelled data, drift in the production data or a group that is not represented at all; regularizing the model does nothing for those.
Learning curves and diagnosis
A learning curve shows how training and validation performance change as the number of training examples grows. A very good training score with clearly worse validation suggests overfitting; two weak scores close together suggest the model or the features are not enough. State the direction of your metric clearly on the chart.
scikit-learn's learning_curve and validation_curve help you inspect scores across different training sizes or hyperparameter values. Do not treat a single chart as a definitive diagnosis: data volume, fold variance and the business metric all matter too.
A checklist for model selection
- ☐ I am looking at training and validation performance together.
- ☐ The splitting method matches the time, group and class structure of the data.
- ☐ Preprocessing is learned on the training fold only; I am using a pipeline.
- ☐ I choose hyperparameters by cross-validation.
- ☐ I keep the test set out of the selection process.
- ☐ I have checked that my metric reflects the cost of errors in the business decision.
- ☐ I compared the results with a simple baseline and with error cases.
- ☐ My monitoring plan allows for production data drifting away from the training data.
Conclusion
Overfitting is a model fitting the training data so closely that it struggles on new examples; underfitting is a model too simple to capture the pattern at all. Cross-validation gives you a steadier evaluation and helps you choose model settings. Regularization can reduce excess complexity by limiting parameter sizes, but set too high it causes underfitting instead. The best decision rests on measurement: a split suited to the data, the right metric, and a test set you set aside.