AWS Builder Center

Machine Learning from Scratch – Day 5: Understanding Overfitting and Underfitting

Understanding Overfitting and Underfitting

Series: Machine Learning From Scratch (18 articles)

  1. …
  2. 5
    Machine Learning from Scratch – Day 5: Understanding Overfitting and Underfitting This article

Introduction

In our previous article, we learned about Training, Validation, and Testing datasets and why dividing data is important when building Machine Learning models.
But here's an interesting question:
What happens when a Machine Learning model learns too much or too little from the training data?
A model might perform exceptionally well during training but fail when given new data. Another model might struggle even with the data it was trained on.
These problems are known as Overfitting and Underfitting.
Let's understand them with simple examples.

1. What is Overfitting?

Overfitting occurs when a Machine Learning model learns the training data too closely, including noise and unnecessary patterns.
Instead of learning general relationships, the model starts memorizing the training examples.
Example: Student Examination
Imagine a student preparing for an examination by memorizing answers to a particular set of questions.
When the exact same questions appear, the student performs exceptionally well.
However, when slightly different questions are asked, the student struggles.
A Machine Learning model can behave in a similar way.
Common signs of Overfitting:
  • Very high training accuracy.
  • Poor performance on unseen data.
  • Model becomes unnecessarily complex.
  • Learns noise instead of meaningful patterns.
How to prevent Overfitting:
  • Collect more training data.
  • Apply Regularization.
  • Use Cross-Validation.
  • Reduce unnecessary model complexity.
  • Use techniques like Dropout in neural networks.
  • Apply Early Stopping.

2. What is Underfitting?

Underfitting happens when a Machine Learning model is too simple to understand the patterns present in the training data.
The model fails to learn the important relationships between input features and outputs.
Example: Student Examination
Imagine a student who studies only one chapter for an examination that covers ten chapters.
Even questions from the studied chapter might be difficult, and the student performs poorly overall.
Similarly, an underfitted model cannot capture the complexity of the dataset.
Common signs of Underfitting:
  • Poor training performance.
  • Poor testing performance.
  • Model is too simple.
  • Important patterns remain unidentified.
How to prevent Underfitting:
  • Use a more suitable algorithm.
  • Increase model complexity.
  • Add useful features.
  • Reduce excessive regularization.
  • Train the model appropriately.

3. What is a Good Fit?

A good-fit model finds the right balance between learning important patterns and avoiding unnecessary complexity.
It should:
  • Perform well on training data.
  • Generalize to unseen data.
  • Capture meaningful relationships.
  • Avoid memorizing noise.
The main objective of Machine Learning is not simply to achieve high training accuracy. It is to build a model that performs well on new data.

4. Understanding the Difference

Feature
Underfitting
Good Fit
Overfitting
Model complexity
Too low
Appropriate
Often too high
Training error
High
Low
Very low
Testing error
High
Low
Often high
Learning
Too little
Balanced
Memorizes data
Generalization
Poor
Good
Poor

5. Understanding the Bias-Variance Tradeoff

Two important concepts help explain why overfitting and underfitting happen.
Bias
Bias refers to errors caused by overly simple assumptions made by a model.
  • High bias often leads to underfitting.
  • The model cannot capture important patterns.
Variance
Variance refers to how sensitive a model is to changes in its training data.
  • High variance often leads to overfitting.
  • The model learns patterns that may not generalize.
The Bias-Variance Tradeoff is about finding a suitable balance between these two sources of error.
Our goal is to build a model with enough complexity to learn useful patterns without becoming overly sensitive to the training data.

6. Practical Python Example

Let's see how model complexity can affect predictions using Python.
We will use Polynomial Regression to understand the concept.
import numpy as npimport matplotlib.pyplot as pltfrom sklearn.preprocessing import PolynomialFeaturesfrom sklearn.linear_model import LinearRegressionfrom sklearn.pipeline import make_pipeline# Generate sample datanp.random.seed(42)X = np.linspace(-3, 3, 30).reshape(-1, 1)y = X**2 + np.random.normal(0, 2, (30, 1))# Create test pointsX_test = np.linspace(-3, 3, 100).reshape(-1, 1)# Compare different model complexitiesfor degree in [1, 2, 15]: model = make_pipeline( PolynomialFeatures(degree), LinearRegression() ) model.fit(X, y) predictions = model.predict(X_test) plt.plot( X_test, predictions, label=f"Degree {degree}" )plt.scatter(X, y, label="Training Data")plt.xlabel("X")
What should you observe?
  • Degree 1: May underfit the curved relationship.
  • Degree 2: Can capture the underlying quadratic pattern.
  • Degree 15: May overfit the training observations.
This experiment demonstrates why selecting an appropriate model complexity is important.
Note: The example is illustrative. Actual model performance should be verified using separate validation and testing data.

7. Real-World Applications

Understanding overfitting and underfitting is important in many applications.
  • Healthcare: A diagnostic model should work reliably on new patient data, not just training records.
  • Fraud Detection: A model should identify new fraudulent transaction patterns.
  • Recommendation Systems: A recommendation engine should adapt to user preferences rather than simply memorizing previous purchases.
  • Image Recognition: An image classifier should recognize objects in different environments and lighting conditions.

Conclusion

Overfitting and Underfitting are two common challenges in Machine Learning.
Remember:
  • Underfitting: The model learns too little.
  • Overfitting: The model memorizes too much.
  • Good Fit: The model learns meaningful patterns and generalizes well.
As Machine Learning engineers, our goal is not to build the most complicated model but to build the model that performs reliably on unseen data.
Understanding this balance is an important step toward developing better Machine Learning applications.
Coming Next – Day 6: Understanding Linear Regression – Your First Machine Learning Algorithm.
We'll explore how computers learn relationships between variables and use them to predict numerical values, with a practical Python implementation.

Series: Machine Learning From Scratch (18 articles)

  1. …
  2. 5
    Machine Learning from Scratch – Day 5: Understanding Overfitting and Underfitting This article
Any opinions in this article are those of the individual author and may not reflect the opinions of AWS.
Enjoyed reading this content? Let the author know!

Your likes, comments, shares, and saves help creators reach more builders.

Loading recommendations

Loading article