🚧 Under construction — VoTechWorks is being built. A free tech program — complimentary, as our commitment to get America working.
voTechWorksGrade 13 · a vocational technology learning center, by urbanicity
newSchoolWorks.com › VoTechWorks › Technology & Design › Data Science & Analytics › Introduction to Machine Learning for Data Analytics › Lesson 7
TEC-DATA85-08 · Lesson 7 · 12 clock hours · practice

Common ML Failure Modes: Overfitting, Leakage, and Class Imbalance

Objective. Students will diagnose overfitting, data leakage, and class imbalance in provided flawed notebooks and apply remediation techniques including regularization, SMOTE/class weights, and pipeline restructuring.

⚠ Pending professional review

This lesson, its worked examples and its practice questions has not yet been verified by an industry-certified professional or by a certification or approval body. It is a study draft and may contain errors. Do not use it as instructions for work on a job site or on live equipment. Always follow your instructor, your supervising professional, and current official references and regulations.

VoTechWorks program approval and accreditation are still in progress. Credentials are issued only by the certifying bodies named in each program, after their own exams.

Common ML Failure Modes: Overfitting, Leakage, and Class Imbalance

Building a machine learning model is only half the job. The other half is making sure the model actually works on data it has never seen. Three failure modes destroy more deployed models than almost any other cause: overfitting, data leakage, and class imbalance. Understanding each one—and knowing how to fix it—is a core competency tested by CompTIA Data+, the Google Data Analytics Certificate, and the IBM Data Science Professional Certificate.

Overfitting

A model overfits when it memorizes the training data instead of learning the underlying pattern. The symptom is a large gap between training accuracy and validation (or test) accuracy. For example, a decision tree with no depth limit can grow one branch per training sample, achieving nearly 100% training accuracy while performing little better than a coin flip on new data.

Why it happens. Overfitting occurs when a model has too many parameters relative to the amount of training data, or when training continues too long without a stopping criterion.

How to fix it.

What to check in a notebook. Look at the gap between training score and validation score. If training accuracy is 0.98 and validation accuracy is 0.62, the model is overfitting. After applying regularization, both numbers should converge—even if the training score drops.

Data Leakage

Data leakage is the accidental inclusion of information in training that would not be available at prediction time. It produces suspiciously good metrics during development and catastrophic performance in production.

Common sources.

How to fix it. Wrap all preprocessing steps inside a scikit-learn `Pipeline`. When the pipeline is fit on training data only, the scaler sees only training statistics. When it transforms the test set, it uses those same training statistics—mimicking real-world deployment accurately. Moving `StandardScaler()` from outside the pipeline to inside is often the single line change that eliminates leakage.

What to check in a notebook. Look for `scaler.fit(X)` or `scaler.fit_transform(X)` called before `train_test_split`. That is the classic leakage bug. Also look for features with suspiciously high correlations to the target.

Class Imbalance

Class imbalance occurs when one class (the majority class) vastly outnumbers another (the minority class). A fraud-detection dataset might have 990 legitimate transactions for every 10 fraudulent ones. A naive model that always predicts "legitimate" achieves 99% accuracy while being completely useless.

Why accuracy is misleading here. Accuracy counts all correct predictions equally. In imbalanced data, the majority class dominates. Use precision, recall, and F1-score for the minority class, or the ROC-AUC score, to measure real performance.

How to fix it.

What to check in a notebook. Run `y.value_counts()` early. If the ratio is 10:1 or worse, imbalance is a concern. Check whether the reported metric is accuracy alone—if so, also compute minority-class recall.

Connecting Failure Modes to Real-World Risk

These are not academic edge cases. Production ML systems have failed in high-stakes settings because of each of these bugs. A model deployed on data that has shifted away from its training distribution (a related problem called distribution shift) behaves like an overfitted model in reverse: it learned real patterns, but those patterns no longer match the new world. Recognizing the red flags early—large train/validation gaps, implausibly high metrics, poor minority-class recall—is what separates a professional data analyst from someone who just runs code.

A Note on Reproducibility and Safety

When sharing or submitting notebooks, always set a random seed (`random_state=42` is conventional) so results are reproducible. Never include real personally identifiable information (PII) or protected health information (PHI) in practice notebooks, even anonymized versions. Confirm your instructor's data-handling policy before loading any external dataset.

Key terms9

OverfittingA condition in which a model learns the noise and specific details of the training data so closely that it performs well on training data but poorly on new, unseen data.
Data LeakageThe accidental use of information during model training that would not be legitimately available at prediction time, causing inflated performance metrics that do not hold in production.
Class ImbalanceA dataset condition in which one target class has far fewer examples than another, causing models trained on accuracy alone to neglect the minority class.
L2 Regularization (Ridge)A technique that adds a penalty equal to the sum of squared model coefficients to the loss function, discouraging large weights and reducing overfitting.
Pipeline (scikit-learn)A scikit-learn object that chains preprocessing steps and a model estimator together, ensuring that transformations like scaling are fit only on training data and applied consistently to test data.
SMOTESynthetic Minority Over-sampling Technique; a method from the imbalanced-learn library that creates synthetic minority-class training examples by interpolating between existing minority samples.
Validation GapThe difference between a model's training metric and its validation metric; a large positive gap (high training, low validation) is a key diagnostic signal for overfitting.
class_weight='balanced'A scikit-learn classifier parameter that automatically adjusts the penalty for misclassifying each class in inverse proportion to its frequency, helping compensate for class imbalance.
Minority-Class RecallThe proportion of actual minority-class instances that the model correctly identifies; a more informative metric than overall accuracy when classes are severely imbalanced.

Worked examples3

