Skip to main content

Phase 3B: Modeling Luxury Homes - Handling Outliers and Neighborhood Effects

Updated 11 min readMarkdown
Phase 3B: Modeling Luxury Homes - Handling Outliers and Neighborhood Effects

In real estate, extreme listings, both ultra-luxury and severely underpriced, can disproportionately influence predictions. These outliers, though rare, carry meaningful signals that must be preserved while keeping our model stable and robust.

In this post, we tackle handling outliers while enriching the dataset with luxury features, geospatial data, and neighborhood amenities. We continue with XGBoost with early stopping, which outperformed other models in Phase 3A. The goal: a model sensitive to nuanced high-end signals yet resilient to extremes.


Quantifying the Outlier Problem

Before introducing advanced features, I first examined how extreme listings affected baseline model performance. Using an Isolation Forest with 2% contamination rate, 86 listings out of 4,298 were flagged as outliers, typically ultra-luxury homes or unusually cheap listings.

To isolate their impact, I trained two simple baseline XGBoost models, without Optuna tuning or complex feature engineering, purely to compare how outliers influence metrics:

  • Full dataset: 4,298 listings (including outliers)

  • After removal: 4,212 listings (excluding the ~2% outliers)

The difference was striking. With the full dataset, the model’s test Root Mean Squared Error (RMSE) was ~230k and Mean Absolute Error (MAE) ~77k. After removing just 2% of listings, RMSE dropped to ~108k and MAE to ~54k. This confirmed that even a handful of extreme values can dominate model performance and inflate error metrics.

As shown in the chart, the last week’s model (green) lies between the pre- and post-outlier removal metrics, highlighting how feature engineering and hyperparameter tuning can stabilize performance. Our next modeling steps aim to bridge this gap even further.

While removing outliers improved metrics, these extreme listings still carry valuable market signals, motivating their stabilization through log transformation and richer contextual features rather than discarding them


Target Transformation for Outliers

Luxury homes create a strong right-skew in prices. To address this, I applied a log transformation to the target variable, which compresses extreme values, stabilizes variance, and reduces the influence of ultra-luxury listings on model learning.

The effect is visualized in the left and right histogram plots. The raw prices (left) exclude the top 1% of listings to keep the scale readable, with a red dashed line marking the 99th percentile, showing where most extreme values begin. The log-transformed distribution (right) includes all listings, compressing the upper range so XGBoost can focus on meaningful patterns across the full price spectrum.

Early stopping ensures robust generalization, and in combination with enriched features and tuned hyperparameters, the model improves predictive performance while preserving rare high-end listings.


Luxury and Location: Capturing Context in Housing Prices

Luxury Amenities

The weighted luxury score measures premium amenities, while interaction features contextualize it by combining the score with size, neighborhood price per m², and local population density, letting the model recognize subtle effects. For example, a sauna in a central apartment adds more value than one in a suburban mansion.

Visualizing the impact

Feature importance plots show that lifts, air conditioning, and smart systems dominate luxury scoring, while interactions with neighborhood price per m² and size amplify contextual effects, showing how location and structure jointly drive premium pricing.

These plots illustrate which amenities matter most and how context amplifies their value, turning subjective notions of luxury into measurable signals for high-end housing prices.

Geospatial and Neighborhood Features

Each property was geocoded using the geopy.geocoders API, and its distance from Amsterdam’s city center was calculated. These distances were then grouped into categorical bands of a few kilometers each to capture non-linear effects: central apartments generally command a premium, while prices drop beyond roughly 10 km.

Neighborhood amenities were quantified by counting schools, parks, hospitals, supermarkets, and public transport stops within walking or short-driving distance, using data retrieved via the overpy.Overpass API. The resulting counts were binned by density, allowing the model to capture contextual location effects: a central apartment with nearby parks and top schools scores higher than a similar-sized property farther from amenities. To avoid double-counting, raw latitude and longitude were excluded, letting derived features carry the predictive signal.

By combining weighted luxury features with context-aware geospatial variables, the model differentiates nuanced high-end signals, capturing both structural and locational drivers of value. This dual approach transforms subjective notions of desirability into measurable, actionable predictors for pricing luxury properties.


XGBoost Modeling with Early Stopping

