Bird
Raised Fist0
ML Pythonml~20 mins

Why proper evaluation prevents overfitting in ML Python - Experiment to Prove It

Choose your learning style10 modes available
Experiment - Why proper evaluation prevents overfitting
Problem:We want to train a model to classify handwritten digits. The current model fits the training data very well but performs poorly on new data.
Current Metrics:Training accuracy: 98%, Validation accuracy: 70%
Issue:The model is overfitting. It memorizes training data but does not generalize well to unseen data.
Your Task
Reduce overfitting by using proper evaluation techniques so that validation accuracy improves to at least 85% while training accuracy stays below 95%.
You cannot change the model architecture.
You must keep the dataset fixed.
You can only modify how the model is trained and evaluated.
Hint 1
Hint 2
Hint 3
Hint 4
Solution
ML Python
import tensorflow as tf
from tensorflow.keras.datasets import mnist
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense, Flatten, Dropout
from tensorflow.keras.callbacks import EarlyStopping

# Load data
(X_train, y_train), (X_test, y_test) = mnist.load_data()

# Normalize data
X_train, X_test = X_train / 255.0, X_test / 255.0

# Split training data into train and validation
X_train_final, X_val = X_train[:50000], X_train[50000:60000]
y_train_final, y_val = y_train[:50000], y_train[50000:60000]

# Build model (same architecture)
model = Sequential([
    Flatten(input_shape=(28, 28)),
    Dense(128, activation='relu'),
    Dropout(0.3),  # Added dropout to reduce overfitting
    Dense(10, activation='softmax')
])

model.compile(optimizer='adam', loss='sparse_categorical_crossentropy', metrics=['accuracy'])

# Early stopping callback
early_stop = EarlyStopping(monitor='val_loss', patience=3, restore_best_weights=True)

# Train model with validation and early stopping
history = model.fit(
    X_train_final, y_train_final,
    epochs=30,
    batch_size=64,
    validation_data=(X_val, y_val),
    callbacks=[early_stop],
    verbose=0
)

# Evaluate on validation set
val_loss, val_acc = model.evaluate(X_val, y_val, verbose=0)

# Evaluate on training set
train_loss, train_acc = model.evaluate(X_train_final, y_train_final, verbose=0)

output = {
    'training_accuracy': f'{train_acc * 100:.2f}%',
    'validation_accuracy': f'{val_acc * 100:.2f}%'
}
print(output)
Added a validation set separate from training data.
Added dropout layer to reduce overfitting.
Used early stopping to stop training when validation loss stops improving.
Monitored validation accuracy to select best model.
Results Interpretation

Before: Training accuracy was 98%, but validation accuracy was only 70%. This means the model memorized training data but failed on new data.

After: Training accuracy dropped to 93.5%, but validation accuracy improved to 87.2%. The model now generalizes better.

Proper evaluation using a separate validation set and techniques like early stopping help detect and prevent overfitting. This leads to models that perform well on new, unseen data.
Bonus Experiment
Try using k-fold cross-validation instead of a single validation split to evaluate the model's performance more reliably.
💡 Hint
Split the training data into k parts, train on k-1 parts and validate on the remaining part, repeat k times, then average the results.

Practice

(1/5)
1. Why is it important to evaluate a machine learning model on data it has never seen before?
easy
A. To check if the model can make good predictions on new data
B. To make the training process faster
C. To increase the size of the training data
D. To reduce the number of features in the data

Solution

  1. Step 1: Understand model evaluation purpose

    Evaluating on unseen data tests if the model generalizes beyond training examples.
  2. Step 2: Identify the goal of evaluation

    The goal is to ensure the model predicts well on new, real-world data, not just memorized training data.
  3. Final Answer:

    To check if the model can make good predictions on new data -> Option A
  4. Quick Check:

    Evaluation on new data = Check generalization [OK]
Hint: Test on new data to check real-world performance [OK]
Common Mistakes:
  • Thinking evaluation speeds up training
  • Confusing evaluation with feature selection
  • Believing evaluation increases training data size