1. A logistic regression model reports 0.96 training accuracy and 0.61 validation accuracy on a balanced binary dataset. The analyst wants to apply Ridge (L2) regularization using scikit-learn. Walk through selecting and interpreting the regularization parameter.
  1. Recognize the large validation gap (0.96 − 0.61 = 0.35) as a sign of overfitting.
  2. In scikit-learn's LogisticRegression, the regularization strength is controlled by C, where C = 1 / alpha. A smaller C means stronger regularization. The default is C=1.0.
  3. Try C=0.01 (strong regularization): refit the model, then record training accuracy and validation accuracy.
  4. Suppose the result is training accuracy 0.79, validation accuracy 0.76. The gap has shrunk from 0.35 to 0.03, indicating the model is now generalizing far better, even though training accuracy dropped.
  5. Confirm by running cross-validation (e.g., 5-fold) to ensure the improved validation score is consistent and not a fluke of one split.
Answer: With C=0.01 the validation gap narrows from 0.35 to 0.03, confirming that L2 regularization successfully reduced overfitting. Training accuracy fell from 0.96 to 0.79, which is expected and acceptable because the model is no longer memorizing noise.
2. A dataset contains 950 samples of class 0 and 50 samples of class 1. A classifier that always predicts class 0 is evaluated. Calculate its accuracy, and then calculate minority-class recall.
  1. Total samples = 950 + 50 = 1000.
  2. A classifier that always predicts class 0 correctly classifies all 950 class-0 samples and zero class-1 samples.
  3. Accuracy = correct predictions / total = 950 / 1000 = 0.95 (95%).
  4. Minority-class recall = true positives for class 1 / actual class-1 instances = 0 / 50 = 0.00 (0%).
  5. Conclusion: 95% accuracy is misleading. The model has completely failed to detect the minority class.
Answer: Accuracy = 0.95, but minority-class recall = 0.00. This demonstrates why accuracy alone is an unreliable metric for imbalanced datasets; always report minority-class recall (or F1) alongside accuracy.
3. An analyst fits a StandardScaler on the full dataset (X) before splitting into train and test sets, then trains a model. Explain the leakage, calculate how many test samples' statistics 'leak' into the scaler, and describe the corrected pipeline.
  1. The scaler computes mean and standard deviation from all 1000 samples (both future train and future test rows).
  2. When train_test_split later creates an 80/20 split, 200 test samples had their statistics included in the scaler's fit. That is 200 out of 200 test samples (100%) whose distributional information leaked into preprocessing.
  3. Correct approach: call train_test_split first, then fit the scaler only on X_train (800 samples), then use scaler.transform(X_test) to transform test data using training statistics only.
  4. Best practice: wrap the scaler and model inside a Pipeline object. Call pipeline.fit(X_train, y_train). The pipeline will internally fit the scaler on X_train and the model on the scaled X_train. Calling pipeline.predict(X_test) scales X_test using the same training statistics automatically.
Answer: 100% of test samples are contaminated when the scaler is fit on the full dataset before splitting. The fix is to place StandardScaler inside a Pipeline and fit the pipeline only on training data, ensuring test data is transformed with training-set statistics.

The math in this lesson1

Learners compute train-minus-validation score gaps and relate C = 1/alpha to regularization strength.
N-Q.3
Brush up in the math halls at newSchoolWorks.com:
In class: Instructor presents three deliberately broken notebooks (one each for overfitting, leakage, and severe class imbalance); student pairs perform a 'code review' using a structured checklist and document each bug and its effect on reported metrics. · Hands-on remediation: students fix the overfitting notebook by adding L2 regularization (ridge) or max_depth constraint, fix the leakage notebook by moving scaling inside the pipeline, and fix the imbalanced notebook using class_weight='balanced' or SMOTE from imbalanced-learn; re-run and compare before/after metrics. · Class debrief: each group presents one fix; instructor leads discussion connecting these failure modes to real-world ML disasters (e.g., model deployed on distribution-shifted data); students add a 'red flags' section to their concept maps.
Materials: Jupyter Lab, scikit-learn, imbalanced-learn (imblearn), instructor-prepared broken notebooks, code-review checklist handout, Géron ch. 1–2 on ML pitfalls
Check: Each remediated notebook must show improved validation metric (e.g., reduced overfit gap, improved minority-class recall) and include an inline markdown comment explaining what was wrong and how it was fixed; all three notebooks required at ≥ 70% rubric.

Practice check8

Answer each question, then check it. Nothing is recorded; this is your own practice.

Data Analysis and Statistics / Model Evaluation
1. A model achieves 0.99 training accuracy and 0.58 validation accuracy. Which failure mode does this pattern most clearly indicate?
Data Preparation and Feature Engineering
2. Which scikit-learn code change correctly prevents data leakage when using StandardScaler before a logistic regression model?
Data Analysis and Statistics / Model Evaluation
3. A fraud detection dataset has 10,000 legitimate transactions and 100 fraudulent ones. A model achieves 99% overall accuracy. Which additional metric is most important to report?
Machine Learning / Handling Imbalanced Data
4. What does SMOTE do to address class imbalance?
Data Preparation and Feature Engineering
5. An analyst applies SMOTE to the entire dataset before calling train_test_split. Why is this a problem?
Machine Learning / Regularization
6. In scikit-learn's LogisticRegression, which parameter setting applies L2 regularization?
Machine Learning / Model Selection and Tuning
7. A decision tree classifier is trained with no max_depth limit on a small dataset. Which remediation is most directly appropriate?
Data Preparation and Feature Engineering
8. When using imbalanced-learn's SMOTE inside a preprocessing pipeline, which pipeline class should be used to ensure SMOTE is applied only during the fit step and not during transform of new data?
Record this lesson on my transcript. Sign in with your key and enrollment email to record lessons (enroll free if you have no key). This page stays open to read and practise.