Find a course

Module 1: The Machine Learning Workflow and DataLesson 2 of 1115 min

Preparing Data: Cleaning, Encoding, Scaling and Splitting

Handle missing values and outliers, one-hot encode categories, standardize features, and split data into train, validation and test sets without leakage.

Step 1 of 14Learn

Real data is messy

A student project predicts apartment rents from listings. The raw data looks like this: some listings have no square footage; one claims 45,000 square feet for a studio; "neighborhood" is text like "Downtown" or "Riverside"; prices are written as "$1,450/mo" in some rows and "1450" in others; and 3% of listings appear twice.

None of this is unusual. Before any model can learn, data must be cleaned and converted into numbers.

Missing values. Options include:

  • Drop rows with missing values, which is fine if few rows are affected and they are missing at random.
  • Impute: fill in a value such as the median of the column. The median resists distortion from extreme values better than the mean.
  • Add an indicator column, such as sqft_missing = 1, because the fact that a value is missing can itself carry information. Listings without square footage might be older buildings.

Outliers and errors. A 45,000-square-foot studio is almost certainly a typo. Fix it if the cause is obvious, otherwise remove or cap it. Be careful, though: genuine extreme values, such as a real penthouse, are information, not noise.

Duplicates and inconsistent formats. Remove duplicate rows so they don't get double weight or land in both training and test sets. Standardize formats: strip "$" and "/mo", convert to numbers, use consistent units.

One rule applies to every step: compute cleaning statistics, such as the median used for imputation, from the training data only, then apply them to validation and test data. You'll see why at the end of this lesson.

Step 2 of 14Tap to reveal

Four kinds of mess and what to do

  1. Missing values

    Drop rows only if few and random. Otherwise impute (median, most frequent) and consider a "was missing" flag, since missingness itself can carry information.

  2. Impossible values

    A 45,000 sq ft apartment is almost certainly a typo. Fix it from the source if you can; otherwise treat it as missing.

  3. Duplicates

    The same listing posted twice gets double weight and can leak between train and test. Remove exact duplicates before splitting.

  4. Inconsistent labels

    "Down town", "downtown" and "DT" are one neighborhood. Standardize text categories before encoding.

Step 3 of 14Practice · What would you do?

What would you do?

In your rent dataset, 4% of listings are missing the number of bathrooms, and those listings are spread across all neighborhoods and price levels. What is a sensible way to handle this?

Step 4 of 14Learn

Turning categories into numbers

Models work with numbers, so text categories must be encoded. How you encode them matters.

Label encoding maps each category to an integer: Downtown = 0, Riverside = 1, Suburbs = 2. This is fine for ordinal categories with a natural order, such as shirt sizes S, M, L or education levels. For nominal categories with no order, like neighborhoods, it misleads many models: a linear model would treat Suburbs as "twice" Riverside, and Riverside as halfway between the other two.

One-hot encoding creates one 0/1 column per category:

Neighborhoodis_Downtownis_Riversideis_Suburbs
Downtown100
Suburbs001

Now no false order is implied. For linear models, one column is often dropped (it is implied when the others are all 0) to avoid redundancy.

Watch out for categories with hundreds or thousands of values, like zip codes or product IDs. One-hot encoding them creates a huge, sparse table. Alternatives include grouping rare categories into "Other," using a numeric summary of each category computed on training data, or models with built-in support for categories.

Also plan for unseen categories: a new neighborhood that appears after deployment. Your pipeline should handle it gracefully, for example by mapping it to "Other," instead of crashing.

Tree-based models like decision trees are less sensitive to encoding choices, but one-hot encoding remains a safe default for nominal features with a modest number of values.

Step 5 of 14Compare

Label encoding vs. one-hot encoding

AspectLabel (integer) encodingOne-hot encoding
Looks likeDowntown = 0, Riverside = 1, Suburbs = 2One 0/1 column per category
Best forOrdinal categories: S < M < LNominal categories: neighborhoods, colors
Columns added1One per category
RiskInvents an order the data doesn't haveToo many columns for high-cardinality features
Tree modelsOften fineAlso fine

Step 6 of 14Practice · Sort into groups

For a linear model, which encoding fits each feature best?

Tap an item, then tap its group (or drag it there).

Step 7 of 14Learn

Scaling features

