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.

Hızlı teşhis: Eğitim ve doğrulama performansını birlikte değerlendirin. Tek başına yüksek eğitim skoru, modelin yeni veride iyi çalışacağını göstermez.

Overfitting ve underfitting farkı

DurumEğitim performansıDoğrulama/test performansıTipik yorum
Underfitting (yetersiz öğrenme)ZayıfZayıfModel temel örüntüyü yakalayamıyor veya özellik/veri yetersiz.
Dengeli genellemeİyiBenzer ve yeterince iyiÖğrenilen örüntü yeni gözlemlere taşınıyor.
Overfitting (aşırı öğrenme)Çok iyiBelirgin biçimde daha zayıfModel 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ı.
Ön işlemeyi unutmayın: Ölçekleme, eksik değer doldurma ve özellik seçimi gibi adımlar da veriden bilgi öğrenebilir. Bunları bölme öncesi tüm veriye uygulamak değerlendirme skorunu olduğundan iyi gösterebilir.

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

1 · Böl

Eğitim verisini K parçaya ayır.

2

2 · Öğren

K−1 parçayla modeli eğit.

3

3 · Doğrula

Boşta kalan parçadaki skoru kaydet.

4

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öntemCezaÖ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 NetL1 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.

Pratik karar: Overfitting varsa daha güçlü regularization, daha sığ/daha basit model, daha fazla veri veya gürültü/özellik denetimi deneyin. Underfitting varsa daha esnek model, daha anlamlı özellik veya daha düşük regularization değerlendirin. Her adımı çapraz doğrulamayla karşılaştırın.

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.

A quick diagnosis: read training and validation performance together. A high training score on its own tells you nothing about how the model will behave on new data.

The difference between overfitting and underfitting

SituationTraining performanceValidation/test performanceTypical reading
UnderfittingWeakWeakThe model cannot capture the underlying pattern, or the features/data are insufficient.
Balanced generalisationGoodSimilar and good enoughThe learned pattern carries over to new observations.
OverfittingVery goodClearly weakerThe 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.
Don't forget preprocessing: steps like scaling, imputing missing values and feature selection also learn from the data. Applying them to the whole data set before splitting makes your evaluation score look better than it is.

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

1 · Split

Divide the training data into K parts.

2

2 · Train

Fit the model on K−1 parts.

3

3 · Validate

Record the score on the held-out part.

4

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.

MethodPenaltyCharacteristic
Ridge (L2)Sum of squared coefficientsShrinks coefficients; rarely drives them to zero.
Lasso (L1)Sum of absolute coefficientsCan zero out some coefficients, performing feature selection.
Elastic NetA combination of L1 and L2Balances 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 practical rule: if you are overfitting, try stronger regularization, a shallower or simpler model, more data, or a check on noise and features. If you are underfitting, consider a more flexible model, more meaningful features or less regularization. Compare every step with cross-validation.

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.

Resources