1.2  Data Preprocessing

So far, we have been working with synthetic data that arrived in ready-made tensors of whatever shape and data type we asked for. To apply deep learning in the wild, however, we must extract messy data stored in arbitrary file formats and preprocess it into clean numerical tensors. Turning a raw table of records into model-ready tensors involves more statistical judgment than the humble word preprocessing suggests.

Consider our running example for this section: a small table of ten residential home sales recording the number of rooms (NumRooms), roof material (RoofType), floor area in square feet (Area), and sale price in dollars (Price). Small as it is, this table exhibits the three obstacles that prevent feeding raw tabular data straight into a neural network:

  1. Missing values: three of the ten homes are missing a room count, and four are missing a roof type.
  2. Categorical text fields: the roof type is recorded as a word (Slate or Tile), whereas neural networks compute exclusively with numbers.
  3. Incommensurate scales: floor area in square feet is roughly \(500\) times larger numerically than the room count.

Each obstacle demands a statistical choice: discarding incomplete rows would throw away most of the table, encoding unordered roof types as 0, 1, 2 would invent a false ordering, and leaving square footage unscaled would let it dominate distances and gradients. The pandas library (McKinney 2010) is Python’s standard tool for tabular data; below we walk through the preprocessing pipeline in Figure 1.2.1, taking a raw CSV file to float32 feature and target tensors.

Figure 1.2.1: From a file to tensors. read_csv loads the text file into a DataFrame with gaps and text columns; imputation, encoding, and scaling make every entry a number; to_numpy hands the result to the framework as the tensors X and y.

We begin by importing pandas under its customary alias pd, Python’s os module for file-path handling, and our deep learning framework (needed at the final step when we convert the cleaned table into tensors).

As in the previous section, MXNet’s array module is imported as mnp so that np continues to denote standard NumPy.

import os
import pandas as pd
import torch
import os
import pandas as pd
import tensorflow as tf
import os
import pandas as pd
from jax import numpy as jnp
import os
import pandas as pd
from mxnet import np as mnp, npx
npx.set_np()

1.2.1 Loading and Inspecting

1.2.1.1 CSV Files

Comma-separated values (CSV) files store tabular data in plain text, with column headers on the first line and one comma-delimited record per subsequent line. We write our ten-home dataset to ../data/house_tiny.csv, where empty fields between consecutive commas (such as ,Tile,2100,290000) denote unrecorded values:

os.makedirs(os.path.join('..', 'data'), exist_ok=True)
data_file = os.path.join('..', 'data', 'house_tiny.csv')
with open(data_file, 'w') as f:
    f.write('''NumRooms,RoofType,Area,Price
3,Slate,1500,210000
,Tile,2100,290000
2,,850,127500
4,Slate,1940,258000
,,1200,168000
3,Tile,1650,225000
5,Slate,2600,375000
2,,900,142000
,Tile,1750,240000
4,,2050,295000''')

Calling pd.read_csv parses the file into a pandas DataFrame, a two-dimensional table of named, typed columns with a row index (\(0\) through \(9\)) along the left margin:

data = pd.read_csv(data_file)
data
   NumRooms RoofType  Area   Price
0       3.0    Slate  1500  210000
1       NaN     Tile  2100  290000
2       2.0      NaN   850  127500
3       4.0    Slate  1940  258000
4       NaN      NaN  1200  168000
5       3.0     Tile  1650  225000
6       5.0    Slate  2600  375000
7       2.0      NaN   900  142000
8       NaN     Tile  1750  240000
9       4.0      NaN  2050  295000

Notice that pandas automatically replaced every empty field (as well as standard tokens like NA) with NaN (not a number), its sentinel for a missing value.

1.2.1.2 Data Types and Summaries

Before modifying a newly loaded dataset, inspect its row and column counts, non-missing entries, and inferred types with data.info():

data.info()
<class 'pandas.DataFrame'>
RangeIndex: 10 entries, 0 to 9
Data columns (total 4 columns):
 #   Column    Non-Null Count  Dtype  
---  ------    --------------  -----  
 0   NumRooms  7 non-null      float64
 1   RoofType  6 non-null      str    
 2   Area      10 non-null     int64  
 3   Price     10 non-null     int64  