Imagine predicting house prices from two features: square footage (500 to 5,000) and number of bedrooms (1 to 6). Many algorithms are sensitive to these different ranges.

  • Distance-based methods like k-nearest neighbors and k-means compute distances between points. A difference of 100 square feet would swamp a difference of 3 bedrooms, simply because of units.
  • Gradient descent converges much faster when features are on similar scales.
  • Regularization penalizes large weights, which is only fair if features share a scale.

Two common transformations:

Standardization (z-score): z = (x − mean) ÷ standard deviation. The result has mean 0 and standard deviation 1. A house with 2,600 square feet, when the mean is 2,000 and the standard deviation is 400, gets z = (2,600 − 2,000) ÷ 400 = 1.5: one and a half standard deviations above average.

Min-max scaling: x' = (x − min) ÷ (max − min), which maps values to the range 0 to 1. It is simple but sensitive to outliers: one extreme value squashes everything else into a narrow band.

Decision trees and tree ensembles don't need scaling, because they split on one feature at a time using thresholds; the scale doesn't change where the best split falls.

And again: the mean, standard deviation, min and max must be computed on the training set only and then reused to transform the validation and test sets, and later the live data the model sees in production.

Step 8 of 14Explore

Standardizing square footage

The line maps raw square footage (x) to its z-score. Move the mean and standard deviation and watch where 3,000 sq ft lands.

-5-2.502.55 1,0002,0003,0004,0005,000
z-score of 3,000 sq ft
2
z-score of 1,200 sq ft
-1

Step 9 of 14Practice · Code challenge

Write a function standardize(x, mean, sd) that returns the z-score of x: how many standard deviations x lies above (positive) or below (negative) the mean.

Runs in a sandbox in your browser.
  • standardize(70, 50, 10)
  • standardize(45, 50, 10)
  • standardize(50, 50, 5)
  • standardize(2600, 2000, 400)

Step 10 of 14Learn

Splitting without leaking

Data leakage happens when information that would not be available at prediction time influences training. It produces models that look excellent in testing and fail in the real world, and it is one of the most common serious mistakes in machine learning.

Leakage comes in several forms:

Target leakage: a feature that is a consequence of the label. Predicting whether a patient has pneumonia using "was prescribed antibiotics for pneumonia" will score brilliantly and be useless, because the prescription happens after diagnosis.

Train-test contamination: preprocessing using the whole dataset before splitting. If you compute the mean for standardization or imputation over all rows, test-set information has influenced training. The effect is usually small for simple statistics but can be large for more complex steps such as feature selection.

Duplicate or related rows across splits: the same customer, patient or photo appearing in both training and test sets. The model recognizes them instead of generalizing. Split by entity, for example by patient ID, so all of one patient's records land on the same side.

Time leakage: for anything that changes over time, a random split lets the model train on the future and predict the past. Instead, train on earlier periods and validate on later ones, the way the model will actually be used.

A clean recipe: split first; fit every preprocessing step (imputers, scalers, encoders) on training data only; apply the fitted steps to validation and test data. Libraries offer pipelines that enforce this order automatically.

A rule of thumb: if a result seems too good to be true, hunt for leakage before celebrating.

Step 11 of 14Practice · Diagram

Leak-free preprocessing order

Statistics such as means and category lists must come from training data only. Tap each step.

At which step are the scaling mean and standard deviation computed?

Tap the shape that answers the question, then press Check.

Leak-free preprocessing orderProcess diagram: Split first → Fit on training data → Apply to validation and test → Train and evaluate.Split firstFit ontraining dataApply tovalidationand testTrain andevaluate
Split first

By time for forecasting, by customer when one customer has many rows.

Fit on training data

Learn the mean, standard deviation and imputation values from the training rows only.

Apply to validation and test

Reuse the training statistics; never recompute them on held-out data.

Train and evaluate

Step 12 of 14Practice · Spot the mistake

A student describes their workflow for predicting next month's product demand. Which steps introduce leakage? Click them.

Step 13 of 14Practice · True or false

When the same customer appears multiple times in a dataset, it is safest to split rows randomly so each customer's records are spread across training and test sets.

Step 14 of 14Practice · Choose one

A spam classifier reaches 99.8% accuracy on the test set. You discover one feature is "was moved to spam folder by user." What is going on?