Data Preprocessing

Dive into Deep Learning · §1.2

From Raw Tabular Data to Clean Tensors
schema inspection · missing-data mechanisms · one-hot encoding · z-score standardization · data leakage

Why Raw Tabular Data Cannot Go Straight into a Neural Network

The Preprocessing Pipeline

  • Heterogeneous types & gaps: Real-world CSV logs mix numerical columns (int64, float64), free-text categorical strings ("Slate", "Tile"), and unrecorded NaN entries—whereas tensor kernels require dense, homogeneous floating-point buffers.
  • Incommensurate scales: In our house-price dataset, Area (\sim 10^3\text{ sq ft}) is roughly 500\times larger than NumRooms (\sim 10^0), skewing distances and gradients if left unscaled.
  • Statistical judgment, not boilerplate: Every preprocessing choice—dropping vs. imputing NaNs, integer vs. one-hot encoding, whole-table vs. training-split scaling—imposes an explicit statistical assumption on what the downstream model can learn.

Ingesting Raw CSV Records into a DataFrame

Loading Tabular Data

  • Plain-text tabular storage: Comma-separated values (CSV) files store one record per line with comma-delimited fields; empty fields between consecutive commas (e.g., ,Tile,2100,290000) denote unrecorded measurements.
  • Automatic sentinel parsing: pd.read_csv parses the text file into a 2D DataFrame with named, typed columns and replaces blank entries with NaN (Not a Number).
  • Running dataset (house_tiny.csv): 10 residential home sales recording NumRooms, RoofType, floor Area (sq ft), and sale Price ($).
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

Auditing Schema Types and Summary Statistics

Exploratory Inspection

  • data.info() reveals an IEEE 754 effect: Even though room counts are whole numbers, NumRooms is promoted to float64 because standard integer arrays cannot represent the floating-point NaN bit pattern.
data.info()
Column Non-Null Dtype Preprocessing Role
NumRooms 7 / 10 float64 Continuous feature (3 NaNs)
RoofType 6 / 10 str Categorical feature (4 NaNs)
Area 10 / 10 int64 Continuous feature (complete)
Price 10 / 10 int64 Supervised target label y
  • data.describe() exposes scale disparities across observed entries (\bar{x}_{\text{Area}} = 1{,}654\text{ sq ft} vs. \bar{x}_{\text{Rooms}} = 3.29):
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

Separating Input Features (X) from Target Labels (y) First

Pipeline Hygiene

  • Isolate y before transforming X: Split features from target Price before imputation or scaling so target statistics never leak into \mathbf{X}.
  • Select by column name, not position: data.drop(columns='Price') survives upstream schema changes that would break .iloc[:, :3].
inputs, targets = data.iloc[:, :3], data.iloc[:, 3]
list(inputs.columns), targets.name
(['NumRooms', 'RoofType', 'Area'], 'Price')

Diagnosing Missing Values: Why Row Deletion Is Dangerous

Missing Data

  • Counting gaps (isna().sum()): Sums the Boolean missingness mask per column (NumRooms: 3 missing, RoofType: 4 missing).
  • Why dropna() fails in practice:
    1. Sample destruction: Dropping incomplete rows (inputs.dropna()) keeps only 4 of 10 homes, discarding 60\% of our dataset.
    2. Selection bias: Whenever values are not missing completely at random (e.g., studio apartments or luxury estates disproportionately omitting room counts), row deletion biases the surviving sample.
inputs.isna().sum()
NumRooms    3
RoofType    4
Area        0
dtype: int64
len(inputs.dropna()), len(inputs)
(4, 10)

Numerical Imputation and Missingness Indicator Features

Imputation Strategies

  • Mean / median imputation: Fills numerical NaNs with \mu_{\text{Rooms}} \approx 3.29, but piling imputed rows at \mu shrinks sample spread \sigma (1.11 \to 0.91).
  • Missingness indicator (is_na): Adding a binary 0/1 flag lets linear weights shift predictions when unrecorded values carry signal (e.g., luxury estates).
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

Encoding Categorical Features as Orthogonal One-Hot Vectors

Categorical Representation

  • Why integer IDs fail on unordered categories: Assigning \textrm{Slate}=0, \textrm{Tile}=1, \textrm{missing}=2 forces any linear layer \mathbf{x}^\top \mathbf{w} to treat Tile as halfway between Slate and an unrecorded roof, inventing a false ordering and metric distance.
  • One-hot basis vectors in \mathbb{R}^K: pd.get_dummies(..., dummy_na=True, dtype=float) expands K categories into K orthogonal 0/1 columns (including RoofType_nan as a dedicated missingness channel), placing every category at equal Euclidean distance \sqrt{2}.

The Expanded One-Hot Table and High-Cardinality Limits

Categorical Representation

  • Row-sum invariant: In every row, Slate + Tile + nan = 1.0, placing categories at orthogonal corners of \mathbb{R}^K.
  • High-cardinality limit: For K = 50{,}000 ZIP codes or tokens, one-hot vectors are 99.99\% zeros; use learned embeddings \mathbf{E} \in \mathbb{R}^{K \times d} (d \ll K) instead.

The Expanded One-Hot Table (cont.)

One-Hot Encoding in Code

pd.get_dummies with dummy_na=True gives each RoofType category, including NaN, its own 0/1 column:

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
...
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

Feature Scaling: Why Unscaled Units Distort Optimization

Standardization

  • Unit mismatch: In raw units, \Delta\text{Area} = 3\text{ sq ft} dwarfs \Delta\text{NumRooms} = 2\text{ rooms}, distorting Euclidean distances, L_2 weight decay, and gradients.
  • Ill-conditioned valleys: A 500\times scale gap elongates the loss Hessian \nabla^2 \mathcal{L}, forcing gradient descent to zig-zag at a tiny learning rate.
  • Z-score standardization centers each continuous column to mean 0 and unit variance (1): z_i = \frac{x_i - \mu}{\sigma}, \qquad \sigma = \sqrt{\frac{1}{n-1}\sum_{i=1}^n (x_i - \mu)^2}

Standardizing Continuous Features While Preserving Binary Indicators

Standardization in Code

  • Scale continuous features only: We standardize ['NumRooms', 'Area'] while leaving the one-hot columns RoofType_* untouched on \{0.0, 1.0\} so binary presence/absence semantics remain intact.
  • Interpreting z-scores: Row 6 (5 rooms, 2{,}600\text{ sq ft}) maps to (+1.89, +1.70), showing that the home sits \approx 1.7\text{--}1.9\sigma above average on both dimensions.
  • Imputed entries map to 0: Rows 1, 4, and 8 were filled with \mu_{\text{Rooms}}, so their standardized room count is identically 0.0.
numerical = ['NumRooms', 'Area']
mu, sigma = inputs[numerical].mean(), inputs[numerical].std()
inputs[numerical] = (inputs[numerical] - mu) / sigma
inputs

Standardizing Continuous Features (cont.)

The Standardized Table

NumRooms and Area now hold z-scores; the RoofType_* indicators keep their 0/1 values:

   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
...
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

The Golden Rule of Preprocessing: Fit on Train, Apply to Test

Methodological Invariant

  • How leakage happens: Computing imputation means, category schemas, or (\mu, \sigma) on the full table before splitting leaks test distribution statistics into training features.
  • Fit on \mathcal{D}_{\text{train}} only: Freeze (\mu_{\text{train}}, \sigma_{\text{train}}) and apply unchanged to \mathcal{D}_{\text{val}} and \mathcal{D}_{\text{test}}.
  • Zero-variance guard: If \sigma_{\text{train}} = 0, clamp \sigma \leftarrow \max(\sigma, \epsilon) to avoid dividing by zero.

Concept Check: Spotting Data Leakage and Encoding Bugs

Check Your Understanding

Identify the statistical or systems bug in each preprocessing snippet:

  1. Snippet A: Standardize the full DataFrame df[num] = (df[num] - df[num].mean()) / df[num].std(), and then split train, test = df.iloc[:800], df.iloc[800:].
  2. Snippet B: Encode Neighborhood ("Downtown", "Suburb", "Rural") as integers 0, 1, 2 before feeding into a linear regression model \hat{y} = \mathbf{x}^\top \mathbf{w} + b.
  3. Snippet C: Call pd.get_dummies(train_df) and pd.get_dummies(test_df) independently when "Slate" appears in train_df but never in test_df.

Answers:

  1. Data leakage: Test rows 800\ldots N influenced \mu and \sigma. Compute mu, sigma on train only, then transform both train and test with those training parameters.
  2. False metric ordering: A single weight w_{\text{neigh}} forces \hat{y}(\text{Suburb}) - \hat{y}(\text{Downtown}) = \hat{y}(\text{Rural}) - \hat{y}(\text{Suburb}). Use one-hot encoding instead.
  3. Feature-dimension mismatch: test_df will lack the RoofType_Slate column, causing a shape mismatch (or misaligned weights) at matrix multiplication time. Align test_df to train_df’s columns.

Bridging Clean DataFrames to Contiguous float32 Tensors

Tensor Conversion

  • Downcast float64 \to float32: Pandas defaults to 64-bit floats (8 B) or mixed bool/object columns; .to_numpy(dtype='float32') halves memory (4 B) and matches GPU layer weights.
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)

Summary: From Messy Tables to Model-Ready Design Matrices

Key Takeaways

Preprocessing Stage pandas / Framework Primitive Statistical Purpose Production & Leakage Invariant
Schema & Scale Audit df.info(), df.describe() Detect NaN float promotion, text columns, scale gaps Inspect distributions & sentinel codes before modeling
Target Isolation df.drop(columns='Price'), df['Price'] Separate design matrix \mathbf{X} from target labels \mathbf{y} Select by column name, never fragile .iloc positions
Missing Numericals fillna(train_mean) + isna() flag Preserve rows without selection bias; capture missingness signal Fit imputation mean/median on \mathcal{D}_{\text{train}} only
Unordered Categories pd.get_dummies(..., dummy_na=True) Map K categories to orthogonal basis vectors in \mathbb{R}^K Lock category schema on \mathcal{D}_{\text{train}}; use embeddings if K \gg 10^2
Continuous Scaling (x - \mu_{\text{train}}) / \sigma_{\text{train}} Equalize feature units (\mu=0, \sigma=1); condition loss curvature Fit (\mu, \sigma) on \mathcal{D}_{\text{train}} only; leave 0/1 one-hots unscaled
Tensor Construction tensor(df.to_numpy(dtype='float32')) Pack heterogeneous columns into contiguous float32 buffer Verify (N, D) feature and (N,) target shapes