Module 3 · Beginner · Data preparation and EDA

Project: prepare messy data for machine learning

A data preparation project on census data: missing values, duplicates, redundant and skewed columns, rare categories, a leak-proof pipeline and a saved model.

By theprogrammers team · · 21 min read

Real data never arrives ready. Columns are missing values, the same record appears twice, two columns say the same thing in different words, and one category covers 90% of the rows while 40 others share the rest. Most of a machine learning engineer's time goes into this part, and most of a model's quality comes from it.

Here you'll prepare a real, messy dataset for machine learning from start to finish: the US census income data, about 48,800 people, where the task is to predict whether a person earns more than $50,000 a year. You'll look at the data with specific questions, make a cleaning decision for each problem with a reason, build one pipeline that does it all without leakage, prove the preparation helps by comparing it with a careless version, and save the result so it can be used on new people.

What you need first: this module's lessons, especially scikit-learn pipelines, data leakage, train, validation and test sets and encoding categorical data. The EDA lessons on missing values and duplicate rows help too.

Key terms

  • Data preparation: everything between raw data and a model: checking, cleaning, encoding, scaling and splitting.
  • Informative missingness: when the fact that a value is missing itself tells you something about the label.
  • Redundant column: a column that carries the same information as another one.
  • Rare category: a category with very few rows, too few for a model to learn anything reliable about it.
  • Baseline: the score of a trivial method, such as always predicting the most common answer, that a real model must beat.

1. The problem and the metric

The data comes from the 1994 US census. Imagine a survey team that collects income data and wants to flag answers that look inconsistent with the rest of a person's profile, so a person can double-check them. The model estimates whether each person earns above $50,000; the team reviews records where the estimate and the answer disagree.

  • Label: income above $50,000 (1) or not (0).
  • Cost of mistakes: a wrong flag costs a few minutes of a reviewer's time. A missed inconsistency means a wrong figure stays in the survey. Neither is catastrophic.
  • Metric, chosen now, before modelling: accuracy, because both mistakes cost about the same, compared against the baseline of always predicting the common answer. We'll also track the share of high earners the model finds, because with only about a quarter of people above $50,000, a model could look accurate while missing most of them. (That share is called recall; classification metrics covers it fully.)

2. Load the data and take a first look

Download the data: adult-income.csv (5.3 MB), or from the original source, the UCI Machine Learning Repository. The code below loads it for you, so you only need the file to open it in a spreadsheet or work offline: load it with pd.read_csv("adult-income.csv").

fetch_openml(data_id=1590) downloads the data from OpenML, a public library of datasets, the first time, and saves a copy. .frame gives the whole table, label included:

import numpy as np
import pandas as pd
from sklearn.datasets import fetch_openml

adult = fetch_openml(data_id=1590, as_frame=True).frame
print(adult.shape)
print(adult.head(3).T)
(48842, 15)
                                0                   1                   2
age                            25                  38                  28
workclass                 Private             Private           Local-gov
fnlwgt                     226802               89814              336951
education                    11th             HS-grad          Assoc-acdm
education-num                   7                   9                  12
marital-status      Never-married  Married-civ-spouse  Married-civ-spouse
occupation      Machine-op-inspct     Farming-fishing     Protective-serv
relationship            Own-child             Husband             Husband
race                        Black               White               White
sex                          Male                Male                Male
capital-gain                    0                   0                   0
capital-loss                    0                   0                   0
hours-per-week                 40                  50                  40
native-country      United-States       United-States       United-States
class                       <=50K               <=50K                >50K

.T flips the table on its side (rows become columns) so all 15 columns fit on screen. 48,842 people and 15 columns, the last one being the label, class. A few columns already raise questions: what is fnlwgt? Why are there both education and education-num?

print(adult["class"].value_counts(normalize=True).round(3))
class
<=50K    0.761
>50K     0.239
Name: proportion, dtype: float64

