Predicting House Prices on Kaggle

Dive into Deep Learning · §4.7

Predicting House Prices on Kaggle: End-to-End Tabular ML
log-RMSE metric · leakage-free preprocessing · shared 5-fold cross-validation · weight-decayed MLP · submission

From Clean Image Grids to Messy Tabular Data

The Capstone Challenge

  • Scarce, heterogeneous data: Only 1{,}460 labeled Ames homes (+1{,}459 test homes) across 79 mixed columns (35 numeric spanning 10^0–10^5 and 44 categorical after recasting MSSubClass, with NaNs in 19 columns).
  • Relative evaluation metric: Sale prices span \$34.9\textrm{k}–\$755\textrm{k} (22\times range) and are scored by log-RMSE.
  • Overfitting risk (\sim 19 params/house): With 345 one-hot expanded features, leakage-free preprocessing, 5-fold cross-validation, and \ell_2 weight decay are essential.

Inspecting the Raw Ames Housing Table

Raw Data Anatomy

Loading the CSV tables via read_house_prices() reveals 1{,}460 \times 81 training rows (Id, 79 features, SalePrice) and 1{,}459 \times 80 test rows:

   Id  MSSubClass MSZoning  LotFrontage SaleType SaleCondition  SalePrice
0   1          60       RL         65.0       WD        Normal     208500
1   2          20       RL         80.0       WD        Normal     181500
2   3          60       RL         68.0       WD        Normal     223500
3   4          70       RL         60.0       WD       Abnorml     140000
  • Numeric vs. disguised categorical codes: LotFrontage is a physical length in feet (with 259 NaN rows), whereas MSSubClass uses integers (20, 60, 90, \ldots) to encode dwelling style (1-story, 2-story, duplex) and must be cast to str.
  • Informative missingness: In many categorical attributes (such as PoolQC or Alley), NaN is not a recording error; it encodes the physical absence of a pool or alley.
  • Row identifier trap: Column Id (1, 2, \ldots, 1460) carries zero predictive signal and must be dropped before training so the model cannot memorize row indices.

Why Kaggle Scores Log-RMSE Instead of Dollar RMSE

The Competition Metric

\textrm{log-RMSE} = \sqrt{\frac{1}{n}\sum_{i=1}^n \bigl(\log y_i - \log \hat{y}_i\bigr)^2}

  • Percentage error interpretation: Since \log(\hat{y}/y) \approx (\hat{y} - y)/y, a log-RMSE of 0.135 means predictions typically lie within e^{\pm 0.135} \approx \pm 14\% of the true price across all brackets.
  • Direct loss alignment: Predicting z_i = \log y_i under mean squared error optimizes the exact square of the competition metric.

Step 1 & 2: Standardization and Mean Imputation

Leakage-Free Preprocessing

x_{ij} \leftarrow \frac{x_{ij} - \hat{\mu}_j}{\hat{s}_j}, \qquad \hat{\mu}_j, \hat{s}_j \textrm{ from train ONLY}

  • Unit-variance scaling: Standardizing every numerical feature to zero mean and unit variance puts all weights w_j on an equal footing under \frac{\lambda}{2}\|\mathbf{W}\|_{\textrm{F}}^2.
  • Zero imputation equals mean imputation: After standardizing by \hat{\mu}_j, \hat{s}_j, replacing missing entries (fillna(0)) imputes the exact training-set mean without leakage.

Step 3 & 4: One-Hot Encoding With a Missingness Column

Leakage-Free Preprocessing

  • Preserving informative NaNs: pd.get_dummies(df, dummy_na=True) creates binary indicator columns for every observed category plus an explicit _nan column (e.g., PoolQC_nan = 1 for homes without a pool).
  • Vocabulary alignment (reindex): Any test-set category never seen in train is dropped, and any train category absent from test is filled with 0 (reindex(columns=train_cols, fill_value=0)).

The Complete Leakage-Free Preprocessing Pipeline

Preprocessing Code

All four steps fit exclusively on train and transform *others (val or test) identically, expanding 79 raw attributes into 345 float32 features:

def preprocess(train, *others):
    """Fit the feature preprocessing on train; apply it to all tables."""
    frames = [df.drop(columns=['Id', 'SalePrice'], errors='ignore')
                .astype({'MSSubClass': str})  # A code, not a quantity
              for df in (train, *others)]
    numeric = frames[0].select_dtypes(include='number').columns
    mean, std = frames[0][numeric].mean(), frames[0][numeric].std()
    for df in frames:
        df[numeric] = ((df[numeric] - mean) / std).fillna(0)
    frames = [pd.get_dummies(df, dummy_na=True) for df in frames]
    return [df.reindex(columns=frames[0].columns, fill_value=0)
              .to_numpy(dtype=np.float32) for df in frames]