dtypes: float64(1), int64(2), str(1)
memory usage: 481.0 bytes

Of the \(10\) rows, Area and Price are complete (int64), NumRooms has \(7\) observed entries (float64), and RoofType has \(6\) (str, or object in older pandas releases). Notice that NumRooms counts whole rooms yet was promoted to float64: under IEEE 754, NaN is a floating-point bit pattern, so standard integer arrays cannot represent missing entries.

For the numerical columns, data.describe() reports the count, mean, sample standard deviation (std), minimum, quartiles, and maximum across observed entries:

data.describe()
       NumRooms         Area          Price
count  7.000000    10.000000      10.000000
mean   3.285714  1654.000000  233050.000000
std    1.112697   556.421104   76128.710455
min    2.000000   850.000000  127500.000000
25%    2.500000  1275.000000  178500.000000
50%    3.000000  1700.000000  232500.000000
75%    4.000000  2022.500000  282000.000000
max    5.000000  2600.000000  375000.000000

NumRooms ranges from \(2\) to \(5\) (mean \(3.29\)), whereas Area ranges from \(850\) to \(2{,}600\) square feet (mean \(1{,}654\)) and Price from \(\$127{,}500\) to \(\$375{,}000\).

1.2.1.3 Separating Inputs and Targets

In supervised learning, we predict a designated target (or label) column, here Price, from the remaining input (feature) columns (NumRooms, RoofType, Area). Separating features from the target up front prevents subsequent feature transformations from touching or leaking the target. Using \(0\)-based positional slicing via .iloc, data.iloc[:, :3] selects the first three columns and data.iloc[:, 3] selects the fourth:

inputs, targets = data.iloc[:, :3], data.iloc[:, 3]
list(inputs.columns), targets.name
(['NumRooms', 'RoofType', 'Area'], 'Price')

Positional slicing is compact, but in production pipelines an inserted or reordered CSV column would cause data.iloc[:, 3] to grab the wrong target silently; selecting by name (targets = data['Price'] and inputs = data.drop(columns='Price')) avoids this risk (Exercise 1).

1.2.2 Cleaning and Encoding

1.2.2.1 Missing Values

Missing values arise routinely when sensors drop out, survey respondents skip questions, or historical records go unrecorded. Chaining .isna() with .sum() counts the missing entries in each column (True counts as \(1\)):

inputs.isna().sum()
NumRooms    3
RoofType    4
Area        0
dtype: int64

Three strategies are standard, each with a distinct statistical trade-off (Figure 1.2.2):

  • Deletion discards every row (or column) containing a missing value. It is effortless to implement, but it sacrifices data and biases the surviving sample whenever values are not missing completely at random (for instance, if studio apartments disproportionately omit room counts).
  • Imputation replaces each NaN with an estimate such as the column mean or median, preserving every row at the cost of substituting approximations that reduce the column’s apparent spread.
  • Missingness indicators pair imputation with an extra binary (\(0/1\)) column recording whether each entry was originally missing, allowing the model to exploit informative missingness (for example, if unreported room counts occur mainly on luxury estates) at the cost of one extra feature per imputed column.
Figure 1.2.2: Three treatments of a missing room count, on the first four rows of NumRooms. Deletion drops the row. Imputation fills in the mean of the seven observed counts, \(23/7 \approx 3.29\). A missingness indicator fills in the same mean and adds a column that records where the gap was.

On our ten-home table, row deletion (inputs.dropna()) leaves very little data:

len(inputs.dropna()), len(inputs)
(4, 10)

Dropping incomplete rows discards \(6\) of our \(10\) homes (\(60\%\) of the dataset), so we impute instead. Calling inputs.fillna(inputs.mean(numeric_only=True)) replaces each numerical NaN with the mean of that column’s observed entries (the median is preferable when outliers skew the mean), while leaving the text column RoofType for the categorical step next:

inputs = inputs.fillna(inputs.mean(numeric_only=True))
inputs
   NumRooms RoofType  Area