About 24% earn above $50,000. So a "model" that always says "no" is right 76% of the time. Every real model must clearly beat that.

3. Explore with questions

Each check below answers one question, and ends with a decision.

Which values are missing, and does it matter?

missing = adult.isna().sum()
print(missing[missing > 0])
print(f"rows with any missing value: {adult.isna().any(axis=1).mean():.1%}")
workclass         2799
occupation        2809
native-country     857
dtype: int64
rows with any missing value: 7.4%

Three categorical columns have gaps, affecting about 7% of rows. The easy move is to drop those rows. Before you do, ask: are the people with missing values different?

high_earner = adult["class"] == ">50K"
print(high_earner.groupby(adult["occupation"].isna()).mean().round(3))
occupation
False    0.248
True     0.094
Name: class, dtype: float64

Of people with an occupation recorded, about 25% are high earners. Of people with occupation missing, only about 9%. Many of them are probably not working at all. So "occupation is missing" is useful information. Dropping those rows would throw it away, and would also leave the model unable to handle a new person with a blank occupation.

Decision: keep the rows, and fill missing categories with a new category, "Missing", so the model can learn what a blank means.

Are there duplicate rows?

print("duplicate rows:", adult.duplicated().sum())
pair = adult[adult.duplicated(keep=False)].sort_values(["age", "fnlwgt"]).head(2)
print(pair[["age", "workclass", "fnlwgt", "occupation", "hours-per-week", "class"]])
duplicate rows: 52
       age workclass  fnlwgt occupation  hours-per-week  class
4152    17   Private  153021      Sales              20  <=50K
40948   17   Private  153021      Sales              20  <=50K

duplicated() marks every row that's an exact copy of an earlier one; keep=False marks all copies, so you can see them side by side. These pairs match in every column, including fnlwgt, a number that's almost unique per person (see below). They're almost certainly the same record entered twice. If one copy landed in training and the other in testing, the model would be tested on a person it had already seen.

Decision: drop exact duplicates, before splitting.

Do any columns say the same thing?

pairs = adult.groupby("education", observed=True)["education-num"].unique()
print(pairs.head(6))
education
10th       [6]
11th       [7]
12th       [8]
1st-4th    [2]
5th-6th    [3]
7th-8th    [4]
Name: education-num, dtype: object

groupby("education") collects the rows for each education level, and .unique() lists the education-num values found in each group. (observed=True only lists categories that actually occur.) Every education level has exactly one number: education-num is the same information, coded as a number in order, from 1 (preschool) to 16 (doctorate).

Decision: keep education-num, because its order means something (more years of education), and drop education, which would add 16 one-hot columns for the same information.

What is fnlwgt?

The dataset's documentation explains that fnlwgt ("final weight") is the number of people in the US population each row represents, used by statisticians to scale survey results up to the whole country. It describes how the census sampled people, not the person.

Decision: drop it. It isn't something you'd know about a new person, and it isn't a property of them.

How are the numbers spread?

numeric = ["age", "education-num", "hours-per-week", "capital-gain", "capital-loss"]
print(adult[numeric].describe().round(1).T[["mean", "50%", "max"]])
print(f"capital-gain is 0 for {(adult['capital-gain'] == 0).mean():.1%} of people")
print("capital-gain exactly 99999:", (adult["capital-gain"] == 99999).sum())
                  mean   50%      max
age               38.6  37.0     90.0
education-num     10.1  10.0     16.0
hours-per-week    40.4  40.0     99.0
capital-gain    1079.1   0.0  99999.0
capital-loss      87.5   0.0   4356.0
capital-gain is 0 for 91.7% of people
capital-gain exactly 99999: 244

describe() gives summary statistics; .T[[...]] keeps three of them. Age and hours look sensible. Capital gain is extremely skewed: zero for 92% of people, with a maximum of exactly 99,999 for 244 people. That value is a cap used by the census for "99,999 or more", not a real amount. A log transform is the usual fix for a column like this (skewed data and log transforms), but whether it helps this model is a question for the validation set, not a rule.