((1460, 345), (1459, 345))

Target Centering in KaggleHouse

Target Normalization

  • Why center \log y \approx 12.02? An initialized network starts with outputs near 0. If targets sit around 12.02, the initial MSE is 12^2 = 144, wasting early epochs shifting the output bias.
  • Zero-mean targets (y_i - \bar{y}_{\textrm{train}}): Subtracting self.offset starts step-0 RMSE at \approx 0.40; at prediction time we add self.offset back before np.exp(pred + data.offset).

Shared 5-Fold Cross-Validation Without Leakage

Model Selection Protocol

With only 1{,}460 labeled houses, a single 20\% validation split (292 houses) has a sampling standard error of \sim 0.015 in log-RMSE, larger than the gap between competing models.

  • 5-fold partition (k_fold_data): Shuffles and splits raw_train once into K = 5 folds of 292 houses each.
  • Fold-local preprocessing: Each fold instantiates its own KaggleHouse(train_4_folds, val_1_fold), refitting \hat{\mu}, \hat{s}, dummy columns, and offset on its 1{,}168 training homes only.
  • Shared folds for paired comparison: Evaluating every candidate model on the exact same 5 folds cancels fold-sampling noise when taking pairwise differences.

Benchmarking the Linear Regression Baseline

Baseline Model

Before tuning an MLP, we benchmark d2l.LinearRegression across our 5 folds (100 epochs, batch size 64, learning rate \eta = 0.02, averaging the final 5 epochs to smooth single-epoch SGD noise):

training RMSE 0.114, validation RMSE 0.145 (folds 0.129 to 0.182)
  • Baseline performance: Achieves \sim 0.11 training log-RMSE and \sim 0.15 validation log-RMSE (\sim 15\% typical price error), with individual folds ranging from \sim 0.12 to \sim 0.19 (due to a few outlier mansions in one fold).

Building HouseMLP: 64 ReLU Units With Weight Decay

Regularized MLP Architecture

HouseMLP (345 \to 64 \to 1, \sim 22{,}200 parameters): He init, weight decay on weights only:

class HouseMLP(d2l.Module):
    """An MLP with one hidden layer, squared loss, and weight decay."""
    loss = d2l.LinearRegression.loss

    def __init__(self, num_hiddens, wd, lr):
        super().__init__()
        self.save_hyperparameters()
        self.net = nn.Sequential(nn.LazyLinear(num_hiddens), nn.ReLU(),
                                 nn.LazyLinear(1))

    def weight_init(self, module):
        if isinstance(module, nn.Linear):
            nn.init.kaiming_normal_(module.weight, nonlinearity='relu')
            nn.init.zeros_(module.bias)

    def configure_optimizers(self):
        weights = [p for p in self.parameters() if p.dim() > 1]
        biases = [p for p in self.parameters() if p.dim() == 1]
        return torch.optim.SGD([{'params': weights, 'weight_decay': self.wd},
                                {'params': biases}], lr=self.lr)

make_mlp = lambda num_inputs, wd: HouseMLP(num_hiddens=64, wd=wd, lr=0.02)

Cross-Validating Weight Decay: The U-Curve in Action

Hyperparameter Sweep

  • Sweeping wd over \{0.001, \ldots, 0.3\} on our 5 shared folds traces a textbook U-curve:
  • Under-regularized (wd = 0.001): Overfits the 1{,}168 training homes (train RMSE \sim 0.09), pushing validation RMSE to \sim 0.15–0.18, no better than linear regression.
  • Sweet spot (wd = 0.03 or 0.1): Constrains weight norms so validation RMSE drops to \sim 0.13–0.15, beating the linear baseline.
  • Over-regularized (wd = 0.3): Shrinks weights too aggressively, underfitting both training and validation splits (\sim 0.17).

Cross-Validating Weight Decay (cont.)

The Printed Sweep

For each weight decay: mean training and validation RMSE over the 5 folds, and the range of the per-fold validation RMSE:

weight decay 0.001: training RMSE 0.093, validation RMSE 0.183 (folds 0.146 to 0.277)
weight decay 0.003: training RMSE 0.095, validation RMSE 0.154 (folds 0.137 to 0.174)
weight decay 0.01: training RMSE 0.094, validation RMSE 0.151 (folds 0.138 to 0.168)
weight decay 0.03: training RMSE 0.105, validation RMSE 0.139 (folds 0.130 to 0.153)
weight decay 0.1: training RMSE 0.132, validation RMSE 0.146 (folds 0.139 to 0.159)
weight decay 0.3: training RMSE 0.163, validation RMSE 0.169 (folds 0.153 to 0.180)