0  3.000000    Slate  1500
1  3.285714     Tile  2100
2  2.000000      NaN   850
3  4.000000    Slate  1940
4  3.285714      NaN  1200
5  3.000000     Tile  1650
6  5.000000    Slate  2600
7  2.000000      NaN   900
8  3.285714     Tile  1750
9  4.000000      NaN  2050

Rows \(1\), \(4\), and \(8\) now hold \(23/7 \approx 3.285714\), the average of the seven observed room counts. No physical house has \(3.29\) rooms; the imputed mean serves as a neutral statistical placeholder.

1.2.2.2 Categorical Features

Including missing entries as a distinct state, RoofType falls into three unordered categories: Slate, Tile, or NaN. Assigning single integer codes such as \(\textrm{Slate} = 0\), \(\textrm{Tile} = 1\), and \(\textrm{missing} = 2\) would force any linear combination of features to treat Tile as halfway between Slate and an unrecorded roof, imposing an artificial metric and ordering.

One-hot encoding (dummy variable encoding) avoids this trap by replacing a \(k\)-category column with \(k\) binary (\(0/1\)) indicator columns, setting the active category’s entry to \(1.0\) and the other \(k - 1\) entries to \(0.0\). In pandas, pd.get_dummies encodes all string/categorical columns while leaving numerical columns intact; dummy_na=True adds an explicit RoofType_nan missingness indicator, and dtype=float stores \(0.0/1.0\) floats rather than Booleans:

inputs = pd.get_dummies(inputs, dummy_na=True, dtype=float)
inputs
   NumRooms  Area  RoofType_Slate  RoofType_Tile  RoofType_nan
0  3.000000  1500             1.0            0.0           0.0
1  3.285714  2100             0.0            1.0           0.0
2  2.000000   850             0.0            0.0           1.0
3  4.000000  1940             1.0            0.0           0.0
4  3.285714  1200             0.0            0.0           1.0
5  3.000000  1650             0.0            1.0           0.0
6  5.000000  2600             1.0            0.0           0.0
7  2.000000   900             0.0            0.0           1.0
8  3.285714  1750             0.0            1.0           0.0
9  4.000000  2050             0.0            0.0           1.0

In every row, RoofType_Slate, RoofType_Tile, and RoofType_nan sum to \(1.0\) (making one column redundant alongside an intercept bias; likewise, a two-state column with no missing values needs only one \(0/1\) indicator). One-hot encoding suits modest category counts, whereas columns with tens of thousands of categories (such as postal codes, user IDs, or vocabulary words) are mapped instead to compact learnable embeddings (Section 8.4).

1.2.3 Scaling and Converting

1.2.3.1 Standardization

Although every column in inputs is now numerical, NumRooms and Area live on incompatible measurement scales: in raw units, a difference of \(2\) rooms is numerically smaller than \(3\) square feet. Unscaled square footage would dominate Euclidean distances and weight penalties, and as we will see in Section 2.3 and Chapter 9, multi-order scale gaps stretch the loss surface into narrow valleys that slow gradient descent.

Standardization (z-score normalization) puts continuous features on a common scale by mapping each entry \(x\) to

\[\frac{x - \mu}{\sigma}, \tag{1.2.1}\]

where \(\mu\) is the column’s sample mean and \(\sigma = \sqrt{\frac{1}{n-1}\sum_{i=1}^n (x_i - \mu)^2}\) is its sample standard deviation (Bessel’s \(n - 1\) denominator is derived in Section 1.6). Every standardized column has mean \(0\) and standard deviation \(1\), measuring observations in unitless standard deviations regardless of whether area was recorded in square feet or square meters. Because our one-hot indicators already lie in \(\{0, 1\}\), we standardize only ['NumRooms', 'Area']:

numerical = ['NumRooms', 'Area']
mu, sigma = inputs[numerical].mean(), inputs[numerical].std()
inputs[numerical] = (inputs[numerical] - mu) / sigma
inputs
   NumRooms      Area  RoofType_Slate  RoofType_Tile  RoofType_nan