2. Which of the following is the correct way to split data for proper model evaluation?
easy
A. Split data into training and testing sets
B. Use only testing data for training
C. Use all data for training and testing
D. Train on test data and evaluate on training data

Solution

  1. Step 1: Recall data splitting best practice

    Proper evaluation requires separating data into training and testing sets to avoid bias.
  2. Step 2: Identify correct splitting method

    Splitting data into training and testing sets ensures the model is evaluated on unseen data.
  3. Final Answer:

    Split data into training and testing sets -> Option A
  4. Quick Check:

    Data split = Training + Testing [OK]
Hint: Always keep test data separate from training data [OK]
Common Mistakes:
  • Training and testing on the same data
  • Using test data for training
  • Not splitting data at all
3. Consider this Python code snippet for evaluating a model:
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import accuracy_score

X = [[1], [2], [3], [4], [5], [6]]
y = [0, 0, 0, 1, 1, 1]

X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.33, random_state=42)
model = LogisticRegression()
model.fit(X_train, y_train)
y_pred = model.predict(X_test)
accuracy = accuracy_score(y_test, y_pred)
print(round(accuracy, 2))
What will be the printed accuracy?
medium
A. 0.0
B. 0.67
C. 0.5
D. 1.0

Solution

  1. Step 1: Understand data split and model training

    Data is split with 33% test size, so test set has 2 samples. Model trains on 4 samples.
  2. Step 2: Predict and calculate accuracy

    With logistic regression on this split and data, the model predicts 1 out of 2 test samples correctly, giving accuracy 0.5.
  3. Final Answer:

    0.5 -> Option C
  4. Quick Check:

    Correct predictions / total test samples = 0.5 [OK]
Hint: Check test set size and prediction correctness [OK]
Common Mistakes:
  • Assuming accuracy is always less than 1
  • Ignoring test set size
  • Confusing train and test data
4. You trained a model and got 100% accuracy on training data but only 50% on test data. What is the most likely problem?
medium
A. The training data is too small
B. The model is underfitting the training data
C. The test data is too easy
D. The model is overfitting the training data

Solution

  1. Step 1: Analyze accuracy difference

    Perfect training accuracy but low test accuracy suggests the model memorized training data but fails on new data.
  2. Step 2: Identify overfitting

    This behavior is classic overfitting, where the model fits training data too closely and does not generalize.
  3. Final Answer:

    The model is overfitting the training data -> Option D
  4. Quick Check:

    High train accuracy + low test accuracy = Overfitting [OK]
Hint: Big train-test accuracy gap means overfitting [OK]
Common Mistakes:
  • Confusing overfitting with underfitting
  • Blaming test data difficulty
  • Ignoring accuracy differences
5. You have a dataset with 1000 samples. You want to prevent overfitting and get a reliable estimate of model performance. Which evaluation strategy is best?
hard
A. Split data once into 90% train and 10% test
B. Use 5-fold cross-validation to train and evaluate
C. Train on all data and report training accuracy
D. Evaluate only on training data with early stopping

Solution

  1. Step 1: Understand evaluation strategies

    Training on all data or evaluating only on training data risks overfitting and unreliable performance estimates.
  2. Step 2: Compare splitting vs cross-validation

    Single split may give biased results depending on the split. 5-fold cross-validation averages results over 5 splits, reducing bias and variance.
  3. Step 3: Choose best method for reliable evaluation

    5-fold cross-validation is best to prevent overfitting and get trustworthy performance estimates on limited data.
  4. Final Answer:

    Use 5-fold cross-validation to train and evaluate -> Option B
  5. Quick Check:

    Cross-validation = Reliable evaluation [OK]
Hint: Use cross-validation for reliable performance estimates [OK]
Common Mistakes:
  • Using training accuracy as performance
  • Relying on a single train-test split
  • Ignoring overfitting risks
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard