data = pd.read_csv(data_file)
dataDive 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
The Preprocessing Pipeline
int64, float64), free-text categorical strings ("Slate", "Tile"), and unrecorded NaN entries—whereas tensor kernels require dense, homogeneous floating-point buffers.Area (\sim 10^3\text{ sq ft}) is roughly 500\times larger than NumRooms (\sim 10^0), skewing distances and gradients if left unscaled.NaNs, integer vs. one-hot encoding, whole-table vs. training-split scaling—imposes an explicit statistical assumption on what the downstream model can learn.Loading Tabular Data
,Tile,2100,290000) denote unrecorded measurements.pd.read_csv parses the text file into a 2D DataFrame with named, typed columns and replaces blank entries with NaN (Not a Number).house_tiny.csv): 10 residential home sales recording NumRooms, RoofType, floor Area (sq ft), and sale Price ($).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.| 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): 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
Pipeline Hygiene
Price before imputation or scaling so target statistics never leak into \mathbf{X}.data.drop(columns='Price') survives upstream schema changes that would break .iloc[:, :3].(['NumRooms', 'RoofType', 'Area'], 'Price')
Missing Data
isna().sum()): Sums the Boolean missingness mask per column (NumRooms: 3 missing, RoofType: 4 missing).dropna() fails in practice:
inputs.dropna()) keeps only 4 of 10 homes, discarding 60\% of our dataset.NumRooms 3
RoofType 4
Area 0
dtype: int64
Imputation Strategies
NaNs with \mu_{\text{Rooms}} \approx 3.29, but piling imputed rows at \mu shrinks sample spread \sigma (1.11 \to 0.91).is_na): Adding a binary 0/1 flag lets linear weights shift predictions when unrecorded values carry signal (e.g., luxury estates). 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
Categorical Representation
Tile as halfway between Slate and an unrecorded roof, inventing a false ordering and metric distance.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}.Categorical Representation
Slate + Tile + nan = 1.0, placing categories at orthogonal corners of \mathbb{R}^K.One-Hot Encoding in Code
pd.get_dummies with dummy_na=True gives each RoofType category, including NaN, its own 0/1 column:
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
Standardization
Standardization in Code
['NumRooms', 'Area'] while leaving the one-hot columns RoofType_* untouched on \{0.0, 1.0\} so binary presence/absence semantics remain intact.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
Methodological Invariant
Check Your Understanding
Identify the statistical or systems bug in each preprocessing snippet:
df[num] = (df[num] - df[num].mean()) / df[num].std(), and then split train, test = df.iloc[:800], df.iloc[800:].Neighborhood ("Downtown", "Suburb", "Rural") as integers 0, 1, 2 before feeding into a linear regression model \hat{y} = \mathbf{x}^\top \mathbf{w} + b.pd.get_dummies(train_df) and pd.get_dummies(test_df) independently when "Slate" appears in train_df but never in test_df.Answers:
mu, sigma on train only, then transform both train and test with those training parameters.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.Tensor Conversion
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.(torch.Size([10, 5]), torch.float32, torch.Size([10]), torch.float32)
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 |