0 -0.314485 -0.276769             1.0            0.0           0.0
1  0.000000  0.801551             0.0            1.0           0.0
2 -1.415185 -1.444949             0.0            0.0           1.0
3  0.786214  0.513999             1.0            0.0           0.0
4  0.000000 -0.815929             0.0            0.0           1.0
5 -0.314485 -0.007189             0.0            1.0           0.0
6  1.886913  1.700151             1.0            0.0           0.0
7 -1.415185 -1.355089             0.0            0.0           1.0
8  0.000000  0.172531             0.0            1.0           0.0
9  0.786214  0.711691             0.0            0.0           1.0

Row \(6\) (\(5\) rooms, \(2{,}600\) square feet) now reads \((1.89, 1.70)\), about \(1.7\) to \(1.9\) standard deviations above average on both dimensions, while the three mean-imputed room counts in rows \(1\), \(4\), and \(8\) sit at \(0.0\). Notice the side effect shown in Figure 1.2.3: placing three imputed rows at \(\mu\) adds zero to the numerator of \(\sigma\) while raising \(n\) from \(7\) to \(10\), shrinking the room-count standard deviation from \(1.11\) to \(0.91\) and inflating the observed \(z\)-scores (from \(1.54\) to \(1.89\) on row \(6\)).

Figure 1.2.3: The room counts before and after mean imputation. The three imputed counts (orange) all land on the mean \(\mu\) of the seven observed ones, so the column is less spread out than the data it came from: its standard deviation falls from \(1.11\) to \(0.91\).

One methodological rule is paramount whenever a dataset is split into a training set and a test set: all preprocessing statistics, including imputation means or medians, category vocabularies, and standardization \((\mu, \sigma)\), must be fitted exclusively on the training set and applied unchanged to the test set (Figure 1.2.4). Fitting statistics on the combined dataset leaks information from the held-out test split into training (data leakage) and inflates test scores; we enforce this rule on a full real-estate benchmark in Section 4.7 (see also Exercise 4).

Figure 1.2.4: The order of fitting and splitting. (a) Statistics fitted on all rows have already seen the test set, so the test score comes out too optimistic. (b) Statistics fitted on the training split alone are applied unchanged to both splits, and the test set stays unseen.

1.2.3.2 Conversion to Tensors

Finally, .to_numpy(dtype='float32') extracts the cleaned columns as contiguous 32-bit floating-point NumPy arrays (downcasting from pandas’ default float64), ready for our framework’s tensor constructor (Section 1.1):

X = torch.tensor(inputs.to_numpy(dtype='float32'))
y = torch.tensor(targets.to_numpy(dtype='float32'))
X.shape, X.dtype, y.shape, y.dtype
(torch.Size([10, 5]), torch.float32, torch.Size([10]), torch.float32)
X = tf.constant(inputs.to_numpy(dtype='float32'))
y = tf.constant(targets.to_numpy(dtype='float32'))
X.shape, X.dtype, y.shape, y.dtype
(TensorShape([10, 5]), tf.float32, TensorShape([10]), tf.float32)
X = jnp.array(inputs.to_numpy(dtype='float32'))
y = jnp.array(targets.to_numpy(dtype='float32'))
X.shape, X.dtype, y.shape, y.dtype
((10, 5), dtype('float32'), (10,), dtype('float32'))
X = mnp.array(inputs.to_numpy(dtype='float32'))
y = mnp.array(targets.to_numpy(dtype='float32'))
X.shape, X.dtype, y.shape, y.dtype
((10, 5), dtype('float32'), (10,), dtype('float32'))

The feature matrix X has shape (10, 5) (\(10\) homes by \(2\) standardized numerical features plus \(3\) roof-type indicators) and the target vector y has shape (10,), both in float32. Production pipelines often join multiple relational tables and screen for corrupted records or sentinel codes (such as -9999 for an unknown coordinate) before reaching this stage; once assembled into a design matrix \(\mathbf{X}\), data flow into the linear-algebraic operations of the next section.

1.2.4 Summary

Real-world tabular datasets almost always arrive with missing values, categorical text fields, and numerical columns measured on wildly different scales, whereas neural networks require clean float32 tensors. Using pandas, we load CSV files into a DataFrame with read_csv, inspect column types, missing-value counts, and value distributions with info() and describe(), and separate the target column from the input features right at the outset. Missing values can be handled via deletion, imputation (such as filling numerical gaps with the training-set mean or median), or missingness indicator columns. Unordered categorical columns are converted into binary (\(0/1\)) indicator columns via one-hot encoding (get_dummies) to avoid fabricating a numerical order, and continuous numerical columns are standardized to zero mean and unit variance (\(x \mapsto (x - \mu)/\sigma\)) using statistics computed solely on the training split. Finally, .to_numpy(dtype='float32') bridges the cleaned DataFrame directly to deep learning framework tensors.