With enriched features and log-transformed targets, I ran Optuna hyperparameter tuning, just as in Phase 3A, on an XGBoost model using early stopping. This stabilized training while preserving rare high-end listings, preventing the model from overfitting to extreme prices.

Top Features Identified

Examining feature contributions via SHAP values reveals which predictors most influence model outputs.

  • Property size (€349k SHAP) and neighborhood price per m² (€78k SHAP) remain the strongest predictors, capturing baseline value driven by scale and location.

  • Luxury score and interaction terms capture nuanced high-end signals:

    • Luxury × Price per m² (€12.9k SHAP) measures how premium amenities amplify local per-square-meter value.

    • Luxury × Size (€8.4k SHAP) accounts for the total impact of luxury in larger apartments.

    • Size per Luxury Feature (€12.6k SHAP) reflects amenity density: smaller values indicate many luxury features packed into a smaller space.
      These features help the model differentiate a small, amenity-rich central apartment from a large suburban unit with fewer perks.

  • Distance to Amsterdam city center (€12.2k SHAP) encodes centrality and non-linear effects on price.

  • Neighborhood amenity densities quantify local desirability, such as proximity to schools, parks, and transport links.

  • Traditional features like room count and energy label still matter, but their influence is now contextualized by luxury and location.

Luxury and geospatial interactions help differentiate small, amenity-rich apartments from larger suburban units, while size and neighborhood price/m² remain dominant drivers. Feature importance has shifted from last phase’s coarser proxies like postal codes to property-specific and neighborhood-level nuances, reflecting the impact of new feature engineering.

Performance Evolution: Phase 3A vs. Latest Model

Compared to Phase 3A, the updated model shows reduced overfitting: train RMSE increased slightly, while validation and test RMSE decreased. Cross-validation confirmed stable generalization.

MAPE remains below 10% across price tiers, indicating balanced performance from budget to luxury listings. MAE rose marginally due to better fitting of luxury outliers, reflecting the impact of luxury and interaction features.

Compared to Phase 3A, the updated model exhibits improved generalization: training R² decreased from 0.98 to 0.95 while validation R² rose from 0.88 to 0.92, reflecting reduced overfitting. Test R² increased from ≈ 0.81 to ≈ 0.82, confirming consistent real-world performance. R², or coefficient of determination, measures how much variance in prices the model explains - higher values indicate better fit. Together with lower validation RMSE, these results show that log-transforming targets and enriching features strengthened the model’s stability without sacrificing accuracy.


Alternative Approaches

While the current XGBoost setup performs robustly across the full spectrum, it’s important to consider alternative modeling strategies and evaluation metrics, particularly when luxury listings are rare or skew distributions

Two-Model Setup: Luxury vs. Standard

When dealing with datasets where luxury listings make up a small but distinguishable fraction (e.g., ~2% of the data), one tempting approach is to treat them as a separate class.

Concept: first train a classifier to separate luxury from standard listings, then train two separate regression models. One model for the luxury segment, one for the rest. In theory, this allows each model to focus on the specific pricing dynamics of its segment: the luxury-only model can learn high-end pricing patterns more accurately, while the standard model can specialize on the bulk of the market.

Challenges and Risks

  • Very small luxury sample: With limited luxury data, the model may struggle to learn stable patterns, leading to high variance.

  • Misclassification of luxury listings: If the classifier incorrectly labels properties, predictions from the wrong model can be severely off. This risk is amplified by the small sample size of luxury listings, where even a few misclassifications can have a disproportionate impact on overall accuracy.

  • Pipeline complexity: Implementing two separate models increases engineering overhead: data routing, separate feature transformations, and maintenance all become more complex.

  • Inconsistent predictions at segment boundaries: Properties near the luxury threshold can end up being inconsistently predicted depending on minor classifier errors.

Takeaway:

While splitting the data seems appealing conceptually, in practice the small luxury sample and added pipeline complexity introduce variance and instability. A single, robust XGBoost model with log-transformed targets and enriched features (e.g., neighborhood quality, view scores) generally delivers more consistent and reliable predictions across all segments.

Error Metric Considerations

Choosing the right error metric is crucial for stable model behavior, especially when the price range spans several orders of magnitude.
Metrics like RMSE, MAE, and MAPE differ not just numerically but in how they weight large vs. typical errors and what kind of fairness they impose across the price range.

Example Predictions (k€)