Paired Fold-by-Fold Comparison vs. Linear Baseline

Statistical Verification

Because both models were evaluated on the exact same 5 folds, we can inspect the paired difference \textrm{RMSE}_{\textrm{MLP}} - \textrm{RMSE}_{\textrm{linear}} on each fold:

weight decay 0.03: MLP minus linear, per fold [-0.009  0.    -0.029  0.012 -0.006]
  • Variance reduction via pairing: Even though fold-to-fold validation RMSE varies by \pm 0.04 across splits (depending on which fold holds out unusual luxury sales), the paired difference favors the regularized MLP on nearly every fold, lowering mean validation RMSE by \sim 0.006–0.014.
  • Tabular reality check: While our regularized 64-unit MLP beats linear regression by \sim 0.01 log-RMSE on average, on heterogeneous tabular data gradient-boosted decision trees (XGBoost / LightGBM) remain fierce competitors (see the exercises).

Retraining on All 1,460 Houses & Writing submission.csv

Final Submission Pipeline

Once 5-fold cross-validation selects the best weight decay best, we fit a fresh KaggleHouse(raw_train, raw_test) preprocessor and retrain HouseMLP on all 1{,}460 labeled houses for 100 epochs:

     Id      SalePrice
0  1461  119006.625000
1  1462  154548.484375
2  1463  177151.687500
3  1464  201103.609375
4  1465  186113.750000
  • Un-centering and exponentiating: Adding data.offset back to the predicted centered log prices and applying np.exp(...) converts log predictions back into dollars for submission.csv.

Concept Check: Leakage, Log-RMSE, and Selection Bias

Check

Test your mastery of end-to-end tabular modeling:

  1. Relative nature of log-RMSE: Home A sells for \$100{,}000 and is predicted at \$125{,}000; Home B sells for \$400{,}000 and is predicted at \$500{,}000. Compare their dollar squared errors and their log-price squared errors.
  2. Subtle data leakage bug: Suppose someone runs preprocess(raw_train) once on all 1{,}460 rows before splitting into 5 cross-validation folds. What two statistics leak from the validation fold into training?
  3. Winner’s curse in model selection: When we pick the lowest validation RMSE among M hyperparameter candidates on our 5 folds, is that winning score an unbiased estimate of test-set RMSE?

Answers:

  1. Equal log error: Dollar squared errors differ 16\times (\$25\textrm{k}^2 vs. \$100\textrm{k}^2), but both have ratio \hat{y}/y = 1.25, giving the exact same log squared error (\log 1.25)^2 \approx 0.223^2 \approx 0.050.
  2. Leaked statistics: The validation fold’s feature means/standard deviations (\hat{\mu}_j, \hat{s}_j used for scaling and mean imputation) and category vocabulary leak into every training fold.
  3. Downward selection bias: No—\mathbb{E}[\min_{m=1\dots M} \hat{R}_m] \le \min_m \mathbb{E}[\hat{R}_m]. With M = 6 candidates on 5 folds the optimistic bias is tiny, but across hundreds of hyperparameter trials a separate held-out test split is required.

Summary: End-to-End Tabular Pipeline on Kaggle

Key Takeaways

Pipeline Stage Implementation Choice Mathematical / Statistical Rationale Pitfall Prevented
Metric & Target Predict z_i = \log y_i - \bar{z}_{\textrm{train}} under MSE \sqrt{\textrm{MSE}(\log y, \log \hat{y})} = \textrm{log-RMSE} (\approx \% error) Dollar MSE over-weights mansions; uncentered \log y \approx 12 slows epoch 1
Type Hygiene Drop Id; cast MSSubClass to str Row IDs are arbitrary; numeric codes are nominal categories Prevents memorizing row order or treating duplex code 90 = 4.5 \times 20
Numeric Scaling x_{ij} \leftarrow (x_{ij} - \hat{\mu}_{\textrm{train}}) / \hat{s}_{\textrm{train}}, then fillna(0) Equalizes feature scales for SGD & \ell_2 penalty; 0 = train mean Computing \hat{\mu}, \hat{s} on full table leaks validation/test distribution
Categoricals get_dummies(dummy_na=True) + reindex Binary indicator per category + explicit _nan column (345 cols) Preserves informative missingness (e.g., PoolQC = NaN means no pool)
Model Selection 5-fold CV on shared folds (k_fold) Averages 5 validation splits (292 homes each); paired differences Single 292-home split has \pm 0.015 noise; unregularized MLP overfits (0.16)
Submission Retrain with wd = best on all 1{,}460 homes \hat{y} = \exp(\hat{z} + \bar{z}_{\textrm{train}}) restores dollar scale Training error of retrained model is not a valid generalization estimate