1.2.5 Exercises

  1. [code] Selecting columns by name versus position. In this section, we split data into features and targets by integer position using data.iloc[:, :3] and data.iloc[:, 3]. Suppose an updated version of house_tiny.csv inserts a new column YearBuilt between Area and Price.

    1. What will the positional split data.iloc[:, :3] and data.iloc[:, 3] place into inputs and targets on the updated file? Will any subsequent line of code in this section raise an exception, or will the pipeline train a model to predict the wrong target silently?
    2. Rewrite the feature/target split using column names (for example, via data['Price'] and data.drop(...)) so that targets always extracts Price and inputs retains all other columns, regardless of column order or newly added features. Consult the pandas user guide on indexing and selecting data for details.
  2. [code] Comparing imputation strategies. Impute the missing entries in NumRooms under three different schemes: (i) mean imputation, (ii) median imputation, and (iii) mean imputation augmented with a binary NumRooms_isna indicator column.

    1. For both mean imputation and median imputation, compute the sample mean and sample standard deviation of the filled NumRooms column, compare them against the mean and standard deviation of the \(7\) originally observed values, and explain why the standard deviation changes in the direction it does.
    2. Suppose that in a larger real-estate dataset, NumRooms goes unreported primarily for luxury mansions. What room count does a model see for those mansions under mean imputation alone? Explain how a linear model (which predicts price as a weighted sum of the input columns plus a bias) can use the extra NumRooms_isna indicator column to compensate for that systematic understatement.
    3. State clearly what statistical assumption each of the three treatments (deletion, mean imputation alone, and imputation with an indicator) makes about the mechanism causing values to go missing.

    Adapted from Kaggle Learn, Intermediate Machine Learning, Exercise 2.

  3. High-cardinality categorical features. One-hot encoding expands a categorical column with \(k\) distinct categories into \(k\) binary columns (or \(k + 1\) with dummy_na=True).

    1. Suppose a table of \(n = 10^6\) homes contains a ZipCode column with \(k = 10^4\) distinct postal codes and no missing values. Calculate how many gigabytes the resulting one-hot encoded matrix occupies if stored densely in 64-bit floating point (float64), and state what fraction of its entries are nonzero.
    2. Suppose the table also includes a ListingID column containing a unique identifier string for every single row. Compare three possible ways of handling ListingID: (i) one-hot encoding, (ii) mapping each ID to a learnable embedding vector, and (iii) dropping the column entirely. Under each treatment, what can a model learn from ListingID that generalizes to a newly listed house whose ListingID never appeared in the training set? Which treatment should you choose?

    Adapted from Kaggle Learn, Intermediate Machine Learning, Exercise 3.

  4. [code] Quantifying data leakage. In the main text, we imputed missing NumRooms entries and standardized NumRooms and Area using the sample mean and standard deviation computed across all \(10\) rows. Now partition data into a training set consisting of the first \(8\) rows (data.iloc[:8]) and a test set consisting of the final \(2\) rows (data.iloc[8:]).

    1. Re-run the preprocessing pipeline so that the imputation mean and the standardization parameters (\(\mu\) and \(\sigma\)) are computed exclusively on the \(8\) training rows, and then use those training parameters unchanged to impute and standardize both the training split and the test split. Compare the resulting standardized test rows against the values obtained when \(\mu\) and \(\sigma\) were computed from all \(10\) rows.
    2. Explain precisely what information about the held-out test homes leaked into the training features under the whole-table recipe.
    3. Suppose a categorical or numerical feature happens to take a constant value across all training rows (so its training standard deviation is \(\sigma = 0\)), but varies on the test rows. What does the training-only standardization formula \((x - \mu)/\sigma\) produce on the training and test splits, and how should a robust preprocessing pipeline handle zero-variance features?