4  Cleaning the Litter Box

Data Preprocessing, Normalization, and Handling Missing Values

🐾 Evergreen Chapter: Core mathematics and theory do not expire. Last verified: 2026-02-24

Prerequisites: Chapter 1, 2, & 3 Technical Keywords: Data Preprocessing, Handling Missing Values, Outliers, Normalization, Standardization, Data Augmentation, SMOTE, Class Imbalance, Train/Val/Test Split


In Chapters 1 through 3, we built the ultimate mathematical kitten. Pixel knows how to navigate space using Linear Algebra, how to handle uncertainty using Probability, and how to find the bottom of the loss landscape using Gradient Descent.

We have the perfect learning engine. Now, we need to feed it.

In Machine Learning, data is the food. But real-world data is rarely a pristine bowl of perfectly portioned kibble. It is messy, incomplete, heavily biased, and sometimes completely toxic. If you pour raw, uncleaned data into a neural network, the gradient descent engine will happily optimize itself to learn all the wrong lessons.

In the industry, we have a saying: Garbage In, Garbage Out (GIGO). A common industry aphorism is that ML engineers spend most of their time cleaning and preparing data. Let’s learn how to prep Pixel’s meals.


4.1 Missing Values: Holes in the Treat Bag

Imagine you are tracking Pixel’s daily habits in a spreadsheet. You record his weight, hours slept, and treats eaten. But on Tuesday, you forgot to write down how many hours he slept. That cell in the spreadsheet is completely blank.

To a computer, a blank space isn’t zero—it is a terrifying void known as NaN (Not a Number). If you pass a NaN into a matrix multiplication (Chapter 1), the NaN propagates. Every subsequent calculation becomes NaN, silently corrupting your entire forward pass.

We have two main ways to handle missing data:

1. Deletion (Dropping): If only a few rows have missing data, just throw those rows away.

  • Pros: Safe, no fake data introduced.
  • Cons: If you throw away every day Pixel missed a measurement, you might throw away half your dataset!

2. Imputation (Guessing): Instead of throwing the row away, we fill the hole with an educated guess.

  • Mean Imputation: Fill it with the mathematical average of all other days. (Good for smooth, Gaussian data).
  • Median Imputation: Fill it with the middle value. (Better if there are crazy outliers).
  • Mode Imputation: Fill it with the most common value. (Used for categories, like “favorite toy”).

Analogy

You lose a piece of a jigsaw puzzle of a mouse. Do you throw the whole puzzle away (Deletion)? Or do you cut out a piece of gray cardboard and shove it in the hole (Imputation)? The cardboard isn’t real, but it lets you see the big picture.

Missing data illustrated as jigsaw puzzle holes

The Missing Data Jigsaw

Rosetta Stone

Kitten World Math/Concept Python (pandas / sklearn)
“The terrifying void” NaN or None np.nan
“Throw the broken toy away” Drop rows with missing values df.dropna()
“Fill the hole with average gray” Mean Imputation (fit on train split) train_mean = X_train.mean(); X_train = X_train.fillna(train_mean); X_test = X_test.fillna(train_mean)

4.2 Outliers: The Vacuum Cleaner in the Living Room

Let’s say you are calculating the average weight of animals in your house. You have three 10-pound kittens… and one 150-pound Great Dane.

If you calculate the mean weight, the math says the “average” animal in your house weighs 45 pounds. But there is no 45-pound animal in your house! The Great Dane is an Outlier—a data point so wildly different from the rest of the distribution that it breaks your statistics.

Why do outliers ruin Machine Learning? Remember our Loss Function from Chapter 3: Mean Squared Error (MSE). Because the error is squared, an outlier creates a massive, gravitational pull on the Gradient. The neural network will warp its entire understanding of the world just to try and minimize the massive penalty caused by that one Great Dane.

How to detect them: We often use the Z-score (how many standard deviations \sigma away from the mean \mu a point is). On larger datasets, a common rule of thumb is |Z| > 3—though in our tiny 4-animal example above, the Great Dane’s Z-score is only 1.73 because the extreme value inflates \mu and \sigma itself, which is why small or heavily skewed samples often prefer robust detectors like IQR or MAD (Median Absolute Deviation).

How to fix them:

  • Remove them: Just delete the Great Dane from the dataset.
  • Cap/Clip them: Say “any animal over 20 pounds will just be recorded as exactly 20 pounds.”

