Lesson 8 of 9
Mini Project: Real Estate Valuation Engine with Regularized Regression
Build a production-grade automated valuation model (AVM) for residential real estate pricing. We ingest continuous and categorical property features, construct a leak-free ColumnTransformer pipeline with log-transformed targets, optimize ElasticNet regularization parameters using cross-validation, and inspect standardized feature importances.
Complete End-to-End Real Estate Valuation Engine
import pandas as pd
import numpy as np
from sklearn.model_selection import train_test_split, KFold, cross_val_score
from sklearn.compose import ColumnTransformer, TransformedTargetRegressor
from sklearn.pipeline import Pipeline
from sklearn.impute import SimpleImputer
from sklearn.preprocessing import StandardScaler, OneHotEncoder, RobustScaler
from sklearn.linear_model import ElasticNetCV
from sklearn.metrics import mean_absolute_error, root_mean_squared_error, r2_score
# 1. INGEST REAL ESTATE DATASET (Synthetic Housing Market)
np.random.seed(42)
n_houses = 2500
df_house = pd.DataFrame({
'living_sqft': np.random.normal(2100, 600, n_houses).clip(600, 6000),
'lot_sqft': np.random.exponential(8000, n_houses),
'bedrooms': np.random.choice([1, 2, 3, 4, 5], size=n_houses, p=[0.05, 0.25, 0.45, 0.20, 0.05]),
'bathrooms': np.random.choice([1.0, 1.5, 2.0, 2.5, 3.0, 3.5], size=n_houses),
'neighborhood': np.random.choice(['Downtown', 'Suburbs_North', 'Suburbs_West', 'Waterfront', 'Industrial'], size=n_houses),
'property_condition': np.random.choice(['Poor', 'Fair', 'Good', 'Excellent'], size=n_houses)
})
# Ground truth price with non-linear multipliers and lognormal noise
neighborhood_mult = {'Downtown': 1.6, 'Suburbs_North': 1.1, 'Suburbs_West': 1.0, 'Waterfront': 2.3, 'Industrial': 0.7}
base_price = (
180.0 * df_house['living_sqft']
+ 12.0 * df_house['lot_sqft']
+ 15000.0 * df_house['bedrooms']
+ 25000.0 * df_house['bathrooms']
)
price_mult = df_house['neighborhood'].map(neighborhood_mult)
df_house['price_usd'] = (base_price * price_mult * np.random.lognormal(0, 0.1, n_houses)).round(-2)
# 2. SPLIT BEFORE ANY PROCESSING
X = df_house.drop(columns=['price_usd'])
y = df_house['price_usd']
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
# 3. ATOMIC PREPROCESSING PIPELINE
preprocessor = ColumnTransformer(
transformers=[
('num', Pipeline([
('imputer', SimpleImputer(strategy='median')),
('scaler', RobustScaler())
]), ['living_sqft', 'lot_sqft', 'bedrooms', 'bathrooms']),
('cat', Pipeline([
('imputer', SimpleImputer(strategy='constant', fill_value='MISSING')),
('ohe', OneHotEncoder(drop='first', sparse_output=False, handle_unknown='ignore'))
]), ['neighborhood', 'property_condition'])
]
)
# 4. REGULARIZED REGRESSION ENGINE WITH LOG-TRANSFORMED TARGET
elastic_cv = ElasticNetCV(
l1_ratio=[0.1, 0.5, 0.7, 0.9, 0.99],
alphas=np.logspace(-3, 1, 20),
cv=5,
random_state=42,
max_iter=2000
)
# TransformedTargetRegressor applies log1p during fit and expm1 during predict automatically
avm_pipeline = Pipeline([
('preprocessor', preprocessor),
('regressor', TransformedTargetRegressor(regressor=elastic_cv, func=np.log1p, inverse_func=np.expm1))
])
# 5. TRAIN & EVALUATE
avm_pipeline.fit(X_train, y_train)
y_pred = avm_pipeline.predict(X_test)
test_mae = mean_absolute_error(y_test, y_pred)
test_rmse = root_mean_squared_error(y_test, y_pred)
test_r2 = r2_score(y_test, y_pred)
print("=== REAL ESTATE AVM TEST PERFORMANCE ===")
print(f"Test MAE : ${test_mae:,.2f}")
print(f"Test RMSE : ${test_rmse:,.2f}")
print(f"Test R^2 : {test_r2:.4f}")
# 6. INFERENCE ON LIVE PROPERTY
sample_listing = pd.DataFrame([{
'living_sqft': 2400, 'lot_sqft': 6500, 'bedrooms': 3,
'bathrooms': 2.5, 'neighborhood': 'Waterfront', 'property_condition': 'Excellent'
}])
predicted_val = avm_pipeline.predict(sample_listing)[0]
print(f"\nPredicted Valuation for Waterfront 3-Bed Listing: ${predicted_val:,.2f}")Pro Tip: Logging Target Transformed Metrics
When training with `TransformedTargetRegressor(func=np.log1p)`, always evaluate the final metrics (MAE, RMSE) in raw dollar units rather than log units. A 0.05 RMSE in log space is meaningless to business executives; reporting an MAE of $14,200 is immediately actionable.
MlHousePricePredictionProject Visual Representation
Hands-On Challenge: Build a Residual Confidence Interval
Compute the empirical 10th and 90th percentiles of percentage errors on the test set. For any new predicted house price, output a 80% valuation range: `[predicted_price * (1 - p10), predicted_price * (1 + p90)]`.
Quick Quiz & Key Concept Checks
Common Pitfall: Forgetting That Median Minimizes MAE, While Mean Minimizes MSE
If your model is trained to minimize squared error (MSE), its predictions estimate the conditional mathematical mean E[y|X]. If evaluated using MAE (which is minimized by the conditional median), the model may appear suboptimal. Match your loss function to your target evaluation metric.