Building a Home Sale Price Estimator End to End
Machine LearningModel answerLast updated
Design a regression pipeline that estimates residential sale prices, covering missing data, categorical encoding, feature ideas, time-aware validation, metrics, and interpretability.
Context
A real estate platform wants a model that estimates the sale price of residential homes. You have roughly 100,000 completed sales from the last five years. Each record includes living area (sqft), bedroom and bathroom counts, year built, lot size, basement area, a categorical neighborhood field, and the price the home sold for. Some records also carry an earlier sale of the same property.
The model's users are real estate agents, so predictions must be explainable to non-technical people.
What to cover
Walk through how you would design the full pipeline:
- Cleaning and encoding. How do you treat missing values (for example, a blank basement area or lot size) and a high-cardinality categorical field such as neighborhood?
- Feature engineering. Propose three concrete derived features and explain the reasoning behind each.
- Validation. Housing markets drift over time. How do you split the data so your offline results reflect performance on future sales?
- Metrics. Which evaluation metric(s) would you report, and why might you choose them over mean squared error?
- Outliers. How do you detect unusual prices and decide what to do with them?
Worked scenario
A new listing arrives: 2,500 sqft, built in 1990, located in an affluent neighborhood that is on the rise, with the lot size field empty. Describe what happens to this record, step by step, before the model scores it. Focus on the missing lot size and the neighborhood encoding.
Constraint
Whatever model you choose, justify how it stays interpretable for agents.
Hints
Hint 1
Ask why a value is missing before choosing a fix: a blank basement area usually means no basement, while a blank lot size is genuinely unknown. Consider a missingness flag alongside any imputation.
Hint 2
Neighborhood has too many levels for one-hot encoding. Think about shrinking each neighborhood's average toward the overall average based on how many sales it has, and make sure the encoding is computed without peeking at the row's own price or at future sales.
Hint 3
Do not shuffle the data randomly. Train on earlier periods and test on later ones, and think about which metric treats a $50k miss on a $200k house differently from the same miss on a $2M house.
Model answer
Easy Try it yourself first — then compare your approach, complexity and edge cases.
Framing
Before designing anything, pin down the prediction moment: we estimate the price at listing or sale time, so every feature must be known then. The current sale price is the target and can never be a feature. An earlier sale of the same property, dated before the current one, is a legitimate and powerful feature.
Target. Model log(price). Prices are right-skewed and errors are mostly proportional, so the log stabilizes variance and makes linear coefficients read as approximate percentage effects.
Model choice (interpretability).
- A ridge regression on log price is a transparent baseline.
- The main model is gradient-boosted trees with monotonic constraints (price should not decrease as area or bathrooms increase, all else equal). Explain individual predictions with SHAP.
- An Explainable Boosting Machine is a good alternative when agents want to see each feature's effect curve.
1. Preprocessing
Missing values: diagnose the cause first.
- Structural: a missing basement area typically means no basement. Fill with 0 and add
has_basement. - Genuinely unknown: for lot size, add a
lot_size_missingflag (condos often lack it, so the flag carries signal), then impute with the training median for the same neighborhood and property type, falling back to the city median. - Tree libraries can handle NaN natively, but the flag plus group-median approach also helps the linear baseline.
- Compute all imputation statistics on training data only, inside each fold.
High-cardinality neighborhood.
-
One-hot creates hundreds of sparse columns and overfits small areas.
-
Use smoothed target encoding on
log(price per sqft):enc = (n · area_mean + m · global_mean) / (n + m), withmaround 20 to 50. -
Avoid leakage by using out-of-fold values for training rows and only sales before the row's date.
-
Unseen or tiny neighborhoods fall back to a parent region (zip, then city).
Outliers.
- Detect with domain rules (price under a floor, zero sqft, impossible bedroom counts), a robust z-score of price per sqft within neighborhood (median and MAD), and large out-of-fold residuals.
- Remove data errors and non-arm's-length sales (family transfers, foreclosures) if flagged. Keep real luxury homes; the log target and a Huber loss limit their pull.
2. Feature engineering
- Age at sale = sale year minus year built (plus years since remodel). Raw year built mixes vintage with market timing; age captures depreciation directly.
- Trailing neighborhood price per sqft over the prior 6 to 12 months, plus its year-over-year growth. This encodes the current local level and momentum, which matters for a rising area. It must be strictly lagged.
- Time-adjusted prior sale price =
prior_price × index_now / index_at_prior_sale. It acts as a repeat-sales signal that captures hard-to-observe quality such as finishes and views.
Other useful ones: log(sqft), sqft per bedroom, and sale month for seasonality.
3. Validation
A random split leaks future market conditions into training: the model learns later price levels and is "tested" on earlier sales, which is overly optimistic.
- Use a chronological split: train on the early years, validate on the next block, and hold out the most recent months as a final test.
- For tuning, use walk-forward (expanding window) CV: train through month t, validate on t+1 to t+3, then roll.
- Leave a small gap between train and validation so lagged features do not straddle the boundary.
- Refit every encoder and imputer inside each fold.
4. Metrics
Report median absolute percentage error (MdAPE) and the share of predictions within 10% of the actual price as primary metrics, with RMSE on log price and dollar MAE as secondary.
Why not MSE:
- Squaring lets a handful of mansions or bad records dominate both the metric and the fit.
- Errors in housing are relative: $50k matters far more on a $200k home than on a $2M one.
- Median and percentage metrics are robust to leftover outliers and match how agents judge accuracy.
Also slice results by price tier and neighborhood; a good average can hide bias in thin markets.
Worked scenario
For the 2,500 sqft, 1990, rising-neighborhood listing with no lot size:
- Set
lot_size_missing = 1and impute lot size with the stored median for that neighborhood and property type (city median if the neighborhood is thin). With boosted trees, passing NaN is also fine; keep the flag. - Look up the stored smoothed neighborhood encoding. Attach the neighborhood's trailing price per sqft and its growth rate as of today, which tells the model the area is appreciating. A brand-new neighborhood uses the parent-region value.
- Derive age (current year minus 1990),
log(2500), sqft per bedroom, and any time-adjusted prior sale. - Score to get log price, exponentiate to dollars, and return a SHAP breakdown plus a prediction interval (for example from quantile models) so agents see both the number and its drivers.
Common mistakes
- Using the sale price, or any statistic including it, as a feature.
- Fitting imputers or encoders on the full dataset before splitting.
- Randomly shuffled validation on time-dependent data.
- Deleting all high-priced homes as outliers, which biases the model against the luxury segment.
- Reporting only RMSE in dollars, hiding poor relative accuracy on cheaper homes.