Decision: keep both capital columns, and test raw against log-transformed on validation data.

Are some categories too rare to learn from?

countries = adult["native-country"].value_counts()
print(f"{len(countries)} countries; United States = {countries.iloc[0] / countries.sum():.1%}")
print(countries.tail(4))
41 countries; United States = 91.3%
native-country
Scotland              21
Honduras              20
Hungary               19
Holand-Netherlands     1
Name: count, dtype: int64

41 countries, but 91% of people are from the United States, and some countries have a handful of rows. A model can't learn anything reliable from 23 people, and one-hot encoding every country adds 41 columns.

Decision: group rare categories (under 0.5% of training rows) into one "infrequent" category. Scikit-learn's OneHotEncoder does this with min_frequency, and learns which categories are rare from the training rows only.

Does education relate to income the way you'd expect?

A last check that the data makes sense:

import matplotlib.pyplot as plt

share = high_earner.groupby(adult["education-num"]).mean()
fig, ax = plt.subplots(figsize=(8, 4.5))
ax.bar(share.index, share.values * 100, color="#c2410c")
ax.set_xlabel("Years of education (education-num)")
ax.set_ylabel("% earning over $50,000")
ax.set_title("Share of high earners rises with education")
ax.set_xticks(range(1, 17))
plt.show()
Bar chart of the percentage of people earning over $50,000 for each value of education-num from 1 to 16. The bars stay below about 7% up to 8 years, rise to about 16% at 9 (high school graduate), about 19% at 10, around 25% at 11 and 12, about 41% at 13 (bachelor's degree), and reach about 55%, 74% and 73% at 14, 15 and 16.

Finding: the share of high earners climbs with education, slowly at first and then steeply after 12 years. That confirms education-num is a strong feature and that its order matters. It also shows the effect isn't a straight line, worth remembering when you choose a model.

4. Clean, then split first

The decisions that don't learn anything from the data (dropping duplicates and two columns, making the label 0/1) are safe to do on the whole table. Everything that learns (filling, encoding, scaling) waits until after the split.

from sklearn.model_selection import train_test_split

clean = adult.drop_duplicates()
y = (clean["class"] == ">50K").astype(int)
X = clean.drop(columns=["class", "fnlwgt", "education"])

X_rest, X_test, y_rest, y_test = train_test_split(
    X, y, test_size=0.2, random_state=0, stratify=y)
X_train, X_val, y_train, y_val = train_test_split(
    X_rest, y_rest, test_size=0.25, random_state=0, stratify=y_rest)
print(len(X_train), len(X_val), len(X_test))
29274 9758 9758

Two splits give three parts: 60% to train, 20% to compare choices (validation), and 20% to test once at the very end. (0.25 of the remaining 80% is 20% of the whole.) stratify keeps the 24% share of high earners in every part.

5. A baseline, and a careless first attempt

DummyClassifier is a "model" that ignores the features and always predicts the most common class. It's the baseline every model must beat; baseline models covers it in the next module. A small helper reports both numbers we care about:

from sklearn.dummy import DummyClassifier

def report(name, model, X_part, y_part):
    predicted = model.predict(X_part)
    accuracy = (predicted == y_part).mean()
    found = predicted[y_part == 1].mean()      # share of real high earners predicted as 1
    print(f"{name:28} accuracy {accuracy:.3f}   high earners found {found:.1%}")

baseline = DummyClassifier(strategy="most_frequent").fit(X_train, y_train)
report("baseline (always 'no')", baseline, X_val, y_val)
baseline (always 'no')       accuracy 0.761   high earners found 0.0%

76% accuracy and not a single high earner found. Now a careless approach that a beginner might try: drop every row with a missing value, use only the numeric columns, and fit a logistic regression. Logistic regression is a classifier that adds up weighted features and turns the total into a probability; you'll build it yourself in the logistic regression module. Here it's simply a model that needs numbers:

from sklearn.linear_model import LogisticRegression
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler

complete_rows = X_train.dropna()
careless = make_pipeline(StandardScaler(), LogisticRegression(max_iter=1000))
careless.fit(complete_rows[numeric], y_train.loc[complete_rows.index])
report("careless (numbers only)", careless, X_val[numeric], y_val)
careless (numbers only)      accuracy 0.815   high earners found 39.9%

max_iter=1000 gives the solver more steps to finish; the default of 100 is sometimes not enough. It beats the baseline, but finds well under half of the high earners. It threw away 7% of the training rows and all seven categorical columns, including marital status and occupation.

6. The prepared pipeline

Now every decision goes into one pipeline. ColumnTransformer sends each group of columns through its own steps, as in scikit-learn pipelines:

from sklearn.compose import ColumnTransformer
from sklearn.impute import SimpleImputer
from sklearn.preprocessing import OneHotEncoder

categorical = ["workclass", "marital-status", "occupation", "relationship",
               "race", "sex", "native-country"]

categories_pipeline = make_pipeline(
    SimpleImputer(strategy="constant", fill_value="Missing"),
    OneHotEncoder(handle_unknown="infrequent_if_exist", min_frequency=0.005),
)
prepare = ColumnTransformer([
    ("numbers", StandardScaler(), numeric),
    ("categories", categories_pipeline, categorical),
])
prepared = make_pipeline(prepare, LogisticRegression(max_iter=1000))
prepared.fit(X_train, y_train)
report("prepared pipeline", prepared, X_val, y_val)
prepared pipeline            accuracy 0.852   high earners found 60.1%

The settings, and why:

  • SimpleImputer(strategy="constant", fill_value="Missing") turns blanks into a real category, as decided in step 3.
  • min_frequency=0.005 groups categories with under 0.5% of training rows into one "infrequent" column.
  • handle_unknown="infrequent_if_exist" sends a category never seen in training (a new country, say) to that infrequent column instead of crashing.
  • StandardScaler puts the numbers on similar scales, which helps logistic regression train smoothly.

Same algorithm as the careless version, but now it finds far more of the high earners and is more accurate. The difference is entirely preparation.

Test the open questions on validation data

Two decisions were left to the data: log-transforming the capital columns, and whether another model would use the prepared data better. FunctionTransformer(np.log1p) turns any function into a pipeline step; feature_names_out="one-to-one" tells it each output column matches one input column, so names are kept:

from sklearn.preprocessing import FunctionTransformer
from sklearn.tree import DecisionTreeClassifier

plain = ["age", "education-num", "hours-per-week"]
capital = ["capital-gain", "capital-loss"]
prepare_log = ColumnTransformer([
    ("numbers", StandardScaler(), plain),
    ("capital", make_pipeline(FunctionTransformer(np.log1p, feature_names_out="one-to-one"),
                              StandardScaler()), capital),
    ("categories", categories_pipeline, categorical),
])
with_log = make_pipeline(prepare_log, LogisticRegression(max_iter=1000)).fit(X_train, y_train)
report("prepared + log of capital", with_log, X_val, y_val)

tree = make_pipeline(prepare, DecisionTreeClassifier(max_depth=8, random_state=0)).fit(X_train, y_train)
report("prepared, decision tree", tree, X_val, y_val)
prepared + log of capital    accuracy 0.846   high earners found 59.3%
prepared, decision tree      accuracy 0.858   high earners found 57.4%

Predict, then look: most guides say "log-transform skewed columns". Here the log version is slightly worse. Why? With the raw values, a capital gain of $20,000 stands out hugely after scaling, and a big capital gain almost guarantees a high income, so the model can use that strongly. The log squeezes $20,000 and $2,000 much closer together, and some of that signal is lost. The rule of thumb was wrong for this column and this model, and only the validation set could tell you.

The depth-limited tree scores a little higher in accuracy but finds fewer high earners. The differences are within a point, small enough to be noise on one validation set (the next module's cross-validation explained shows how to compare more reliably). Decision: keep the prepared logistic regression without the log. It's simpler, nearly as accurate, and finds more high earners.

7. Check for leakage

A score this good on census data is believable, but check anyway. Train a tiny tree on one column at a time and see whether any single column predicts the label almost perfectly:

def one_column_score(column):
    if column in categorical:
        step = make_pipeline(SimpleImputer(strategy="constant", fill_value="Missing"),
                             OneHotEncoder(handle_unknown="ignore"))
    else:
        step = "passthrough"          # use the number as it is
    model = make_pipeline(ColumnTransformer([("one", step, [column])]),
                          DecisionTreeClassifier(max_depth=3, random_state=0))
    return model.fit(X_train, y_train).score(X_val, y_val)

for column in numeric + categorical:
    print(f"{column:15} {one_column_score(column):.3f}")
age             0.761
education-num   0.774
hours-per-week  0.761
capital-gain    0.805
capital-loss    0.779
workclass       0.767
marital-status  0.761
occupation      0.761
relationship    0.761
race            0.761
sex             0.761
native-country  0.761

No single column comes close to perfect. Most score exactly 0.761, the baseline. That looks odd for marital status, which clearly matters, but even among married people only about 45% are high earners. Below 50%, the tiny tree's best guess for every group is still "no", so on its own the column changes no predictions. education-num does slightly better, because more than half of people with 14 or more years of education are high earners, and capital-gain does best, 0.805, because a large gain is such a clear sign. Nothing here is recorded after the outcome, and every column describes the person at the time of the census. No leakage found.

8. Error analysis

Look at people the model got wrong with high confidence, where it gave a probability above 90% for the wrong answer. predict_proba(...)[:, 1] takes the probability of class 1 (high earner) for every row:

probability = prepared.predict_proba(X_val)[:, 1]
confident_wrong = ((probability > 0.5) != y_val) & ((probability > 0.9) | (probability < 0.1))
print("confidently wrong:", confident_wrong.sum(), "of", len(y_val))
print(X_val[confident_wrong & (probability > 0.9)].head(3).T)
confidently wrong: 124 of 9758
                             19648               20517               6706 
age                             36                  75                  67
workclass                  Private    Self-emp-not-inc             Private
education-num                   13                  16                  14
marital-status  Married-civ-spouse  Married-civ-spouse  Married-civ-spouse
occupation         Exec-managerial      Prof-specialty      Prof-specialty
relationship               Husband             Husband             Husband
race                         White               White               White
sex                           Male                Male                Male
capital-gain                  5013                4931                   0
capital-loss                     0                   0                2457
hours-per-week                  50                   3                  40
native-country       United-States       United-States       United-States

These people look like textbook high earners in the data: married, many years of education, professional or managerial jobs, and some with capital gains. Yet they earned $50,000 or less. One works only 3 hours a week. The data simply doesn't contain what explains them: perhaps retirement, a career break, or a mistake in the survey answer. A different algorithm won't fix this; only more information would. This is useful to know before spending days on tuning.

9. One final test

All decisions are made. Now, once, the test set:

report("prepared pipeline (TEST)", prepared, X_test, y_test)
report("baseline (TEST)", baseline, X_test, y_test)
prepared pipeline (TEST)     accuracy 0.852   high earners found 59.9%
baseline (TEST)              accuracy 0.761   high earners found 0.0%

The test score is very close to the validation score, which suggests the choices didn't overfit the validation set. This is the number to report.

10. Explain what the model learned

Logistic regression gives one weight per prepared column. A positive weight pushes towards "above $50,000", a negative one away from it. Because the numbers were scaled, weights can be compared roughly:

names = prepared[:-1].get_feature_names_out()
weights = pd.Series(prepared[-1].coef_[0], index=names).sort_values()
print(weights.tail(5).round(2))
print(weights.head(5).round(2))
categories__relationship_Wife                    0.78
categories__occupation_Exec-managerial           0.84
categories__marital-status_infrequent_sklearn    1.12
categories__marital-status_Married-civ-spouse    1.69
numbers__capital-gain                            2.23
dtype: float64
categories__relationship_Other-relative    -1.19
categories__marital-status_Never-married   -1.13
categories__workclass_infrequent_sklearn   -1.04
categories__occupation_Priv-house-serv     -1.02
categories__occupation_Handlers-cleaners   -0.94
dtype: float64

prepared[:-1] is the pipeline without its last step (the preparation part), and get_feature_names_out() lists the columns it produces, such as cat__occupation_Exec-managerial. The largest positive weights are capital gain, being married with a spouse at home, and managerial work. The most negative ones include never having married and some lower-paid occupations. These are associations in 1994 census data, not causes: marriage doesn't raise income by itself, but it's linked to age, career stage and household structure.

11. Limitations and harm

  • Old data. Incomes, jobs and households in 1994 differ from today, and $50,000 meant much more then. This model shouldn't make decisions about anyone now.
  • Sensitive features. The data includes race and sex. Even if you remove them, relationship ("Husband", "Wife") nearly encodes sex, so a model can still treat groups differently. Before using any model like this to make decisions about people, compare its mistakes across groups.
  • Not causal. The weights show patterns, not reasons. "Married people earn more" in this data doesn't mean marriage causes higher income.
  • Capped values. The 99,999 capital-gain cap hides real differences at the top.

12. Save it and use it

The whole pipeline (filling, encoding, scaling and model) saves as one file with joblib, a library that comes with scikit-learn:

import joblib

joblib.dump(prepared, "adult_income_pipeline.joblib")
loaded = joblib.load("adult_income_pipeline.joblib")

new_person = pd.DataFrame([{
    "age": 41, "workclass": "Private", "education-num": 14,
    "marital-status": "Married-civ-spouse", "occupation": "Prof-specialty",
    "relationship": "Husband", "race": "Asian-Pac-Islander", "sex": "Male",
    "capital-gain": 0, "capital-loss": 0, "hours-per-week": 45,
    "native-country": "India",
}])
print(f"probability of earning over $50,000: {loaded.predict_proba(new_person)[0, 1]:.2f}")
probability of earning over $50,000: 0.67

The new person's country, India, is one of the rare categories, so the encoder sends it to the "infrequent" column instead of failing. Because every step is inside the pipeline, the raw row goes straight in, with no manual cleaning to remember.

Take it further

  1. Try more features. Create works_overtime (hours above 40) and has_capital_gain (gain above 0) and test them on the validation set. Hint: you can compute them inside the pipeline with a FunctionTransformer on a DataFrame.
  2. Change the rare-category threshold. Try min_frequency of 0.001, 0.01 and 0.05. How many columns does the encoder produce each time, and does validation accuracy change?
  3. Drop the sensitive columns. Remove race and sex, retrain, and compare the share of high earners found for men and for women before and after. Hint: use X_val["sex"] == "Female" to select rows.
  4. Imputation choice. Replace the "Missing" category with the most frequent value (strategy="most_frequent"). Does losing the "missing" signal hurt?
  5. Use the raw file. Download adult.data from the UCI page and load it with pd.read_csv. It marks missing values as " ?" with a leading space. Clean it so it matches the OpenML version.

Practice

  1. Why was it better to fill missing occupations with "Missing" than to drop those rows?
Show the answer

Rows with a missing occupation are different: only about 9% are high earners, against 25% overall. A "Missing" category lets the model use that signal. Dropping them would lose 7% of the data, bias the training set towards people with full records, and leave the model unable to handle a new person with a blank field.

  1. Why must duplicates be removed before the split rather than after?
Show the answer

If duplicates are still there when you split, one copy can go to training and the other to the test set. The model is then tested on a person it has already seen, which inflates the score. Removing them first guarantees each person is on only one side.

  1. Spot the bug: a teammate writes OneHotEncoder(min_frequency=0.005).fit(X[categorical]) on the full dataset, then splits. What's wrong, and how much does it matter here?
Show the answer

The encoder learns which categories are frequent from all rows, including the test rows, which is a small leak. Here the effect is tiny, because the list of frequent categories barely changes. But the habit is wrong; keep the encoder inside the pipeline so it only ever learns from training rows.

  1. The log transform of capital gain made validation accuracy slightly worse. Does that mean log transforms are bad? Explain.
Show the answer

No. It means this transform didn't help this model on this column. A log helps when huge values distort a model, but here the huge capital gains were genuinely informative (they almost guarantee a high income), and squeezing them weakened that signal. Every "rule" of preparation is a hypothesis to test on validation data.

  1. How many columns does the prepared data have? Use the pipeline to find out, and explain where they come from.
Show the answer
print(len(prepared[:-1].get_feature_names_out()))
53

5 scaled numeric columns, plus one-hot columns for the seven categorical features: one per frequent category (including Missing where there were blanks), plus one "infrequent" column for each feature where rare categories were grouped.

  1. Your model will be used next year on new survey data where a new occupation, "Gig-worker", appears. What happens, and why?
Show the answer

Because of handle_unknown="infrequent_if_exist", the new category goes into the occupation's "infrequent" column instead of raising an error. The model treats it like other rare occupations. If many people report it, retrain so the model can learn about it directly.

Interview questions

Why should imputation and encoding go inside a pipeline?

Because they learn from data: an imputer learns medians, an encoder learns categories, a scaler learns means. Fitting them on all the data before splitting lets information from validation and test rows leak into training. Inside a pipeline, each cross-validation fold fits them on its own training rows only.

When would you keep missing values as their own category instead of filling them?

When the fact that a value is missing carries information, as in the census data, where people with no occupation recorded (many probably not working) were far less likely to be high earners. A "Missing" category lets the model use that pattern; filling with the most common value would hide it.

A common preprocessing step makes your model worse. What do you do?

Trust the validation result, not the rule of thumb. Check that the comparison is fair (same folds, same model), then drop the step, and note it: standard advice such as log-transforming skewed columns is a starting point to test, not a guarantee.

Key takeaways

  • Explore with questions, and end each one with a decision and a reason.
  • Missing values can carry information; a "Missing" category keeps it.
  • Remove true duplicates, redundant columns and columns that don't describe the case (like a sampling weight) before splitting.
  • Everything that learns from data (imputing, encoding, scaling) goes inside one pipeline, fitted on training rows.
  • Test preparation ideas on validation data: the standard log transform made this model worse.
  • Same algorithm, better preparation: high earners found rose from about 40% to about 60%.

Frequently asked questions

How much of a project is data preparation?

Usually most of it. Exploring, cleaning and checking the data often takes more time than modelling, and on tabular data it usually has more effect on the final score than the choice of algorithm.

Should I always drop rows with missing values?

No. Drop rows only when very few are affected and they don't differ from the rest. Otherwise, fill them (with a median, the most frequent value or a "Missing" category) inside a pipeline, and test which choice works best on validation data.

Why use a validation set as well as a test set?

The validation set is for decisions: which preparation, which model, which settings. The test set is used once, at the end, to estimate real performance. If you made decisions using the test set, its score would be too optimistic.

What to learn next

  1. How machine learning models learn: the start of the next module, and what happens inside fit.
  2. Baseline models: the score every model must beat.
  3. Data leakage: revisit the checks you used in step 7.