True Price (in thousands €)RMSE-optMAE-optMAPE-opt
100105102100
120125118118
130135128128
150160148149
200210198202
300350290305
1000950800950
  • RMSE-optimized models emphasize large absolute errors, staying closer to high-end listings (e.g., 950 k€ for a 1 M€ home) because the squared-error penalty forces focus on the expensive tail.

  • MAE-optimized models treat all errors equally, often underpredicting luxury properties (e.g., 800 k€) to minimize average deviation.

  • MAPE-optimized models weight percentage errors, giving stronger importance to mid- and lower-priced homes (e.g., accurately predicting 100 k€ for a 100 k€ home), but being less strict at the top end.

Aggregate Error Comparison

MetricRMSEMAEMAPE
RMSE-opt predictions150 k80 k11 %
MAE-opt predictions120 k60 k13 %
MAPE-opt predictions130 k70 k9 %

These numbers illustrate how each loss function shapes model behavior differently:

  • RMSE emphasizes large deviations, pulling predictions closer to high-end values and making the model more sensitive to outliers.

  • MAE focuses on typical (median) behavior, treating all errors equally and therefore underweighting rare extremes.

  • MAPE focuses on relative accuracy, promoting fairness across price levels but over-penalizing low-value homes.

What about Huber?

Huber loss blends MAE and RMSE, offering robustness to moderate outliers, and is sometimes used in presence of large outliers. In practice, it adds complexity and its benefits are largely redundant once we apply a log transformation to prices. For this reason, training with log-transformed targets and RMSE remains a stable and interpretable choice. Reporting MAE and MAPE alongside RMSE provides a more complete picture of performance across the price spectrum. Huber can still be explored as a secondary check if extreme outliers are expected to be particularly influential.


Takeaway

RMSE is the pragmatic, stable choice when combined with log-transformed targets.
MAE and MAPE add interpretability across price tiers, while Huber remains an optional secondary loss for robustness experiments.


Key Takeaways

Following the discussion on error metrics and model robustness, it’s worth summarizing the main insights and practical lessons from the modeling phase.

  • Log-transformed targets stabilized variance and reduced the disproportionate influence of ultra-luxury listings, allowing the model to learn consistent relationships across the full price spectrum.

  • Luxury-weighted features and interaction terms captured nuanced high-end signals, differentiating small, amenity-rich central apartments from larger suburban units.

  • Geospatial and neighborhood amenity features quantified location context, capturing the value of proximity to schools, parks, and public transport.

  • Extended feature engineering and the log transformation jointly improved validation and test RMSE compared to the previous baseline, while keeping MAE stable, demonstrating better generalization and robustness.

  • Feature importance evolved from Phase 3A to 3B: luxury interactions and geospatial attributes now drive predictions more strongly, reducing reliance on coarse proxies such as postal codes.

  • A single robust XGBoost model remains the most practical solution for datasets with a small luxury segment, avoiding instability and misclassification risk inherent in a split-model approach.

  • Multiple error metrics (RMSE, MAE, MAPE) provide a balanced performance view, highlighting both extreme and typical deviations, and ensuring interpretability for real-world deployment.


Next Steps: Serving Predictions via an API (Blog Post 5 Preview)

With a robust predictive model in place, the next phase focuses on making it actionable in production.
I’ll develop an API backend to serve live price predictions for new or scraped listings.

Goals

  • Develop a REST API for model inference

  • Integrate the scraper and model pipeline into the API

  • Provide validated, reliable predictions for any input listing

Planned Implementation

  • FastAPI Endpoints

    • /predict: Accepts a listing URL or structured feature inputs and returns a predicted price (or price range).

    • /scrape: Triggers on-demand or batch scraping of listings for prediction.

  • Input validation and error handling for robustness against incomplete or invalid data.

  • Docker containerization to simplify deployment and scaling across environments.


This next step bridges modeling and real-world application, turning the predictive model into an operational service for live listings.
With the model now capturing both structural and high-end signals, and the API pipeline about to be ready for deployment, we’re moving from analysis to action, transforming predictive power into practical, data-driven real estate insights.

About the author

  • I’m a data scientist with 4 years of experience working on real-world machine learning and analytics projects. I enjoy building end-to-end data products and sharing what I learn along the way.

No comments yet. Be the first to comment.