4.3 Feature Scaling: Squeezing into the Cardboard Box

Imagine feeding a dataset into our network with two features: 1. Pixel’s weight in kilograms (ranges from 3 to 5). 2. Pixel’s daily steps in millimeters (ranges from 10,000 to 50,000).

When Gradient Descent tries to find the bottom of the loss bowl, it will find that the “steps” axis is a massive, elongated canyon, while the “weight” axis is a tiny, steep cliff. The gradient will bounce violently back and forth across the canyon, struggling to find the bottom.

Neural networks expect all data to live roughly in the same neighborhood—usually between -1 and 1, or 0 and 1. We must scale our features so they fit into the same perfectly square mathematical cardboard box.

1. Normalization (Min-Max Scaling): Squeezes all data exactly into a range of [0, 1]. X_{norm} = \frac{X - X_{min}}{X_{max} - X_{min}}

2. Standardization (Z-Score Scaling): Shifts the data so the mean is 0, and scales it so the standard deviation is 1. This is usually preferred for Deep Learning because it handles outliers slightly better and centers the data nicely around zero. X_{std} = \frac{X - \mu}{\sigma}

Analogy

You can’t compare the size of a mouse (inches) to the distance to the moon (miles). Standardization translates both measurements into “Kitten Units,” where 0 is an exactly average size, +1 is a bit bigger, and -1 is a bit smaller.

Catastrophic Failure: Data Leakage during Scaling

Split the data first. Fit preprocessing steps such as imputation, scaling, and PCA only on training data, then apply the fitted transformations to validation and test data. Resampling methods such as SMOTE must only be applied to training data. If you compute statistics across the entire dataset before splitting, information from the test set “leaks” into training—Pixel is secretly peeking at the answers to the exam!

Rosetta Stone

Kitten World Math/Concept Python (sklearn.preprocessing)
“Squeeze into the [0,1] box” Min-Max Scaling scaler = MinMaxScaler(); X_tr = scaler.fit_transform(X_train); X_te = scaler.transform(X_test)
“Center at 0, unit variance” Standardization scaler = StandardScaler(); X_tr = scaler.fit_transform(X_train); X_te = scaler.transform(X_test)

4.4 Class Imbalance & SMOTE: The Rare Blue Bird

You are training a neural network to look out the window and detect either “Pigeons” or “Rare Blue Birds.” You collect a dataset of 9,900 photos of Pigeons, and exactly 100 photos of Rare Blue Birds.

You train your model. It achieves 99% accuracy! You are thrilled! Then you look at its code. The model isn’t looking at the photos at all. It just blindly outputs “Pigeon” every single time. Because 99% of the photos are pigeons, the math proves that guessing “Pigeon” yields a 99% success rate.

This is the curse of Class Imbalance. The model ignores the minority class because there isn’t enough reward to learn it.

How do we fix this?

  • Undersampling: Throw away 9,800 pictures of pigeons. (But now you have very little data overall).
  • Oversampling: Duplicate the 100 blue bird photos over and over. (But the model might just memorize those exact 100 photos and overfit).
  • SMOTE (Synthetic Minority Oversampling Technique): Magic! (Chawla et al., 2002)

How SMOTE works: It goes back to Chapter 1 (Linear Algebra). It takes two vectors representing Rare Blue Birds in your dataset, draws a line between them in mathematical space, and randomly picks a point on that line to create a brand new, synthetic Rare Blue Bird that has never existed before!


4.5 Data Augmentation: Hallucinating New Toys

What if you just don’t have enough data in general? Pixel only has one toy mouse. How can he learn to recognize mice in any situation?

You use Data Augmentation. You take the single image of the toy mouse and: 1. Flip it upside down. 2. Rotate it 45 degrees. 3. Make it 20% darker. 4. Crop into just the tail.

To a neural network, a rotated matrix of pixel values looks like a completely different set of numbers. By augmenting the data, you teach the model invariance—the understanding that a mouse is a mouse, whether it is right-side up, upside down, or hiding in the shadows.


4.6 Train, Validation, and Test Splits: Not Cheating on the Exam

Before Pixel can train on the data, you must split his practice problems into three distinct piles. If you let him look at all the data at once, you will have no idea if he actually learned the rules, or if he just memorized the exact images.

  1. Training Set (Usually ~70-80%): The study material. The network looks at this data, calculates the loss, and updates its weights using backpropagation.
  2. Validation Set (Usually ~10-15%): The practice exam. The network is tested on this data after every epoch, but it does NOT update its weights from it. This prevents the model from tricking you. If validation loss starts going up while training loss goes down, Pixel is memorizing the study material (Overfitting). You use this set to tune your hyperparameters (like learning rate).
  3. Test Set (Usually ~10-15%): The final exam. This data is locked in a vault and completely hidden. You run Pixel on this data only once, at the very end of training. If you touch this data during training, it is called Data Leakage, and your results are mathematically invalid.

Analogy

Train = Homework. Val = Practice quizzes to see if he’s ready. Test = The real, one-shot bar exam.

Advanced Track Notice

The Reproducibility Habit: Get used to setting a “Random Seed” (like seed=42) in your code right now. If you shuffle your Train and Test sets randomly every time you run the script, your experiments are mathematically invalid. Good science requires reproducible data.


Micro-notebook (optional): micro-notebooks/phase01_ch04_scaling_leakage.ipynb
Time: ~20 minutes. Goal: show train-only scaling workflow and demonstrate leakage effects with a toy distance model.


4.7 Removing the Training Wheels

The Real Engineering

We talked about cleaning the litter box and missing jigsaw pieces. In the real world, data engineering is 80% of the job. ‘Data Leakage’ means you accidentally included test set information in your training features, resulting in a model that looks like a genius in Jupyter but loses the company millions in production. SMOTE and standardization aren’t just neat tricks; if you feed unscaled features into a neural network, the gradient updates will be so skewed that the model will simply fail to converge.

4.8 Paws and Reflect: Chapter Quiz

Work through these conceptually before checking the answers.

  1. You have a dataset of cat ages. One row says a cat is 9,400 years old. If you use Mean Imputation to fill in missing values in other rows, what happens?

  2. Why is predicting “Not a Bird” on every single image a perfectly logical strategy for a neural network trained on a highly imbalanced dataset?

  3. You want to normalize Pixel’s jump height. His lowest jump is 2 feet, his highest is 6 feet. Using the Min-Max formula, what is the normalized value of a 4-foot jump?

  4. True or False: You should apply Data Augmentation (like flipping and cropping) to your Test Set to see if the model is robust.

Reveal answers
  1. The 9,400 is a massive outlier. It will drag the mathematical average up so high that your “imputed” values might guess the average cat is 200 years old. Always handle outliers before imputing with the mean, or use the median!
  2. Because the Loss Function strictly penalizes wrong answers. If 99.9% of the dataset is “Not a Bird”, guessing “Not a Bird” minimizes the loss far more safely than risking a wrong guess.
  3. 0.5. The formula is (4 - 2) / (6 - 2) = 2/4 = 0.5.
  4. False! Keep the primary Test Set untouched so it reflects real-world data—if you want to evaluate robustness under flips or crops, report those separately on transformed copies without altering the primary Test Set.

4.9 Chapter 4 Summary

You’ve learned how to prepare a clean, balanced meal for your AI:

  • Garbage In, Garbage Out: The algorithm is only as good as the data you feed it.
  • Missing Values: Must be handled by dropping the broken data or imputing (guessing) the missing holes.
  • Outliers: Extreme values warp the MSE loss function and must be removed or clipped.
  • Feature Scaling: Min-Max Scaling and Standardization ensure all inputs are in the same mathematical neighborhood so Gradient Descent can walk smoothly.
  • Class Imbalance & SMOTE: When one category dominates, you must artificially balance the scales, sometimes by mathematically synthesizing new examples.
  • Data Augmentation: Stretching, flipping, and rotating existing data to create a richer, more robust dataset.

We have the math. We have the optimizer. The litter box is clean.

Checkpoint 1 is complete. You have built a solid foundation in Machine Learning fundamentals. It is time to enter Phase II. We are finally going to teach Pixel how to predict the future.


AI Safety Thread: Chapter 4

Historical Bias & Representational Harm: Data is a mirror of the world it was collected from. If you build an automatic cat-door that opens when it sees a cat face, but you only train it on pictures of white cats, the model will lock black cats out in the cold. This isn’t because the math is racist; it’s because the data was biased. If your training data lacks representation of minority classes, your model will fail them in the real world. Cleaning data isn’t just about fixing NaNs—it’s about auditing your dataset for fairness and inclusion before you ever press ‘Train’.


Next: Chapter 5: Kitty Training School →